Skip to content

Commit

Permalink
Add supportsMicrotasks to the host config (facebook#20809)
Browse files Browse the repository at this point in the history
* Add `supportsMicrotasks` to the host config

Only certain renderers support scheduling a microtask, so we need a
renderer specific flag that we can toggle. That way it's off for some
renderers and on for others.

I copied the approach we use for the other optional parts of the host
config, like persistent mode and test selectors.

Why isn't the feature flag sufficient?

The feature flag modules, confusingly, are not renderer-specific, at
least when running the our tests against the source files. They are
meant to correspond to a release channel, not a renderer, but we got
confused at some point and haven't cleaned it up.

For example, when we run `yarn test`, Jest loads the flags from the
default `ReactFeatureFlags.js` module, even when we import the React
Native renderer — but in the actual builds, we load a different feature
flag module, `ReactFeatureFlags.native-oss.js.` There's no way in our
current Jest load a different host config for each renderer, because
they all just import the same module. We should solve this by creating
separate Jest project for each renderer, so that the flags loaded when
running against source are the same ones that we use in the
compiled bundles.

The feature flag (`enableDiscreteMicrotasks`) still exists — it's used
to set the React DOM host config's `supportsMicrotasks` flag to `true`.
(Same for React Noop) The important part is that turning on the feature
flag does *not* affect the other renderers, like React Native.

The host config will likely outlive the feature flag, too, since the
feature flag only exists so we can gradually roll it out and measure the
impact in production; once we do, we'll remove it. Whereas the host
config flag may continue to be used to disable the discrete microtask
behavior for RN, because RN will likely use a native (non-JavaScript)
API to schedule its tasks.

* Add `supportsMicrotask` to react-reconciler README
  • Loading branch information
acdlite authored and koto committed Jun 15, 2021
1 parent b9ed6a0 commit c466ce9
Show file tree
Hide file tree
Showing 12 changed files with 62 additions and 34 deletions.
4 changes: 1 addition & 3 deletions packages/react-art/src/ReactARTHostConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,7 @@ export * from 'react-reconciler/src/ReactFiberHostConfigWithNoPersistence';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoHydration';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoScopes';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoTestSelectors';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoMicrotasks';

export function appendInitialChild(parentInstance, child) {
if (typeof child === 'string') {
Expand Down Expand Up @@ -338,9 +339,6 @@ export function getChildHostContext() {
export const scheduleTimeout = setTimeout;
export const cancelTimeout = clearTimeout;
export const noTimeout = -1;
export function scheduleMicrotask(callback: Function) {
invariant(false, 'Not implemented.');
}

export function shouldSetTextContent(type, props) {
return (
Expand Down
6 changes: 6 additions & 0 deletions packages/react-dom/src/client/ReactDOMHostConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import {
enableCreateEventHandleAPI,
enableScopeAPI,
enableNewReconciler,
enableDiscreteEventMicroTasks,
} from 'shared/ReactFeatureFlags';
import {HostComponent, HostText} from 'react-reconciler/src/ReactWorkTags';
import {listenToAllSupportedEvents} from '../events/DOMPluginEventSystem';
Expand Down Expand Up @@ -399,6 +400,11 @@ export const scheduleTimeout: any =
export const cancelTimeout: any =
typeof clearTimeout === 'function' ? clearTimeout : (undefined: any);
export const noTimeout = -1;

// -------------------
// Microtasks
// -------------------
export const supportsMicrotasks = enableDiscreteEventMicroTasks;
export const scheduleMicrotask: any =
typeof queueMicrotask === 'function'
? queueMicrotask
Expand Down
4 changes: 1 addition & 3 deletions packages/react-native-renderer/src/ReactFabricHostConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,7 @@ export * from 'react-reconciler/src/ReactFiberHostConfigWithNoMutation';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoHydration';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoScopes';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoTestSelectors';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoMicrotasks';

export function appendInitialChild(
parentInstance: Instance,
Expand Down Expand Up @@ -360,9 +361,6 @@ export const warnsIfNotActing = false;
export const scheduleTimeout = setTimeout;
export const cancelTimeout = clearTimeout;
export const noTimeout = -1;
export function scheduleMicrotask(callback: Function) {
invariant(false, 'Not implemented.');
}

// -------------------
// Persistence
Expand Down
4 changes: 1 addition & 3 deletions packages/react-native-renderer/src/ReactNativeHostConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ export * from 'react-reconciler/src/ReactFiberHostConfigWithNoPersistence';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoHydration';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoScopes';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoTestSelectors';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoMicrotasks';

export function appendInitialChild(
parentInstance: Instance,
Expand Down Expand Up @@ -255,9 +256,6 @@ export const warnsIfNotActing = true;
export const scheduleTimeout = setTimeout;
export const cancelTimeout = clearTimeout;
export const noTimeout = -1;
export function scheduleMicrotask(callback: Function) {
invariant(false, 'Not implemented.');
}

export function shouldSetTextContent(type: string, props: Props): boolean {
// TODO (bvaughn) Revisit this decision.
Expand Down
7 changes: 6 additions & 1 deletion packages/react-noop-renderer/src/createReactNoop.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ import {
LegacyRoot,
} from 'react-reconciler/src/ReactRootTags';

import {enableNativeEventPriorityInference} from 'shared/ReactFeatureFlags';
import {
enableNativeEventPriorityInference,
enableDiscreteEventMicroTasks,
} from 'shared/ReactFeatureFlags';
import ReactSharedInternals from 'shared/ReactSharedInternals';
import enqueueTask from 'shared/enqueueTask';
const {IsSomeRendererActing} = ReactSharedInternals;
Expand Down Expand Up @@ -372,6 +375,8 @@ function createReactNoop(reconciler: Function, useMutation: boolean) {
scheduleTimeout: setTimeout,
cancelTimeout: clearTimeout,
noTimeout: -1,

supportsMicrotasks: enableDiscreteEventMicroTasks,
scheduleMicrotask:
typeof queueMicrotask === 'function'
? queueMicrotask
Expand Down
5 changes: 4 additions & 1 deletion packages/react-reconciler/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -203,9 +203,12 @@ You can proxy this to `clearTimeout` or its equivalent in your environment.

This is a property (not a function) that should be set to something that can never be a valid timeout ID. For example, you can set it to `-1`.

#### `supportsMicrotask`

Set this to true to indicate that your renderer supports `scheduleMicrotask`. We use microtasks as part of our discrete event implementation in React DOM. If you're not sure if your renderer should support this, you probably should. The option to not implement `scheduleMicrotask` exists so that platforms with more control over user events, like React Native, can choose to use a different mechanism.
#### `scheduleMicrotask(fn)`

You can proxy this to `queueMicrotask` or its equivalent in your environment.
Optional. You can proxy this to `queueMicrotask` or its equivalent in your environment.

#### `isPrimaryRenderer`

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/

import invariant from 'shared/invariant';

// Renderers that don't support microtasks
// can re-export everything from this module.

function shim(...args: any) {
invariant(
false,
'The current renderer does not support microtasks. ' +
'This error is likely caused by a bug in React. ' +
'Please file an issue.',
);
}

// Test selectors (when unsupported)
export const supportsMicrotasks = false;
export const scheduleMicrotask = shim;
6 changes: 3 additions & 3 deletions packages/react-reconciler/src/ReactFiberWorkLoop.new.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,9 @@ import {
warnsIfNotActing,
afterActiveInstanceBlur,
clearContainer,
scheduleMicrotask,
getCurrentEventPriority,
supportsMicrotasks,
scheduleMicrotask,
} from './ReactFiberHostConfig';

import {
Expand Down Expand Up @@ -219,7 +220,6 @@ import {
syncNestedUpdateFlag,
} from './ReactProfilerTimer.new';

import {enableDiscreteEventMicroTasks} from 'shared/ReactFeatureFlags';
// DEV stuff
import getComponentName from 'shared/getComponentName';
import ReactStrictModeWarnings from './ReactStrictModeWarnings.new';
Expand Down Expand Up @@ -756,7 +756,7 @@ function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
performSyncWorkOnRoot.bind(null, root),
);
} else if (
enableDiscreteEventMicroTasks &&
supportsMicrotasks &&
newCallbackPriority === InputDiscreteLanePriority
) {
scheduleMicrotask(performSyncWorkOnRoot.bind(null, root));
Expand Down
6 changes: 3 additions & 3 deletions packages/react-reconciler/src/ReactFiberWorkLoop.old.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,9 @@ import {
warnsIfNotActing,
afterActiveInstanceBlur,
clearContainer,
scheduleMicrotask,
getCurrentEventPriority,
supportsMicrotasks,
scheduleMicrotask,
} from './ReactFiberHostConfig';

import {
Expand Down Expand Up @@ -219,7 +220,6 @@ import {
syncNestedUpdateFlag,
} from './ReactProfilerTimer.old';

import {enableDiscreteEventMicroTasks} from 'shared/ReactFeatureFlags';
// DEV stuff
import getComponentName from 'shared/getComponentName';
import ReactStrictModeWarnings from './ReactStrictModeWarnings.old';
Expand Down Expand Up @@ -756,7 +756,7 @@ function ensureRootIsScheduled(root: FiberRoot, currentTime: number) {
performSyncWorkOnRoot.bind(null, root),
);
} else if (
enableDiscreteEventMicroTasks &&
supportsMicrotasks &&
newCallbackPriority === InputDiscreteLanePriority
) {
scheduleMicrotask(performSyncWorkOnRoot.bind(null, root));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export const shouldSetTextContent = $$$hostConfig.shouldSetTextContent;
export const createTextInstance = $$$hostConfig.createTextInstance;
export const scheduleTimeout = $$$hostConfig.scheduleTimeout;
export const cancelTimeout = $$$hostConfig.cancelTimeout;
export const scheduleMicrotask = $$$hostConfig.scheduleMicrotask;
export const noTimeout = $$$hostConfig.noTimeout;
export const now = $$$hostConfig.now;
export const isPrimaryRenderer = $$$hostConfig.isPrimaryRenderer;
Expand All @@ -75,6 +74,13 @@ export const prepareScopeUpdate = $$$hostConfig.preparePortalMount;
export const getInstanceFromScope = $$$hostConfig.getInstanceFromScope;
export const getCurrentEventPriority = $$$hostConfig.getCurrentEventPriority;

// -------------------
// Microtasks
// (optional)
// -------------------
export const supportsMicrotasks = $$$hostConfig.supportsMicrotasks;
export const scheduleMicrotask = $$$hostConfig.scheduleMicrotask;

// -------------------
// Test selectors
// (optional)
Expand Down
17 changes: 2 additions & 15 deletions packages/react-test-renderer/src/ReactTestHostConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export type RendererInspectionConfig = $ReadOnly<{||}>;
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoPersistence';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoHydration';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoTestSelectors';
export * from 'react-reconciler/src/ReactFiberHostConfigWithNoMicrotasks';

const NO_CONTEXT = {};
const UPDATE_SIGNAL = {};
Expand Down Expand Up @@ -230,21 +231,7 @@ export const warnsIfNotActing = true;

export const scheduleTimeout = setTimeout;
export const cancelTimeout = clearTimeout;
export const scheduleMicrotask =
typeof queueMicrotask === 'function'
? queueMicrotask
: typeof Promise !== 'undefined'
? (callback: Function) =>
Promise.resolve(null)
.then(callback)
.catch(handleErrorInNextTick)
: scheduleTimeout; // TODO: Determine the best fallback here.

function handleErrorInNextTick(error) {
setTimeout(() => {
throw error;
});
}

export const noTimeout = -1;

// -------------------
Expand Down
3 changes: 2 additions & 1 deletion scripts/error-codes/codes.json
Original file line number Diff line number Diff line change
Expand Up @@ -373,5 +373,6 @@
"382": "This query has received more parameters than the last time the same query was used. Always pass the exact number of parameters that the query needs.",
"383": "This query has received fewer parameters than the last time the same query was used. Always pass the exact number of parameters that the query needs.",
"384": "Refreshing the cache is not supported in Server Components.",
"385": "A mutable source was mutated while the %s component was rendering. This is not supported. Move any mutations into event handlers or effects."
"385": "A mutable source was mutated while the %s component was rendering. This is not supported. Move any mutations into event handlers or effects.",
"386": "The current renderer does not support microtasks. This error is likely caused by a bug in React. Please file an issue."
}

0 comments on commit c466ce9

Please sign in to comment.