kiss-for-react 1.1.0 → 2.0.1
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.
- package/README.md +699 -156
- package/lib/cjs/ClassPersistor.js +177 -112
- package/lib/cjs/Esserializer/DeserializationOptions.js +4 -4
- package/lib/cjs/Esserializer/SerializeOptions.js +4 -4
- package/lib/cjs/Esserializer/builtins.js +258 -0
- package/lib/cjs/Esserializer/constant.js +39 -131
- package/lib/cjs/Esserializer/deserializer.js +293 -313
- package/lib/cjs/Esserializer/general.js +91 -39
- package/lib/cjs/Esserializer/index.js +47 -43
- package/lib/cjs/Esserializer/serializer.js +168 -133
- package/lib/cjs/Evt.js +132 -0
- package/lib/cjs/Hooks.js +1474 -969
- package/lib/cjs/KissAction.js +4762 -1333
- package/lib/cjs/LoadPages.js +336 -0
- package/lib/cjs/Persistor.js +189 -120
- package/lib/cjs/ProcessPersistence.js +579 -262
- package/lib/cjs/Store.js +4342 -1534
- package/lib/cjs/StoreException.js +162 -75
- package/lib/cjs/StoreProvider.js +166 -0
- package/lib/cjs/UserException.js +212 -218
- package/lib/cjs/Wait.js +309 -309
- package/lib/cjs/index.js +69 -42
- package/lib/cjs/server.js +54 -0
- package/lib/cjs/types/ClassPersistor.d.ts +143 -112
- package/lib/cjs/types/ClassPersistor.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts +13 -6
- package/lib/cjs/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/SerializeOptions.d.ts +11 -5
- package/lib/cjs/types/Esserializer/SerializeOptions.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/builtins.d.ts +36 -0
- package/lib/cjs/types/Esserializer/builtins.d.ts.map +1 -0
- package/lib/cjs/types/Esserializer/constant.d.ts +25 -49
- package/lib/cjs/types/Esserializer/constant.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/deserializer.d.ts +27 -17
- package/lib/cjs/types/Esserializer/deserializer.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/general.d.ts +28 -4
- package/lib/cjs/types/Esserializer/general.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/index.d.ts +33 -29
- package/lib/cjs/types/Esserializer/index.d.ts.map +1 -1
- package/lib/cjs/types/Esserializer/serializer.d.ts +14 -3
- package/lib/cjs/types/Esserializer/serializer.d.ts.map +1 -1
- package/lib/cjs/types/Evt.d.ts +124 -0
- package/lib/cjs/types/Evt.d.ts.map +1 -0
- package/lib/cjs/types/Hooks.d.ts +1174 -837
- package/lib/cjs/types/Hooks.d.ts.map +1 -1
- package/lib/cjs/types/KissAction.d.ts +5257 -1398
- package/lib/cjs/types/KissAction.d.ts.map +1 -1
- package/lib/cjs/types/LoadPages.d.ts +287 -0
- package/lib/cjs/types/LoadPages.d.ts.map +1 -0
- package/lib/cjs/types/Persistor.d.ts +187 -118
- package/lib/cjs/types/Persistor.d.ts.map +1 -1
- package/lib/cjs/types/ProcessPersistence.d.ts +197 -99
- package/lib/cjs/types/ProcessPersistence.d.ts.map +1 -1
- package/lib/cjs/types/Store.d.ts +2266 -1042
- package/lib/cjs/types/Store.d.ts.map +1 -1
- package/lib/cjs/types/StoreException.d.ts +97 -28
- package/lib/cjs/types/StoreException.d.ts.map +1 -1
- package/lib/cjs/types/StoreProvider.d.ts +95 -0
- package/lib/cjs/types/StoreProvider.d.ts.map +1 -0
- package/lib/cjs/types/UserException.d.ts +178 -169
- package/lib/cjs/types/UserException.d.ts.map +1 -1
- package/lib/cjs/types/index.d.ts +12 -9
- package/lib/cjs/types/index.d.ts.map +1 -1
- package/lib/cjs/types/server.d.ts +12 -0
- package/lib/cjs/types/server.d.ts.map +1 -0
- package/lib/cjs/types/utils.d.ts +15 -1
- package/lib/cjs/types/utils.d.ts.map +1 -1
- package/lib/cjs/utils.js +45 -7
- package/lib/esm/ClassPersistor.mjs +177 -0
- package/lib/esm/Esserializer/{DeserializationOptions.js → DeserializationOptions.mjs} +3 -3
- package/lib/esm/Esserializer/{SerializeOptions.js → SerializeOptions.mjs} +3 -3
- package/lib/esm/Esserializer/builtins.mjs +254 -0
- package/lib/esm/Esserializer/constant.mjs +28 -0
- package/lib/esm/Esserializer/deserializer.mjs +288 -0
- package/lib/esm/Esserializer/general.mjs +81 -0
- package/lib/esm/Esserializer/index.mjs +43 -0
- package/lib/esm/Esserializer/serializer.mjs +164 -0
- package/lib/esm/Evt.mjs +151 -0
- package/lib/esm/Hooks.mjs +1448 -0
- package/lib/esm/KissAction.mjs +4816 -0
- package/lib/esm/LoadPages.mjs +340 -0
- package/lib/esm/Persistor.mjs +180 -0
- package/lib/esm/ProcessPersistence.mjs +581 -0
- package/lib/esm/Store.mjs +4464 -0
- package/lib/esm/StoreException.mjs +153 -0
- package/lib/esm/StoreProvider.mjs +162 -0
- package/lib/esm/{UserException.js → UserException.mjs} +240 -246
- package/lib/esm/{Wait.js → Wait.mjs} +309 -309
- package/lib/esm/index.mjs +12 -9
- package/lib/esm/server.mjs +23 -0
- package/lib/esm/types/ClassPersistor.d.ts +143 -112
- package/lib/esm/types/ClassPersistor.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/DeserializationOptions.d.ts +13 -6
- package/lib/esm/types/Esserializer/DeserializationOptions.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/SerializeOptions.d.ts +11 -5
- package/lib/esm/types/Esserializer/SerializeOptions.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/builtins.d.ts +36 -0
- package/lib/esm/types/Esserializer/builtins.d.ts.map +1 -0
- package/lib/esm/types/Esserializer/constant.d.ts +25 -49
- package/lib/esm/types/Esserializer/constant.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/deserializer.d.ts +27 -17
- package/lib/esm/types/Esserializer/deserializer.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/general.d.ts +28 -4
- package/lib/esm/types/Esserializer/general.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/index.d.ts +33 -29
- package/lib/esm/types/Esserializer/index.d.ts.map +1 -1
- package/lib/esm/types/Esserializer/serializer.d.ts +14 -3
- package/lib/esm/types/Esserializer/serializer.d.ts.map +1 -1
- package/lib/esm/types/Evt.d.ts +124 -0
- package/lib/esm/types/Evt.d.ts.map +1 -0
- package/lib/esm/types/Hooks.d.ts +1174 -837
- package/lib/esm/types/Hooks.d.ts.map +1 -1
- package/lib/esm/types/KissAction.d.ts +5257 -1398
- package/lib/esm/types/KissAction.d.ts.map +1 -1
- package/lib/esm/types/LoadPages.d.ts +287 -0
- package/lib/esm/types/LoadPages.d.ts.map +1 -0
- package/lib/esm/types/Persistor.d.ts +187 -118
- package/lib/esm/types/Persistor.d.ts.map +1 -1
- package/lib/esm/types/ProcessPersistence.d.ts +197 -99
- package/lib/esm/types/ProcessPersistence.d.ts.map +1 -1
- package/lib/esm/types/Store.d.ts +2266 -1042
- package/lib/esm/types/Store.d.ts.map +1 -1
- package/lib/esm/types/StoreException.d.ts +97 -28
- package/lib/esm/types/StoreException.d.ts.map +1 -1
- package/lib/esm/types/StoreProvider.d.ts +95 -0
- package/lib/esm/types/StoreProvider.d.ts.map +1 -0
- package/lib/esm/types/UserException.d.ts +178 -169
- package/lib/esm/types/UserException.d.ts.map +1 -1
- package/lib/esm/types/index.d.ts +12 -9
- package/lib/esm/types/index.d.ts.map +1 -1
- package/lib/esm/types/server.d.ts +12 -0
- package/lib/esm/types/server.d.ts.map +1 -0
- package/lib/esm/types/utils.d.ts +15 -1
- package/lib/esm/types/utils.d.ts.map +1 -1
- package/lib/esm/utils.mjs +38 -0
- package/package.json +54 -30
- package/lib/cjs/UnmodifiableSetView.js +0 -53
- package/lib/cjs/types/UnmodifiableSetView.d.ts +0 -24
- package/lib/cjs/types/UnmodifiableSetView.d.ts.map +0 -1
- package/lib/esm/ClassPersistor.js +0 -112
- package/lib/esm/Esserializer/constant.js +0 -81
- package/lib/esm/Esserializer/deserializer.js +0 -307
- package/lib/esm/Esserializer/general.js +0 -34
- package/lib/esm/Esserializer/index.js +0 -39
- package/lib/esm/Esserializer/serializer.js +0 -130
- package/lib/esm/Hooks.js +0 -955
- package/lib/esm/KissAction.js +0 -1459
- package/lib/esm/Persistor.js +0 -113
- package/lib/esm/ProcessPersistence.js +0 -262
- package/lib/esm/Store.js +0 -1606
- package/lib/esm/StoreException.js +0 -69
- package/lib/esm/UnmodifiableSetView.js +0 -50
- package/lib/esm/types/UnmodifiableSetView.d.ts +0 -24
- package/lib/esm/types/UnmodifiableSetView.d.ts.map +0 -1
- package/lib/esm/utils.js +0 -3
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
All exceptions thrown by Kiss are of type StoreException.
|
|
3
|
+
*/
|
|
4
|
+
export class StoreException extends Error {
|
|
5
|
+
constructor(message) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = 'StoreException';
|
|
8
|
+
// Maintains proper stack trace for where our error was thrown (only available on V8).
|
|
9
|
+
if (Error.captureStackTrace) {
|
|
10
|
+
Error.captureStackTrace(this, StoreException);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* If an action throws an `AbortDispatchException` from its `before` or `reduce` methods, the
|
|
16
|
+
* action aborts immediately, silently. Note the `after` method still runs, as usual.
|
|
17
|
+
*
|
|
18
|
+
* This is similar to throwing a `UserException`, but without showing any errors to the user,
|
|
19
|
+
* and without the action counting as failed:
|
|
20
|
+
*
|
|
21
|
+
* - The action status has `isDispatchAborted: true`, and the exception as its `originalError`.
|
|
22
|
+
* So `status.isCompletedOk` is `false`.
|
|
23
|
+
* - Like any other error, the exception is first given to the action's `wrapError`, and then to
|
|
24
|
+
* the `errorObserver`. They may return it unaltered (the default), turn it into another error,
|
|
25
|
+
* or swallow it by returning `null`. And if they return an `AbortDispatchException` for some
|
|
26
|
+
* other error, the action is aborted in the same way.
|
|
27
|
+
* - The action is not added to the failed actions, so `isFailed` is `false` for it.
|
|
28
|
+
* - It's never thrown by `dispatch`, and `dispatchAndWait` resolves with the action status,
|
|
29
|
+
* instead of rejecting.
|
|
30
|
+
* - It's not retried, if the action uses `retry`.
|
|
31
|
+
*
|
|
32
|
+
* You can use it in the `before` method to abort the action before the `reduce` method runs,
|
|
33
|
+
* after some ASYNC check. This is different from `abortDispatch()`, which must decide
|
|
34
|
+
* synchronously. For example:
|
|
35
|
+
*
|
|
36
|
+
* ```ts
|
|
37
|
+
* class LoadProfile extends KissAction<State> {
|
|
38
|
+
*
|
|
39
|
+
* async before() {
|
|
40
|
+
* if (await isProfileCached()) throw new AbortDispatchException();
|
|
41
|
+
* }
|
|
42
|
+
*
|
|
43
|
+
* async reduce() { ... }
|
|
44
|
+
* }
|
|
45
|
+
* ```
|
|
46
|
+
*
|
|
47
|
+
* Note Kiss itself also aborts actions with an `AbortDispatchException`: an `ignoreOld` action
|
|
48
|
+
* that became old, a `sequential` action discarded from its queue, an action with
|
|
49
|
+
* `checkInternet = { abort: true }` when there is no internet, and an action that stopped
|
|
50
|
+
* retrying. These are NOT given to `wrapError` or the `errorObserver`, since they didn't come
|
|
51
|
+
* from your code. So a `wrapError` that turns all errors into a `UserException` doesn't show
|
|
52
|
+
* them to the user.
|
|
53
|
+
*
|
|
54
|
+
* See also:
|
|
55
|
+
* - `abortDispatch()`, which is a way to abort the dispatch synchronously, before the action
|
|
56
|
+
* runs.
|
|
57
|
+
*/
|
|
58
|
+
export class AbortDispatchException extends Error {
|
|
59
|
+
constructor(message = 'Dispatch aborted.') {
|
|
60
|
+
super(message);
|
|
61
|
+
this.name = 'AbortDispatchException';
|
|
62
|
+
// Maintains proper stack trace for where our error was thrown (only available on V8).
|
|
63
|
+
if (Error.captureStackTrace) {
|
|
64
|
+
Error.captureStackTrace(this, AbortDispatchException);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// The `AbortDispatchException`s created by Kiss itself, and not by the user's code.
|
|
69
|
+
const _kissAborts = new WeakSet();
|
|
70
|
+
/**
|
|
71
|
+
* For Kiss internal use only.
|
|
72
|
+
* Creates an `AbortDispatchException` for an action that Kiss itself aborts. It's not given to
|
|
73
|
+
* the action's `wrapError` or to the `errorObserver`.
|
|
74
|
+
*/
|
|
75
|
+
export function kissAbort(message) {
|
|
76
|
+
const error = new AbortDispatchException(message);
|
|
77
|
+
_kissAborts.add(error);
|
|
78
|
+
return error;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* For Kiss internal use only.
|
|
82
|
+
* Returns true if the error is an `AbortDispatchException` created by `kissAbort`.
|
|
83
|
+
*/
|
|
84
|
+
export function isKissAbort(error) {
|
|
85
|
+
return (error instanceof AbortDispatchException) && _kissAborts.has(error);
|
|
86
|
+
}
|
|
87
|
+
export class TimeoutException extends Error {
|
|
88
|
+
/**
|
|
89
|
+
* The default timeout of the wait functions that are meant for tests only, like
|
|
90
|
+
* `waitActionCondition`, `waitAllActions`, `waitActionType`, `waitAllActionTypes` and
|
|
91
|
+
* `waitAnyActionTypeFinishes`. It's 3 seconds, which is shorter than the default test timeout
|
|
92
|
+
* of Jest and Vitest (5 seconds). This way, a wait that never completes fails the test with
|
|
93
|
+
* a clear `TimeoutException`, instead of the test runner's generic timeout error.
|
|
94
|
+
*
|
|
95
|
+
* You can change it globally, for example to 10 seconds, if your tests are slower:
|
|
96
|
+
*
|
|
97
|
+
* ```ts
|
|
98
|
+
* TimeoutException.defaultTimeoutMillis = 10_000;
|
|
99
|
+
* ```
|
|
100
|
+
*
|
|
101
|
+
* Note `waitCondition` and `dispatchWhen` have no default, since you may also use them in
|
|
102
|
+
* production. You must always give them a `timeoutMillis`.
|
|
103
|
+
*/
|
|
104
|
+
static defaultTimeoutMillis = 3000;
|
|
105
|
+
constructor(message) {
|
|
106
|
+
super(message);
|
|
107
|
+
this.name = 'TimeoutException';
|
|
108
|
+
// Maintains proper stack trace for where our error was thrown (only available on V8).
|
|
109
|
+
if (Error.captureStackTrace) {
|
|
110
|
+
Error.captureStackTrace(this, TimeoutException);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export class ExceptionUtils {
|
|
115
|
+
/**
|
|
116
|
+
Cuts the stack trace at the given string, to avoid showing internal Kiss lines,
|
|
117
|
+
which are not interesting to the user.
|
|
118
|
+
|
|
119
|
+
IMPORTANT: This should only be called during development. V8 only computes it if someone
|
|
120
|
+
actually reads the property, which improves performance dramatically for handable errors.
|
|
121
|
+
When you use this, you'll pay the cost even if your caller doesn't need the stack.
|
|
122
|
+
|
|
123
|
+
The given text will be found at the start of the line, like this: ` at ${text} `
|
|
124
|
+
*/
|
|
125
|
+
static sanitizedStackTrace(error, text) {
|
|
126
|
+
const stack = error.stack;
|
|
127
|
+
if (stack === undefined)
|
|
128
|
+
return error;
|
|
129
|
+
const stackLines = stack.split('\n');
|
|
130
|
+
let newStackStartIndex = -1;
|
|
131
|
+
// Be aware that `constructor.name` cannot be used with bundlers that mangle
|
|
132
|
+
// class or function names, because the error class name in the minified code
|
|
133
|
+
// might be shortened.
|
|
134
|
+
const errorLine = ` at ${text} `;
|
|
135
|
+
// Find the index where the exception was dispatched.
|
|
136
|
+
for (let i = 0; i < stackLines.length - 1; i++) {
|
|
137
|
+
if (stackLines[i].startsWith(errorLine)) {
|
|
138
|
+
newStackStartIndex = i + 1;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
if (newStackStartIndex !== -1) {
|
|
143
|
+
// Reconstruct the stack trace from the desired start point
|
|
144
|
+
// Also, include the error name and message as the first line
|
|
145
|
+
const newStack = [
|
|
146
|
+
`${error.name}: ${error.message}`,
|
|
147
|
+
...stackLines.slice(newStackStartIndex)
|
|
148
|
+
].join('\n');
|
|
149
|
+
error.stack = newStack;
|
|
150
|
+
}
|
|
151
|
+
return error;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
import { StoreException } from './StoreException.mjs';
|
|
4
|
+
// Read through the default import, not as named imports: under the `react-server` export
|
|
5
|
+
// condition, React's server build has no `createContext` or `useContext`, and Node's ESM loader
|
|
6
|
+
// rejects a named import that the module doesn't export, when it links the module. A React
|
|
7
|
+
// Server Components bundler never evaluates this module on the server (it's marked
|
|
8
|
+
// `'use client'`), but the package's server entry re-exports the components from here, and a
|
|
9
|
+
// plain Node import of it with that condition (the package's own tests) must load.
|
|
10
|
+
const { createContext, useContext, useEffect, useLayoutEffect, useMemo, useState } = React;
|
|
11
|
+
// Under the `react-server` export condition, React's server build has no `createContext`. A
|
|
12
|
+
// React Server Components bundler never evaluates this module on the server (it's marked
|
|
13
|
+
// `'use client'`, so its exports become client references), but the package's server entry
|
|
14
|
+
// re-exports the components from here, and a plain Node import of it with that condition (as in
|
|
15
|
+
// the package's own tests) must not throw.
|
|
16
|
+
export const StoreContext = (typeof createContext === 'function')
|
|
17
|
+
? createContext({ store: null, getServerState: () => undefined, getState: () => undefined })
|
|
18
|
+
: null;
|
|
19
|
+
export function StoreProvider(props) {
|
|
20
|
+
const { store, children } = props;
|
|
21
|
+
const serverState = ('serverState' in props) ? props.serverState : store._initialState;
|
|
22
|
+
const value = useMemo(() => ({ store, getServerState: () => serverState, getState: store._getState }), [store, serverState]);
|
|
23
|
+
return (React.createElement(StoreContext.Provider, { value: value }, children));
|
|
24
|
+
}
|
|
25
|
+
// `useLayoutEffect` doesn't run on the server, and React 18 warns when it's rendered there.
|
|
26
|
+
const useIsomorphicLayoutEffect = (typeof window === 'undefined') ? useEffect : useLayoutEffect;
|
|
27
|
+
/**
|
|
28
|
+
* Merges the state the server loaded for a route into the store, in a server-rendered app with
|
|
29
|
+
* several routes (see "Server-side rendering" in the README). The store lives above the routes
|
|
30
|
+
* (the root layout in the Next.js app router, `_app.tsx` in the pages router), and each route's
|
|
31
|
+
* server code loads its own data. Render the route's content inside a `StoreSlice` with that
|
|
32
|
+
* data, in the Next.js app router:
|
|
33
|
+
*
|
|
34
|
+
* ```tsx
|
|
35
|
+
* // app/users/[id]/page.tsx, a server component.
|
|
36
|
+
* export default async function UserPage({ params }) {
|
|
37
|
+
* const user = await loadUser((await params).id);
|
|
38
|
+
* return <StoreSlice state={{ user }} key={user.id}><UserView /></StoreSlice>;
|
|
39
|
+
* }
|
|
40
|
+
* ```
|
|
41
|
+
*
|
|
42
|
+
* What it does:
|
|
43
|
+
* - On the server, it merges the slice into the request's store, and the components inside it
|
|
44
|
+
* render the merged state, so the HTML shows the route's data.
|
|
45
|
+
* - On the client, while hydrating, the components inside it hydrate against the same merged
|
|
46
|
+
* server state (no mismatch, even if the live store already differs), and the slice is merged
|
|
47
|
+
* into the live store in the same commit, before their effects run, so nothing changes under
|
|
48
|
+
* them after hydration.
|
|
49
|
+
* - On client-side navigation, the components inside it read the live state with the slice
|
|
50
|
+
* merged into it from their first render, so the first render of the route already shows its
|
|
51
|
+
* data: no empty or stale frame. The live store gets the slice when the route commits, before
|
|
52
|
+
* the effects of the route and before the browser paints, and the other components (the
|
|
53
|
+
* layout) catch up right then. A render that React throws away (a transition to the route
|
|
54
|
+
* that is cancelled, or that suspends and never commits) leaves nothing in the live store.
|
|
55
|
+
*
|
|
56
|
+
* The merge is `store.mergeServerState(slice)`: the `mergeServerState` option of `createStore`,
|
|
57
|
+
* or a shallow merge for plain-object states. The slice is merged once per mount: use `key`
|
|
58
|
+
* (the entity id, for example) to merge again when the route's data changes. If the store is
|
|
59
|
+
* not ready yet (a persistor still reading), the slice is merged again into the persisted
|
|
60
|
+
* state when it arrives. If the `StoreProvider` above switches to another store while the slice
|
|
61
|
+
* stays mounted, the slice is merged into that store too (once per store), and the components
|
|
62
|
+
* inside it read and change that store.
|
|
63
|
+
*/
|
|
64
|
+
export function StoreSlice(props) {
|
|
65
|
+
const { state: slice, children } = props;
|
|
66
|
+
const parent = useContext(StoreContext);
|
|
67
|
+
const store = parent.store;
|
|
68
|
+
if (store === null)
|
|
69
|
+
throw new StoreException('StoreSlice must be used within a StoreProvider.');
|
|
70
|
+
// Once per mount and store. Usually there's only one store. If the provider switches to another
|
|
71
|
+
// store while this slice stays mounted, the components inside it must read the new store, and
|
|
72
|
+
// still find the route's data there, so the slice is merged into the new store too (its
|
|
73
|
+
// current `state` prop: the latest data of the route, and a new store has no local changes to
|
|
74
|
+
// keep). If the provider switches back to a store this slice already used, the slice is not
|
|
75
|
+
// merged into it again, so the changes made in that store since then are kept.
|
|
76
|
+
//
|
|
77
|
+
// The server state of the subtree is the parent's server state with the slice: what the
|
|
78
|
+
// server HTML shows for this route. (React calls the `useState` initializer twice in
|
|
79
|
+
// StrictMode, and keeps one of the results. An `AppliedSlice` created in a render that React
|
|
80
|
+
// throws away is harmless: on the client, only `CommitSlice` changes the store.)
|
|
81
|
+
const [appliedByStore] = useState(() => new WeakMap());
|
|
82
|
+
let applied = appliedByStore.get(store);
|
|
83
|
+
if (applied === undefined) {
|
|
84
|
+
applied = new AppliedSlice(store, parent.getServerState(), parent.getState, slice);
|
|
85
|
+
appliedByStore.set(store, applied);
|
|
86
|
+
}
|
|
87
|
+
const value = useMemo(() => ({ store, getServerState: applied.getServerState, getState: applied.getState }), [store, applied]);
|
|
88
|
+
// `CommitSlice` comes before the children, so that its layout effect runs before theirs.
|
|
89
|
+
return (React.createElement(StoreContext.Provider, { value: value },
|
|
90
|
+
React.createElement(CommitSlice, { applied: applied }),
|
|
91
|
+
children));
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* The slice of a mounted `StoreSlice`, and how the components inside it read the state.
|
|
95
|
+
*
|
|
96
|
+
* On the server there is no commit, so the slice is merged into the request's store right away,
|
|
97
|
+
* while React renders (the server render is synchronous and never thrown away, and nothing
|
|
98
|
+
* listens to the request's store, so nothing is published).
|
|
99
|
+
*
|
|
100
|
+
* On the client, the live store is not changed while React renders: React may throw the render
|
|
101
|
+
* away (a cancelled transition, a route that suspends and never commits), and a change made in
|
|
102
|
+
* it would stay in the store and show up in the other components later. Instead, until the
|
|
103
|
+
* route commits, the components inside the slice read the parent's state with the slice merged
|
|
104
|
+
* into it (`getState`, cached by the parent's state, since `useSyncExternalStore` needs the
|
|
105
|
+
* same object while nothing changed), and the other components still read the parent's state.
|
|
106
|
+
* When the route commits, `commit` merges the slice into the live store, in a layout effect
|
|
107
|
+
* that runs before the effects of the route's components, and publishes the change, so that the
|
|
108
|
+
* other components catch up before the browser paints. From then on, the components inside the
|
|
109
|
+
* slice read the parent's state, which has the slice.
|
|
110
|
+
*
|
|
111
|
+
* The parent's state is what the context above the slice gives: below a `StoreProvider`, the
|
|
112
|
+
* live state; below another `StoreSlice`, the `getState` of that slice. So, when nested slices
|
|
113
|
+
* mount in the same render (in the Next.js app router, a layout and its page, on client-side
|
|
114
|
+
* navigation), the components inside the inner slice read the data of both slices from their
|
|
115
|
+
* first render. The outer slice commits first (its `CommitSlice` comes before the inner slice),
|
|
116
|
+
* then the inner one, so the live store gets both, and the inner one wins for a key both have.
|
|
117
|
+
*/
|
|
118
|
+
class AppliedSlice {
|
|
119
|
+
store;
|
|
120
|
+
parentGetState;
|
|
121
|
+
slice;
|
|
122
|
+
serverState;
|
|
123
|
+
isCommitted = false;
|
|
124
|
+
base = undefined;
|
|
125
|
+
merged = undefined;
|
|
126
|
+
constructor(store, parentServerState, parentGetState, slice) {
|
|
127
|
+
this.store = store;
|
|
128
|
+
this.parentGetState = parentGetState;
|
|
129
|
+
this.slice = slice;
|
|
130
|
+
this.serverState = store._mergeSlice(parentServerState, slice);
|
|
131
|
+
if (typeof window === 'undefined' || store.isServer) {
|
|
132
|
+
store._mergeServerStateSilently(slice);
|
|
133
|
+
this.isCommitted = true;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
getServerState = () => this.serverState;
|
|
137
|
+
getState = () => {
|
|
138
|
+
const state = this.parentGetState();
|
|
139
|
+
if (this.isCommitted)
|
|
140
|
+
return state;
|
|
141
|
+
if (this.base !== state) {
|
|
142
|
+
this.base = state;
|
|
143
|
+
this.merged = this.store._mergeSlice(state, this.slice);
|
|
144
|
+
}
|
|
145
|
+
return this.merged;
|
|
146
|
+
};
|
|
147
|
+
/** Merges the slice into the live store, once. The second call (StrictMode) does nothing. */
|
|
148
|
+
commit() {
|
|
149
|
+
if (this.isCommitted)
|
|
150
|
+
return;
|
|
151
|
+
this.isCommitted = true;
|
|
152
|
+
this.store.mergeServerState(this.slice);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** Rendered before the children of a `StoreSlice`: its layout effect runs before theirs. */
|
|
156
|
+
function CommitSlice(props) {
|
|
157
|
+
const { applied } = props;
|
|
158
|
+
useIsomorphicLayoutEffect(() => {
|
|
159
|
+
applied.commit();
|
|
160
|
+
}, [applied]);
|
|
161
|
+
return null;
|
|
162
|
+
}
|