Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/jest-preset/jest/mocks/RendererProxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ const {
dispatchCommand,
findHostInstance_DEPRECATED,
findNodeHandle,
flushSync,
getNodeFromInternalInstanceHandle,
getPublicInstanceFromInternalInstanceHandle,
getPublicInstanceFromRootTag,
Expand All @@ -32,6 +33,7 @@ export {
dispatchCommand,
findHostInstance_DEPRECATED,
findNodeHandle,
flushSync,
getNodeFromInternalInstanceHandle,
getPublicInstanceFromInternalInstanceHandle,
getPublicInstanceFromRootTag,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const findNodeHandle: {
componentOrHandle: ?(React.ElementRef<TElementType> | number),
): ?number,
}['findNodeHandle'] = ReactFabric.findNodeHandle;
export const flushSync = ReactFabric.flushSync;
export const sendAccessibilityEvent = ReactFabric.sendAccessibilityEvent;
export const isChildPublicInstance = ReactFabric.isChildPublicInstance;
export const getNodeFromInternalInstanceHandle =
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @fantom_flags enableFlushSync:*
* @flow strict-local
* @format
*/

import '@react-native/fantom/src/setUpDefaultReactNativeEnvironment';

import type {HostInstance} from 'react-native';

import * as ReactNativeFeatureFlags from '../../../src/private/featureflags/ReactNativeFeatureFlags';
import * as Fantom from '@react-native/fantom';
import nullthrows from 'nullthrows';
import * as React from 'react';
import {createRef, startTransition, useLayoutEffect, useState} from 'react';
import {View, unstable_flushSync as maybeFlushSync} from 'react-native';

let log: Array<string> = [];
let setN: (n: number) => void = () => {};
const counterRef = createRef<HostInstance>();

type CounterProps = {onPointerUp?: () => void};

function Counter({onPointerUp}: CounterProps): React.Node {
const [n, _setN] = useState(0);
setN = _setN;
log.push(`render:${n}`);
useLayoutEffect(() => {
log.push(`layout:${n}`);
}, [n]);
return <View ref={counterRef} onPointerUp={onPointerUp} />;
}

function renderCounter(props?: CounterProps): Fantom.Root {
const root = Fantom.createRoot();
Fantom.runTask(() => {
root.render(<Counter {...props} />);
});
expect(log).toEqual(['render:0', 'layout:0']);
log = [];
return root;
}

beforeEach(() => {
log = [];
});

(ReactNativeFeatureFlags.enableFlushSync() ? it.skip : it)(
'is not exported when enableFlushSync is disabled',
() => {
expect(maybeFlushSync).toBe(undefined);
},
);

(ReactNativeFeatureFlags.enableFlushSync() ? describe : describe.skip)(
'flushSync',
() => {
let flushSync: NonNullable<typeof maybeFlushSync>;

beforeEach(() => {
flushSync = nullthrows(maybeFlushSync);
});

it('is exported from react-native', () => {
expect(typeof maybeFlushSync).toBe('function');
});

it('flushes updates synchronously before returning', () => {
renderCounter();

Fantom.runTask(() => {
flushSync(() => setN(1));
log.push('after');
});

expect(log).toEqual(['render:1', 'layout:1', 'after']);
});

it('without flushSync, updates are deferred', () => {
renderCounter();

Fantom.runTask(() => {
setN(1);
log.push('after');
});

expect(log).toEqual(['after', 'render:1', 'layout:1']);
});

it('opts out of transitions', () => {
renderCounter();

Fantom.runTask(() => {
startTransition(() => {
flushSync(() => setN(1));
log.push('after');
});
});

expect(log).toEqual(['render:1', 'layout:1', 'after']);
});

it("returns the callback's return value", () => {
expect(flushSync(() => 42)).toBe(42);
expect(flushSync()).toBe(undefined);
});

it('propagates errors from the callback and still flushes updates', () => {
renderCounter();

Fantom.runTask(() => {
expect(() =>
flushSync(() => {
setN(1);
throw new Error('boom');
}),
).toThrow('boom');
log.push('after');
});

expect(log).toEqual(['render:1', 'layout:1', 'after']);
});

it('flushes pending sync work when called without a callback', () => {
renderCounter({
onPointerUp: () => {
setN(1);
flushSync();
log.push('after');
},
});

Fantom.dispatchNativeEvent(
nullthrows(counterRef.current),
'onPointerUp',
{x: 0, y: 0},
{category: Fantom.NativeEventCategory.Discrete},
);

expect(log).toEqual(['render:1', 'layout:1', 'after']);
});

it('warns and defers the update when called during commit', () => {
const originalConsoleError = console.error;
const consoleErrorSpy = jest.fn();
// $FlowFixMe[cannot-write]
console.error = consoleErrorSpy;
try {
let didFlush = false;
function App(): React.Node {
useLayoutEffect(() => {
if (!didFlush) {
didFlush = true;
flushSync(() => setN(1));
log.push('after');
}
});
return <Counter />;
}

const root = Fantom.createRoot();
Fantom.runTask(() => {
root.render(<App />);
});

expect(log).toEqual([
'render:0',
'layout:0',
'after',
'render:1',
'layout:1',
]);
if (__DEV__) {
expect(consoleErrorSpy).toHaveBeenCalledTimes(1);
expect(consoleErrorSpy.mock.calls[0][0]).toBe(
'flushSync was called from inside a lifecycle method. React ' +
'cannot flush when React is already rendering. Consider moving ' +
'this call to a scheduler task or micro task.',
);
} else {
expect(consoleErrorSpy).not.toHaveBeenCalled();
}
} finally {
// $FlowFixMe[cannot-write]
console.error = originalConsoleError;
}
});
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<9a675a67a9ce5e7ca443dd319e2af91a>>
* @generated SignedSource<<3a6a61e2cc2bf01a35ab5c3919462ad5>>
*/

/**
Expand Down Expand Up @@ -198,6 +198,12 @@ public object ReactNativeFeatureFlags {
@JvmStatic
public fun enableFlexboxAutoMinSizeInStrictMode(): Boolean = accessor.enableFlexboxAutoMinSizeInStrictMode()

/**
* Exposes `unstable_flushSync` from the `react-native` package, with the same semantics as `flushSync` from `react-dom`.
*/
@JvmStatic
public fun enableFlushSync(): Boolean = accessor.enableFlushSync()

/**
* When mount items are queued while MountItemDispatcher is already dispatching on Android (e.g. from a synchronous state update), dispatch them in the same frame instead of deferring them to the next one.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<6b668cbb1ef60126d7e08b2d853b1262>>
* @generated SignedSource<<fe927f4acf804e05b74dbe606e39746f>>
*/

/**
Expand Down Expand Up @@ -48,6 +48,7 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces
private var enableFabricCommitBranchingMergeOnMainThreadCache: Boolean? = null
private var enableFabricLogsCache: Boolean? = null
private var enableFlexboxAutoMinSizeInStrictModeCache: Boolean? = null
private var enableFlushSyncCache: Boolean? = null
private var enableFollowUpMountItemDispatchAndroidCache: Boolean? = null
private var enableIOSCompressedTextFrameAdjustmentCache: Boolean? = null
private var enableIOSTextBaselineOffsetPerLineCache: Boolean? = null
Expand Down Expand Up @@ -376,6 +377,15 @@ internal class ReactNativeFeatureFlagsCxxAccessor : ReactNativeFeatureFlagsAcces
return cached
}

override fun enableFlushSync(): Boolean {
var cached = enableFlushSyncCache
if (cached == null) {
cached = ReactNativeFeatureFlagsCxxInterop.enableFlushSync()
enableFlushSyncCache = cached
}
return cached
}

override fun enableFollowUpMountItemDispatchAndroid(): Boolean {
var cached = enableFollowUpMountItemDispatchAndroidCache
if (cached == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<0890a0b7979d00172b0a79abd94f6c3e>>
* @generated SignedSource<<b58702a0f594f409c0d20fd497395fde>>
*/

/**
Expand Down Expand Up @@ -84,6 +84,8 @@ public object ReactNativeFeatureFlagsCxxInterop {

@DoNotStrip @JvmStatic public external fun enableFlexboxAutoMinSizeInStrictMode(): Boolean

@DoNotStrip @JvmStatic public external fun enableFlushSync(): Boolean

@DoNotStrip @JvmStatic public external fun enableFollowUpMountItemDispatchAndroid(): Boolean

@DoNotStrip @JvmStatic public external fun enableIOSCompressedTextFrameAdjustment(): Boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<3ca183dbeeb3fdeac98780267df9dff2>>
* @generated SignedSource<<834b0e9533cbc775a1c12b86140d718d>>
*/

/**
Expand Down Expand Up @@ -79,6 +79,8 @@ public open class ReactNativeFeatureFlagsDefaults : ReactNativeFeatureFlagsProvi

override fun enableFlexboxAutoMinSizeInStrictMode(): Boolean = false

override fun enableFlushSync(): Boolean = false

override fun enableFollowUpMountItemDispatchAndroid(): Boolean = false

override fun enableIOSCompressedTextFrameAdjustment(): Boolean = false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<ba5e55492e7f521229dd62ac1274924e>>
* @generated SignedSource<<15c65d4497fd9f36f8902efb2812b3b2>>
*/

/**
Expand Down Expand Up @@ -52,6 +52,7 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc
private var enableFabricCommitBranchingMergeOnMainThreadCache: Boolean? = null
private var enableFabricLogsCache: Boolean? = null
private var enableFlexboxAutoMinSizeInStrictModeCache: Boolean? = null
private var enableFlushSyncCache: Boolean? = null
private var enableFollowUpMountItemDispatchAndroidCache: Boolean? = null
private var enableIOSCompressedTextFrameAdjustmentCache: Boolean? = null
private var enableIOSTextBaselineOffsetPerLineCache: Boolean? = null
Expand Down Expand Up @@ -408,6 +409,16 @@ internal class ReactNativeFeatureFlagsLocalAccessor : ReactNativeFeatureFlagsAcc
return cached
}

override fun enableFlushSync(): Boolean {
var cached = enableFlushSyncCache
if (cached == null) {
cached = currentProvider.enableFlushSync()
accessedFeatureFlags.add("enableFlushSync")
enableFlushSyncCache = cached
}
return cached
}

override fun enableFollowUpMountItemDispatchAndroid(): Boolean {
var cached = enableFollowUpMountItemDispatchAndroidCache
if (cached == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<8d21b1b7d2bd5c5fe3a111c0d411f742>>
* @generated SignedSource<<89f683cb28a7d1ef52c86faa96f1107c>>
*/

/**
Expand Down Expand Up @@ -79,6 +79,8 @@ public interface ReactNativeFeatureFlagsProvider {

@DoNotStrip public fun enableFlexboxAutoMinSizeInStrictMode(): Boolean

@DoNotStrip public fun enableFlushSync(): Boolean

@DoNotStrip public fun enableFollowUpMountItemDispatchAndroid(): Boolean

@DoNotStrip public fun enableIOSCompressedTextFrameAdjustment(): Boolean
Expand Down
Loading
Loading