@preact/signals-react 1.3.2 → 1.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,361 @@
1
+ import {
2
+ // @ts-ignore-next-line
3
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
4
+ __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED as ReactInternals,
5
+ } from "react";
6
+ import React from "react";
7
+ import jsxRuntime from "react/jsx-runtime";
8
+ import jsxRuntimeDev from "react/jsx-dev-runtime";
9
+ import { useSignals, wrapJsx } from "./index";
10
+
11
+ export interface ReactDispatcher {
12
+ useRef: typeof React.useRef;
13
+ useCallback: typeof React.useCallback;
14
+ useReducer: typeof React.useReducer;
15
+ useSyncExternalStore: typeof React.useSyncExternalStore;
16
+ useEffect: typeof React.useEffect;
17
+ useImperativeHandle: typeof React.useImperativeHandle;
18
+ }
19
+
20
+ // In order for signals to work in React, we need to observe what signals a
21
+ // component uses while rendering. To do this, we need to know when a component
22
+ // is rendering. To do this, we watch the transition of the
23
+ // ReactCurrentDispatcher to know when a component is rerendering.
24
+ //
25
+ // To track when we are entering and exiting a component render (i.e. before and
26
+ // after React renders a component), we track how the dispatcher changes.
27
+ // Outside of a component rendering, the dispatcher is set to an instance that
28
+ // errors or warns when any hooks are called. This behavior is prevents hooks
29
+ // from being used outside of components. Right before React renders a
30
+ // component, the dispatcher is set to an instance that doesn't warn or error
31
+ // and contains the implementations of all hooks. Right after React finishes
32
+ // rendering a component, the dispatcher is set to the erroring one again. This
33
+ // erroring dispatcher is called the `ContextOnlyDispatcher` in React's source.
34
+ //
35
+ // So, we watch the getter and setter on `ReactCurrentDispatcher.current` to
36
+ // monitor the changes to the current ReactDispatcher. When the dispatcher
37
+ // changes from the ContextOnlyDispatcher to a "valid" dispatcher, we assume we
38
+ // are entering a component render. At this point, we setup our
39
+ // auto-subscriptions for any signals used in the component. We do this by
40
+ // creating an Signal effect and manually starting the Signal effect. We use
41
+ // `useSyncExternalStore` to trigger rerenders on the component when any signals
42
+ // it uses changes.
43
+ //
44
+ // When the dispatcher changes from a valid dispatcher back to the
45
+ // ContextOnlyDispatcher, we assume we are exiting a component render. At this
46
+ // point we stop the effect.
47
+ //
48
+ // Some additional complexities to be aware of:
49
+ // - If a component calls `setState` while rendering, React will re-render the
50
+ // component immediately. Before triggering the re-render, React will change
51
+ // the dispatcher to the HooksDispatcherOnRerender. When we transition to this
52
+ // rerendering adapter, we need to re-trigger our hooks to keep the order of
53
+ // hooks the same for every render of a component.
54
+ //
55
+ // - In development, useReducer, useState, and useMemo change the dispatcher to
56
+ // a different warning dispatcher (not ContextOnlyDispatcher) before invoking
57
+ // the reducer and resets it right after.
58
+ //
59
+ // The useSyncExternalStore shim will use some of these hooks when we invoke
60
+ // it while entering a component render. We need to prevent this dispatcher
61
+ // change caused by these hooks from re-triggering our entering logic (it
62
+ // would cause an infinite loop if we did not). We do this by using a lock to
63
+ // prevent the setter from running while we are in the setter.
64
+ //
65
+ // When a Component's function body invokes useReducer, useState, or useMemo,
66
+ // this change in dispatcher should not signal that we are entering or exiting
67
+ // a component render. We ignore this change by detecting these dispatchers as
68
+ // different from ContextOnlyDispatcher and other valid dispatchers.
69
+ //
70
+ // - The `use` hook will change the dispatcher to from a valid update dispatcher
71
+ // to a valid mount dispatcher in some cases. Similarly to useReducer
72
+ // mentioned above, we should not signal that we are exiting a component
73
+ // during this change. Because these other valid dispatchers do not pass the
74
+ // ContextOnlyDispatcher check, they do not affect our logic.
75
+ //
76
+ // - When server rendering, React does not change the dispatcher before and
77
+ // after each component render. It sets it once for before the first render
78
+ // and once for after the last render. This means that we will not be able to
79
+ // detect when we are entering or exiting a component render. This is fine
80
+ // because we don't need to detect this for server rendering. A component
81
+ // can't trigger async rerenders in SSR so we don't need to track signals.
82
+ //
83
+ // If a component updates a signal value while rendering during SSR, we will
84
+ // not rerender the component because the signal value will synchronously
85
+ // change so all reads of the signal further down the tree will see the new
86
+ // value.
87
+
88
+ /*
89
+ Below is a state machine definition for transitions between the various
90
+ dispatchers in React's prod build. (It does not include dev time warning
91
+ dispatchers which are just always ignored).
92
+
93
+ ENTER and EXIT suffixes indicates whether this ReactCurrentDispatcher transition
94
+ signals we are entering or exiting a component render, or if it doesn't signal a
95
+ change in the component rendering lifecyle (NOOP).
96
+
97
+ ```js
98
+ // Paste this into https://stately.ai/viz to visualize the state machine.
99
+ import { createMachine } from "xstate";
100
+
101
+ // ENTER, EXIT, NOOP suffixes indicates whether this ReactCurrentDispatcher
102
+ // transition signals we are entering or exiting a component render, or
103
+ // if it doesn't signal a change in the component rendering lifecyle (NOOP).
104
+
105
+ const dispatcherMachinePROD = createMachine({
106
+ id: "ReactCurrentDispatcher_PROD",
107
+ initial: "null",
108
+ states: {
109
+ null: {
110
+ on: {
111
+ pushDispatcher: "ContextOnlyDispatcher",
112
+ },
113
+ },
114
+ ContextOnlyDispatcher: {
115
+ on: {
116
+ renderWithHooks_Mount_ENTER: "HooksDispatcherOnMount",
117
+ renderWithHooks_Update_ENTER: "HooksDispatcherOnUpdate",
118
+ pushDispatcher_NOOP: "ContextOnlyDispatcher",
119
+ popDispatcher_NOOP: "ContextOnlyDispatcher",
120
+ },
121
+ },
122
+ HooksDispatcherOnMount: {
123
+ on: {
124
+ renderWithHooksAgain_ENTER: "HooksDispatcherOnRerender",
125
+ resetHooksAfterThrow_EXIT: "ContextOnlyDispatcher",
126
+ finishRenderingHooks_EXIT: "ContextOnlyDispatcher",
127
+ },
128
+ },
129
+ HooksDispatcherOnUpdate: {
130
+ on: {
131
+ renderWithHooksAgain_ENTER: "HooksDispatcherOnRerender",
132
+ resetHooksAfterThrow_EXIT: "ContextOnlyDispatcher",
133
+ finishRenderingHooks_EXIT: "ContextOnlyDispatcher",
134
+ use_ResumeSuspensedMount_NOOP: "HooksDispatcherOnMount",
135
+ },
136
+ },
137
+ HooksDispatcherOnRerender: {
138
+ on: {
139
+ renderWithHooksAgain_ENTER: "HooksDispatcherOnRerender",
140
+ resetHooksAfterThrow_EXIT: "ContextOnlyDispatcher",
141
+ finishRenderingHooks_EXIT: "ContextOnlyDispatcher",
142
+ },
143
+ },
144
+ },
145
+ });
146
+ ```
147
+ */
148
+
149
+ let stopTracking: (() => void) | null = null;
150
+ let lock = false;
151
+ let currentDispatcher: ReactDispatcher | null = null;
152
+
153
+ function installCurrentDispatcherHook() {
154
+ Object.defineProperty(ReactInternals.ReactCurrentDispatcher, "current", {
155
+ get() {
156
+ return currentDispatcher;
157
+ },
158
+ set(nextDispatcher: ReactDispatcher) {
159
+ if (lock) {
160
+ currentDispatcher = nextDispatcher;
161
+ return;
162
+ }
163
+
164
+ const currentDispatcherType = getDispatcherType(currentDispatcher);
165
+ const nextDispatcherType = getDispatcherType(nextDispatcher);
166
+
167
+ // Update the current dispatcher now so the hooks inside of the
168
+ // useSyncExternalStore shim get the right dispatcher.
169
+ currentDispatcher = nextDispatcher;
170
+ if (
171
+ isEnteringComponentRender(currentDispatcherType, nextDispatcherType)
172
+ ) {
173
+ lock = true;
174
+ stopTracking = useSignals();
175
+ lock = false;
176
+ } else if (
177
+ isExitingComponentRender(currentDispatcherType, nextDispatcherType)
178
+ ) {
179
+ stopTracking?.();
180
+ }
181
+ },
182
+ });
183
+ }
184
+
185
+ type DispatcherType = number;
186
+ const ContextOnlyDispatcherType = 1 << 0;
187
+ const WarningDispatcherType = 1 << 1;
188
+ const MountDispatcherType = 1 << 2;
189
+ const UpdateDispatcherType = 1 << 3;
190
+ const RerenderDispatcherType = 1 << 4;
191
+ const ServerDispatcherType = 1 << 5;
192
+ const BrowserClientDispatcherType =
193
+ MountDispatcherType | UpdateDispatcherType | RerenderDispatcherType;
194
+
195
+ const dispatcherTypeCache = new Map<ReactDispatcher, DispatcherType>();
196
+ function getDispatcherType(dispatcher: ReactDispatcher | null): DispatcherType {
197
+ // Treat null the same as the ContextOnlyDispatcher.
198
+ if (!dispatcher) return ContextOnlyDispatcherType;
199
+
200
+ const cached = dispatcherTypeCache.get(dispatcher);
201
+ if (cached !== undefined) return cached;
202
+
203
+ // The ContextOnlyDispatcher sets all the hook implementations to a function
204
+ // that takes no arguments and throws and error. This dispatcher is the only
205
+ // dispatcher where useReducer and useEffect will have the same
206
+ // implementation.
207
+ let type: DispatcherType;
208
+ const useCallbackImpl = dispatcher.useCallback.toString();
209
+ if (dispatcher.useReducer === dispatcher.useEffect) {
210
+ type = ContextOnlyDispatcherType;
211
+
212
+ // @ts-expect-error When server rendering, useEffect and useImperativeHandle
213
+ // are both set to noop functions and so have the same implementation.
214
+ } else if (dispatcher.useEffect === dispatcher.useImperativeHandle) {
215
+ type = ServerDispatcherType;
216
+ } else if (/Invalid/.test(useCallbackImpl)) {
217
+ // We first check for warning dispatchers because they would also pass some
218
+ // of the checks below.
219
+ type = WarningDispatcherType;
220
+ } else if (
221
+ // The development mount dispatcher invokes a function called
222
+ // `mountCallback` whereas the development update/re-render dispatcher
223
+ // invokes a function called `updateCallback`. Use that difference to
224
+ // determine if we are in a mount or update-like dispatcher in development.
225
+ // The production mount dispatcher defines an array of the form [callback,
226
+ // deps] whereas update/re-render dispatchers read the array using array
227
+ // indices (e.g. `[0]` and `[1]`). Use those differences to determine if we
228
+ // are in a mount or update-like dispatcher in production.
229
+ /updateCallback/.test(useCallbackImpl) ||
230
+ (/\[0\]/.test(useCallbackImpl) && /\[1\]/.test(useCallbackImpl))
231
+ ) {
232
+ // The update and rerender dispatchers have different implementations for
233
+ // useReducer. We'll check it's implementation to determine if this is the
234
+ // rerender or update dispatcher.
235
+ let useReducerImpl = dispatcher.useReducer.toString();
236
+ if (
237
+ // The development rerender dispatcher invokes a function called
238
+ // `rerenderReducer` whereas the update dispatcher invokes a function
239
+ // called `updateReducer`. The production rerender dispatcher returns an
240
+ // array of the form `[state, dispatch]` whereas the update dispatcher
241
+ // returns an array of `[fiber.memoizedState, dispatch]` so we check the
242
+ // return statement in the implementation of useReducer to differentiate
243
+ // between the two.
244
+ /rerenderReducer/.test(useReducerImpl) ||
245
+ /return\s*\[\w+,/.test(useReducerImpl)
246
+ ) {
247
+ type = RerenderDispatcherType;
248
+ } else {
249
+ type = UpdateDispatcherType;
250
+ }
251
+ } else {
252
+ type = MountDispatcherType;
253
+ }
254
+
255
+ dispatcherTypeCache.set(dispatcher, type);
256
+ return type;
257
+ }
258
+
259
+ function isEnteringComponentRender(
260
+ currentDispatcherType: DispatcherType,
261
+ nextDispatcherType: DispatcherType
262
+ ): boolean {
263
+ if (
264
+ currentDispatcherType & ContextOnlyDispatcherType &&
265
+ nextDispatcherType & BrowserClientDispatcherType
266
+ ) {
267
+ // ## Mount or update (ContextOnlyDispatcher -> ValidDispatcher (Mount or Update))
268
+ //
269
+ // If the current dispatcher is the ContextOnlyDispatcher and the next
270
+ // dispatcher is a valid dispatcher, we are entering a component render.
271
+ return true;
272
+ } else if (
273
+ currentDispatcherType & WarningDispatcherType ||
274
+ nextDispatcherType & WarningDispatcherType
275
+ ) {
276
+ // ## Warning dispatcher
277
+ //
278
+ // If the current dispatcher or next dispatcher is an warning dispatcher,
279
+ // we are not entering a component render. The current warning dispatchers
280
+ // are used to warn when hooks are nested improperly and do not indicate
281
+ // entering a new component render.
282
+ return false;
283
+ } else if (nextDispatcherType & RerenderDispatcherType) {
284
+ // Any transition into the rerender dispatcher is the beginning of a
285
+ // component render, so we should invoke our hooks. Details below.
286
+ //
287
+ // ## In-place rerendering (e.g. Mount -> Rerender)
288
+ //
289
+ // If we are transitioning from the mount, update, or rerender dispatcher to
290
+ // the rerender dispatcher (e.g. HooksDispatcherOnMount to
291
+ // HooksDispatcherOnRerender), then this component is rerendering due to
292
+ // calling setState inside of its function body. We are re-entering a
293
+ // component's render method and so we should re-invoke our hooks.
294
+ return true;
295
+ } else {
296
+ // ## Resuming suspended mount edge case (Update -> Mount)
297
+ //
298
+ // If we are transitioning from the update dispatcher to the mount
299
+ // dispatcher, then this component is using the `use` hook and is resuming
300
+ // from a mount. We should not re-invoke our hooks in this situation since
301
+ // we are not entering a new component render, but instead continuing a
302
+ // previous render.
303
+ //
304
+ // ## Other transitions
305
+ //
306
+ // For example, Mount -> Mount, Update -> Update, Mount -> Update, any
307
+ // transition in and out of invalid dispatchers.
308
+ //
309
+ // There is no known transition for the following transitions so we default
310
+ // to not triggering a re-enter of the component.
311
+ // - HooksDispatcherOnMount -> HooksDispatcherOnMount
312
+ // - HooksDispatcherOnMount -> HooksDispatcherOnUpdate
313
+ // - HooksDispatcherOnUpdate -> HooksDispatcherOnUpdate
314
+ return false;
315
+ }
316
+ }
317
+
318
+ /**
319
+ * We are exiting a component render if the current dispatcher is a valid
320
+ * dispatcher and the next dispatcher is the ContextOnlyDispatcher.
321
+ */
322
+ function isExitingComponentRender(
323
+ currentDispatcherType: DispatcherType,
324
+ nextDispatcherType: DispatcherType
325
+ ): boolean {
326
+ return Boolean(
327
+ currentDispatcherType & BrowserClientDispatcherType &&
328
+ nextDispatcherType & ContextOnlyDispatcherType
329
+ );
330
+ }
331
+
332
+ interface JsxRuntimeModule {
333
+ jsx?(type: any, ...rest: any[]): unknown;
334
+ jsxs?(type: any, ...rest: any[]): unknown;
335
+ jsxDEV?(type: any, ...rest: any[]): unknown;
336
+ }
337
+
338
+ export function installJSXHooks() {
339
+ const JsxPro: JsxRuntimeModule = jsxRuntime;
340
+ const JsxDev: JsxRuntimeModule = jsxRuntimeDev;
341
+
342
+ /**
343
+ * createElement _may_ be called by jsx runtime as a fallback in certain cases,
344
+ * so we need to wrap it regardless.
345
+ *
346
+ * The jsx exports depend on the `NODE_ENV` var to ensure the users' bundler doesn't
347
+ * include both, so one of them will be set with `undefined` values.
348
+ */
349
+ React.createElement = wrapJsx(React.createElement);
350
+ JsxDev.jsx && /* */ (JsxDev.jsx = wrapJsx(JsxDev.jsx));
351
+ JsxPro.jsx && /* */ (JsxPro.jsx = wrapJsx(JsxPro.jsx));
352
+ JsxDev.jsxs && /* */ (JsxDev.jsxs = wrapJsx(JsxDev.jsxs));
353
+ JsxPro.jsxs && /* */ (JsxPro.jsxs = wrapJsx(JsxPro.jsxs));
354
+ JsxDev.jsxDEV && /**/ (JsxDev.jsxDEV = wrapJsx(JsxDev.jsxDEV));
355
+ JsxPro.jsxDEV && /**/ (JsxPro.jsxDEV = wrapJsx(JsxPro.jsxDEV));
356
+ }
357
+
358
+ export function installAutoSignalTracking() {
359
+ installCurrentDispatcherHook();
360
+ installJSXHooks();
361
+ }
@@ -0,0 +1,158 @@
1
+ import { signal, computed, effect, Signal } from "@preact/signals-core";
2
+ import { useRef, useMemo, useEffect } from "react";
3
+ import { useSyncExternalStore } from "use-sync-external-store/shim/index.js";
4
+
5
+ export { installAutoSignalTracking } from "./auto";
6
+
7
+ const Empty = [] as const;
8
+ const ReactElemType = Symbol.for("react.element"); // https://github.com/facebook/react/blob/346c7d4c43a0717302d446da9e7423a8e28d8996/packages/shared/ReactSymbols.js#L15
9
+
10
+ export function wrapJsx<T>(jsx: T): T {
11
+ if (typeof jsx !== "function") return jsx;
12
+
13
+ return function (type: any, props: any, ...rest: any[]) {
14
+ if (typeof type === "string" && props) {
15
+ for (let i in props) {
16
+ let v = props[i];
17
+ if (i !== "children" && v instanceof Signal) {
18
+ props[i] = v.value;
19
+ }
20
+ }
21
+ }
22
+
23
+ return jsx.call(jsx, type, props, ...rest);
24
+ } as any as T;
25
+ }
26
+
27
+ interface Effect {
28
+ _sources: object | undefined;
29
+ _start(): () => void;
30
+ _callback(): void;
31
+ _dispose(): void;
32
+ }
33
+
34
+ interface EffectStore {
35
+ updater: Effect;
36
+ subscribe(onStoreChange: () => void): () => void;
37
+ getSnapshot(): number;
38
+ }
39
+
40
+ /**
41
+ * A redux-like store whose store value is a positive 32bit integer (a 'version').
42
+ *
43
+ * React subscribes to this store and gets a snapshot of the current 'version',
44
+ * whenever the 'version' changes, we tell React it's time to update the component (call 'onStoreChange').
45
+ *
46
+ * How we achieve this is by creating a binding with an 'effect', when the `effect._callback' is called,
47
+ * we update our store version and tell React to re-render the component ([1] We don't really care when/how React does it).
48
+ *
49
+ * [1]
50
+ * @see https://react.dev/reference/react/useSyncExternalStore
51
+ * @see https://github.com/reactjs/rfcs/blob/main/text/0214-use-sync-external-store.md
52
+ */
53
+ function createEffectStore(): EffectStore {
54
+ let updater!: Effect;
55
+ let version = 0;
56
+ let onChangeNotifyReact: (() => void) | undefined;
57
+
58
+ let unsubscribe = effect(function (this: Effect) {
59
+ updater = this;
60
+ });
61
+ updater._callback = function () {
62
+ version = (version + 1) | 0;
63
+ if (onChangeNotifyReact) onChangeNotifyReact();
64
+ };
65
+
66
+ return {
67
+ updater,
68
+ subscribe(onStoreChange) {
69
+ onChangeNotifyReact = onStoreChange;
70
+
71
+ return function () {
72
+ /**
73
+ * Rotate to next version when unsubscribing to ensure that components are re-run
74
+ * when subscribing again.
75
+ *
76
+ * In StrictMode, 'memo'-ed components seem to keep a stale snapshot version, so
77
+ * don't re-run after subscribing again if the version is the same as last time.
78
+ *
79
+ * Because we unsubscribe from the effect, the version may not change. We simply
80
+ * set a new initial version in case of stale snapshots here.
81
+ */
82
+ version = (version + 1) | 0;
83
+ onChangeNotifyReact = undefined;
84
+ unsubscribe();
85
+ };
86
+ },
87
+ getSnapshot() {
88
+ return version;
89
+ },
90
+ };
91
+ }
92
+
93
+ let finishUpdate: (() => void) | undefined;
94
+
95
+ function setCurrentUpdater(updater?: Effect) {
96
+ // end tracking for the current update:
97
+ if (finishUpdate) finishUpdate();
98
+ // start tracking the new update:
99
+ finishUpdate = updater && updater._start();
100
+ }
101
+
102
+ const clearCurrentUpdater = () => setCurrentUpdater();
103
+
104
+ /**
105
+ * Custom hook to create the effect to track signals used during render and
106
+ * subscribe to changes to rerender the component when the signals change
107
+ */
108
+ export function useSignals(): () => void {
109
+ const storeRef = useRef<EffectStore>();
110
+ if (storeRef.current == null) {
111
+ storeRef.current = createEffectStore();
112
+ }
113
+
114
+ const store = storeRef.current;
115
+ useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
116
+ setCurrentUpdater(store.updater);
117
+
118
+ return clearCurrentUpdater;
119
+ }
120
+
121
+ /**
122
+ * A wrapper component that renders a Signal's value directly as a Text node.
123
+ */
124
+ function Text({ data }: { data: Signal }) {
125
+ return data.value;
126
+ }
127
+
128
+ // Decorate Signals so React renders them as <Text> components.
129
+ Object.defineProperties(Signal.prototype, {
130
+ $$typeof: { configurable: true, value: ReactElemType },
131
+ type: { configurable: true, value: Text },
132
+ props: {
133
+ configurable: true,
134
+ get() {
135
+ return { data: this };
136
+ },
137
+ },
138
+ ref: { configurable: true, value: null },
139
+ });
140
+
141
+ export function useSignal<T>(value: T) {
142
+ return useMemo(() => signal<T>(value), Empty);
143
+ }
144
+
145
+ export function useComputed<T>(compute: () => T) {
146
+ const $compute = useRef(compute);
147
+ $compute.current = compute;
148
+ return useMemo(() => computed<T>(() => $compute.current()), Empty);
149
+ }
150
+
151
+ export function useSignalEffect(cb: () => void | (() => void)) {
152
+ const callback = useRef(cb);
153
+ callback.current = cb;
154
+
155
+ useEffect(() => {
156
+ return effect(() => callback.current());
157
+ }, Empty);
158
+ }