effect-atom-svelte 0.4.1 → 0.5.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 +6 -7
- package/dist/Form.d.ts +58 -24
- package/dist/Hooks.svelte.d.ts +117 -61
- package/dist/Hooks.svelte.js +184 -73
- package/dist/HydrationBoundary.svelte +24 -17
- package/dist/HydrationBoundary.svelte.d.ts +23 -16
- package/dist/Inspector.d.ts +32 -16
- package/dist/Inspector.js +29 -14
- package/dist/RegistryContext.d.ts +14 -5
- package/dist/RegistryContext.js +3 -1
- package/dist/RegistryProvider.svelte +4 -2
- package/dist/RegistryProvider.svelte.d.ts +2 -1
- package/dist/ScopedAtom.d.ts +3 -2
- package/dist/ScopedAtom.js +5 -3
- package/dist/SvelteKit.d.ts +94 -3
- package/dist/SvelteKit.js +168 -8
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/internal/follow.svelte.d.ts +7 -0
- package/dist/internal/follow.svelte.js +15 -0
- package/dist/internal/form/engine.js +140 -45
- package/dist/internal/form/field.js +11 -4
- package/dist/internal/form/types.d.ts +9 -0
- package/dist/internal/hydration.d.ts +2 -1
- package/dist/internal/hydration.js +6 -2
- package/dist/internal/kitVersion.d.ts +5 -0
- package/dist/internal/kitVersion.js +11 -0
- package/dist/internal/nodeInternals.js +2 -2
- package/dist/internal/remoteQueries.d.ts +5 -0
- package/dist/internal/remoteQueries.js +11 -0
- package/package.json +8 -7
package/dist/Hooks.svelte.js
CHANGED
|
@@ -13,6 +13,7 @@ import { queuedByBoundary } from "./internal/boundaries.js";
|
|
|
13
13
|
import { onDispose } from "./internal/disposal.js";
|
|
14
14
|
import { engineOf, initialGetter } from "./internal/form/engineOf.js";
|
|
15
15
|
import { decodeSeed, encodeSeed, isWaiting, noSeed, revalidatesOnHydrate, } from "./internal/hydration.js";
|
|
16
|
+
import { isRemoteQueryAtom } from "./internal/remoteQueries.js";
|
|
16
17
|
import { onRenderEnd } from "./internal/renderEnd.js";
|
|
17
18
|
import { reportReads } from "./internal/scope.svelte.js";
|
|
18
19
|
import { onTeardown } from "./internal/teardown.svelte.js";
|
|
@@ -63,7 +64,7 @@ class AtomCell {
|
|
|
63
64
|
}
|
|
64
65
|
}
|
|
65
66
|
const readOnly = () => {
|
|
66
|
-
throw new Error(`This atom value is read-only: useAtomValue and useAtomSuspense only read, as does useAtomRef for a ref without set, such as one from map. Write an atom with useAtom or useAtomSet, and a writable ref by assigning useAtomRef's current. ${troubleshooting("this-atom-value-is-read-only")}`);
|
|
67
|
+
throw new Error(`This atom value is read-only: useAtomValue, useAtomResult and useAtomSuspense only read, as does useAtomRef for a ref without set, such as one from map. Write an atom with useAtom or useAtomSet, and a writable ref by assigning useAtomRef's current. ${troubleshooting("this-atom-value-is-read-only")}`);
|
|
67
68
|
};
|
|
68
69
|
const valueOrThrow = (exit) => {
|
|
69
70
|
if (Exit.isSuccess(exit)) {
|
|
@@ -83,9 +84,10 @@ const notStarted = (result) => result._tag === "Initial" && !result.waiting;
|
|
|
83
84
|
const hasServerValue = (atom) => Atom.ServerValueTypeId in atom;
|
|
84
85
|
/** The atom's node, created if the registry has none yet. */
|
|
85
86
|
const nodeOf = (registry, atom) =>
|
|
86
|
-
// SAFETY: ensureNode returns the implementation's node (Effect 4.
|
|
87
|
+
// SAFETY: ensureNode returns the implementation's node (Effect 4.1.7), which has
|
|
87
88
|
// preserveInitialValueOnBuild, _value, setValue and failed (set while a first build has thrown)
|
|
88
|
-
// beside the Node interface
|
|
89
|
+
// beside the Node interface, and a setInitialValue that also takes skipInitialRun;
|
|
90
|
+
// @effect/atom-react calls its setValue the same way.
|
|
89
91
|
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- those members are on the implementation only, which Effect doesn't export
|
|
90
92
|
registry.ensureNode(atom);
|
|
91
93
|
/** The atom that holds a value given to `atom`: a wrapper such as `withRefresh` passes it on. */
|
|
@@ -96,6 +98,22 @@ const initialValueTarget = (atom) => {
|
|
|
96
98
|
}
|
|
97
99
|
return target;
|
|
98
100
|
};
|
|
101
|
+
/**
|
|
102
|
+
* The atom whose serialization key carries `atom`'s result between server and browser: `atom`
|
|
103
|
+
* itself, or the source of a wrapper that passes its value on, as `Atom.swr` does. `AtomRpc` and
|
|
104
|
+
* `AtomHttpApi` build a query with a `serializationKey` and a `staleTime` that way: the wrapper
|
|
105
|
+
* isn't serializable, its source is.
|
|
106
|
+
*/
|
|
107
|
+
const serializableOf = (atom) => {
|
|
108
|
+
let current = atom;
|
|
109
|
+
while (current) {
|
|
110
|
+
if (Atom.isSerializable(current)) {
|
|
111
|
+
return current;
|
|
112
|
+
}
|
|
113
|
+
current = current.initialValueTarget;
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
};
|
|
99
117
|
/**
|
|
100
118
|
* Keeps an atom's node in the registry without computing it, as a mount would but without the read.
|
|
101
119
|
* The registry sweeps a node without listeners, so a listener holds it; letting go schedules the
|
|
@@ -134,26 +152,50 @@ const dropInitialValueMark = (registry, atom) => {
|
|
|
134
152
|
current = current.initialValueTarget;
|
|
135
153
|
}
|
|
136
154
|
};
|
|
155
|
+
/** Whether a hook stops waiting at a result: it has left `Initial`, and isn't refreshing if asked. */
|
|
156
|
+
const settles = (result, suspendOnWaiting) => result._tag !== "Initial" && !(suspendOnWaiting && result.waiting);
|
|
157
|
+
/**
|
|
158
|
+
* Whether the atom's own node holds a value a `HydrationBoundary` brought that the server builds
|
|
159
|
+
* and waits for rather than rendering. Since Effect 4.1, a value a boundary queued for the atom's
|
|
160
|
+
* own node is applied as an initial value, as it always was for a wrapper's source. A settled one
|
|
161
|
+
* is rendered as is, like any initial value: building the node would run the effect again, after
|
|
162
|
+
* `load` ran it (#103). An `Initial` isn't: the hooks wait for it, as they did when Effect applied
|
|
163
|
+
* it as the node's value (4.0), since it may be promise-encoded, with a result that lands during
|
|
164
|
+
* the render. Nor, for a reader with `suspendOnWaiting`, is a `Success` still waiting, as `load`
|
|
165
|
+
* sends for a running stream: that reader asked to wait for the refresh, so the stream runs again.
|
|
166
|
+
*/
|
|
167
|
+
const boundaryWaitedFor = (registry, atom, value, suspendOnWaiting) => Atom.isSerializable(atom) &&
|
|
168
|
+
queuedByBoundary(registry, atom[Atom.SerializableTypeId].key) &&
|
|
169
|
+
AsyncResult.isAsyncResult(value) &&
|
|
170
|
+
!settles(value, suspendOnWaiting);
|
|
137
171
|
/**
|
|
138
|
-
* On the server, the node holding
|
|
139
|
-
* source's for a wrapper such as `withRefresh`, which passes
|
|
140
|
-
* The server renders that value: mounting, reading or waiting
|
|
141
|
-
* build runs the atom's read, the source's included, even when it
|
|
142
|
-
* browser-only or start a request the value was there to save.
|
|
172
|
+
* On the server, the node holding an initial value for an atom, from `useAtomInitialValues` or a
|
|
173
|
+
* `HydrationBoundary`: its own, or its source's for a wrapper such as `withRefresh`, which passes
|
|
174
|
+
* the value on and reads as its source. The server renders that value: mounting, reading or waiting
|
|
175
|
+
* for the atom would build it, and a build runs the atom's read, the source's included, even when it
|
|
176
|
+
* keeps the value. That read may be browser-only or start a request the value was there to save.
|
|
177
|
+
* `suspendOnWaiting` is the reader's option: with it, a boundary's waiting value is waited for.
|
|
143
178
|
*
|
|
144
179
|
* For a wrapper, this assumes it reads as its source, as every wrapper Effect makes with
|
|
145
180
|
* `initialValueTarget` does. A user's `Atom.transform` given `initialValueTarget` that changes the
|
|
146
181
|
* value would render its source's value on the server, where Effect computes the transform.
|
|
147
182
|
*/
|
|
148
|
-
const initialNodeOnServer = (registry, atom) => {
|
|
183
|
+
const initialNodeOnServer = (registry, atom, suspendOnWaiting = false) => {
|
|
149
184
|
if (BROWSER) {
|
|
150
185
|
return undefined;
|
|
151
186
|
}
|
|
152
|
-
const
|
|
153
|
-
|
|
187
|
+
const target = initialValueTarget(atom);
|
|
188
|
+
const node = nodeOf(registry, target);
|
|
189
|
+
if (!node.preserveInitialValueOnBuild) {
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
return target === atom &&
|
|
193
|
+
boundaryWaitedFor(registry, atom, node._value, suspendOnWaiting)
|
|
194
|
+
? undefined
|
|
195
|
+
: node;
|
|
154
196
|
};
|
|
155
|
-
/** Whether, on the server, an atom renders
|
|
156
|
-
const initialOnServer = (registry, atom) => initialNodeOnServer(registry, atom) !== undefined;
|
|
197
|
+
/** Whether, on the server, an atom renders an initial value (see `initialNodeOnServer`). */
|
|
198
|
+
const initialOnServer = (registry, atom, suspendOnWaiting = false) => initialNodeOnServer(registry, atom, suspendOnWaiting) !== undefined;
|
|
157
199
|
/** Keeps an atom for the server render: a node with an initial value is held, not mounted. */
|
|
158
200
|
const serverMount = (registry, atom) => {
|
|
159
201
|
const node = initialNodeOnServer(registry, atom);
|
|
@@ -167,8 +209,6 @@ const serverGet = (registry, atom) => {
|
|
|
167
209
|
const awaitResult = (registry, atom, options, signal) => Effect.runPromiseExit(AtomRegistry.getResult(registry, atom, options), {
|
|
168
210
|
signal,
|
|
169
211
|
});
|
|
170
|
-
/** Whether a hook stops waiting at a result: it has left `Initial`, and isn't refreshing if asked. */
|
|
171
|
-
const settles = (result, suspendOnWaiting) => result._tag !== "Initial" && !(suspendOnWaiting && result.waiting);
|
|
172
212
|
/**
|
|
173
213
|
* Waits for an async atom to settle, as `awaitResult` does, but resolves with the atom's own result
|
|
174
214
|
* rather than an `Exit` rebuilt from it, which would drop a `Failure`'s `previousSuccess`.
|
|
@@ -216,6 +256,21 @@ const countSeeded = (registry, key) => {
|
|
|
216
256
|
// The keys of the atoms useAtomValue has warned about, so the server warns once per key, not per
|
|
217
257
|
// request.
|
|
218
258
|
const warnedUnsent = new Set();
|
|
259
|
+
const warnedRemoteQuery = new WeakSet();
|
|
260
|
+
/**
|
|
261
|
+
* In development, warns once per atom that a plain read on the server met a remoteQueryAtom still
|
|
262
|
+
* waiting for its query. SvelteKit sends the query's result with the page anyway, so the browser
|
|
263
|
+
* starts from the value while the server's HTML shows the loading state.
|
|
264
|
+
*/
|
|
265
|
+
const warnRemoteQueryRead = (atom, value, hook) => {
|
|
266
|
+
if (!AsyncResult.isAsyncResult(value) ||
|
|
267
|
+
!value.waiting ||
|
|
268
|
+
warnedRemoteQuery.has(atom)) {
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
warnedRemoteQuery.add(atom);
|
|
272
|
+
console.warn(`effect-atom-svelte: ${hook} read a remoteQueryAtom on the server before its query returned, so the server's HTML shows it loading while the browser starts from SvelteKit's result. Read it with await useAtomResult or useAtomSuspense, so the render waits for the query. ${troubleshooting("read-a-remotequeryatom-on-the-server-before-its-query-returned")}`);
|
|
273
|
+
};
|
|
219
274
|
/**
|
|
220
275
|
* In development, warns once per key that a plain read on the server met a serializable async atom
|
|
221
276
|
* still running: only useAtomResult and useAtomSuspense send an atom's result to the browser, so
|
|
@@ -224,18 +279,22 @@ const warnedUnsent = new Set();
|
|
|
224
279
|
* nothing is computing, such as an Atom.fn nobody called or a value written to the atom.
|
|
225
280
|
*/
|
|
226
281
|
const warnUnsent = (registry, atom, value, hook) => {
|
|
227
|
-
if (
|
|
228
|
-
|
|
282
|
+
if (DEV && isRemoteQueryAtom(atom)) {
|
|
283
|
+
warnRemoteQueryRead(atom, value, hook);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
const source = DEV ? serializableOf(atom) : undefined;
|
|
287
|
+
if (!(source && AsyncResult.isAsyncResult(value)) || !value.waiting) {
|
|
229
288
|
return;
|
|
230
289
|
}
|
|
231
|
-
const { key } =
|
|
290
|
+
const { key } = source[Atom.SerializableTypeId];
|
|
232
291
|
if (warnedUnsent.has(key) ||
|
|
233
292
|
queuedByBoundary(registry, key) ||
|
|
234
293
|
seededOnServer(registry, key)) {
|
|
235
294
|
return;
|
|
236
295
|
}
|
|
237
296
|
warnedUnsent.add(key);
|
|
238
|
-
console.warn(`effect-atom-svelte: ${hook} read the serializable atom "${key}" on the server while it was still running, but only useAtomResult and useAtomSuspense send an atom's result to the browser, so it runs again there. Read it with one of them.
|
|
297
|
+
console.warn(`effect-atom-svelte: ${hook} read the serializable atom "${key}" on the server while it was still running, but only useAtomResult and useAtomSuspense send an atom's result to the browser, so it runs again there. Read it with one of them. ${troubleshooting("only-useatomresult-and-useatomsuspense-send-an-atoms-result-to-the-browser")}`);
|
|
239
298
|
};
|
|
240
299
|
/**
|
|
241
300
|
* Reads the getter's atom and follows it. `plainRead` names the plain read, `useAtomValue` or
|
|
@@ -248,8 +307,9 @@ const subscribedReader = (registry, getAtom, plainRead) => {
|
|
|
248
307
|
// await, keeps it for the request. The mounts are released when the server render ends,
|
|
249
308
|
// because a registry passed in by the caller outlives the request (JND-17).
|
|
250
309
|
// An atom with a withServerValue override is never computed on the server, so it is not mounted:
|
|
251
|
-
// mounting would run its real read, which is often browser-only. One with
|
|
252
|
-
// useAtomInitialValues is held and read without building it (see
|
|
310
|
+
// mounting would run its real read, which is often browser-only. One with an initial value, from
|
|
311
|
+
// useAtomInitialValues or a HydrationBoundary, is held and read without building it (see
|
|
312
|
+
// initialNodeOnServer).
|
|
253
313
|
// Once the render has ended, a read that switches atoms, as from a reader kept past the render,
|
|
254
314
|
// takes no mount: nothing would release it.
|
|
255
315
|
let ended = false;
|
|
@@ -461,11 +521,12 @@ const mountWhileAlive = (input, kind) => {
|
|
|
461
521
|
});
|
|
462
522
|
};
|
|
463
523
|
/**
|
|
464
|
-
*
|
|
465
|
-
* it. Use it in a component that outlives the readers, such as a
|
|
466
|
-
* value while they come and go.
|
|
524
|
+
* [Holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) an atom while the component lives,
|
|
525
|
+
* even when no component reads it. Use it in a component that outlives the readers, such as a
|
|
526
|
+
* layout, so the atom keeps its value while they come and go. Holding an atom that hasn't been
|
|
527
|
+
* computed also computes it.
|
|
467
528
|
*
|
|
468
|
-
* **Example** (Keeping a connection open while a component
|
|
529
|
+
* **Example** (Keeping a connection open while a component lives)
|
|
469
530
|
*
|
|
470
531
|
* ```ts
|
|
471
532
|
* import { useAtomMount } from "effect-atom-svelte";
|
|
@@ -500,11 +561,12 @@ export function useAtomSet(input, options) {
|
|
|
500
561
|
registry.set(atom, updateFrom(registry.get(atom)));
|
|
501
562
|
};
|
|
502
563
|
}
|
|
564
|
+
const settle = (exit) => mode === "promiseExit" ? exit : valueOrThrow(exit);
|
|
503
565
|
return async (value, writeOptions) => {
|
|
504
566
|
if (value === Atom.Reset) {
|
|
505
567
|
// Excluded by the types: a reset result is Initial, which never settles, so the wait would
|
|
506
568
|
// never end.
|
|
507
|
-
throw new TypeError(`useAtomSet's ${mode} mode cannot wait for Atom.Reset; reset with a value mode setter`);
|
|
569
|
+
throw new TypeError(`useAtomSet's ${mode} mode cannot wait for Atom.Reset; reset with a value mode setter. ${troubleshooting("cannot-wait-for-atomreset")}`);
|
|
508
570
|
}
|
|
509
571
|
// SAFETY: the overloads offer the promise modes only for an atom that holds an AsyncResult.
|
|
510
572
|
// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the implementation signature can't carry the overloads' atom type
|
|
@@ -519,7 +581,14 @@ export function useAtomSet(input, options) {
|
|
|
519
581
|
else {
|
|
520
582
|
// oxlint-disable-next-line effecttsgo/global-date -- compared with an AsyncResult's timestamp, which Effect takes from Date.now
|
|
521
583
|
const start = Date.now();
|
|
522
|
-
|
|
584
|
+
try {
|
|
585
|
+
registry.set(atom, value);
|
|
586
|
+
}
|
|
587
|
+
catch (error) {
|
|
588
|
+
// As an Atom.fn that throws before returning its Effect does: a defect, so promiseExit mode
|
|
589
|
+
// still resolves, with it.
|
|
590
|
+
return settle(Exit.die(error));
|
|
591
|
+
}
|
|
523
592
|
// A provider disposing of its registry ends the call without a last result, so the wait ends
|
|
524
593
|
// there too, as interrupted.
|
|
525
594
|
const controller = new AbortController();
|
|
@@ -536,11 +605,13 @@ export function useAtomSet(input, options) {
|
|
|
536
605
|
writeOptions?.signal?.removeEventListener("abort", abort);
|
|
537
606
|
}
|
|
538
607
|
}
|
|
539
|
-
return
|
|
608
|
+
return settle(exit);
|
|
540
609
|
};
|
|
541
610
|
}
|
|
542
611
|
/**
|
|
543
|
-
* Returns a function that runs the atom again.
|
|
612
|
+
* Returns a function that runs the atom again. It also
|
|
613
|
+
* [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom while the component lives,
|
|
614
|
+
* so the refreshed result is kept even when nothing on screen reads it.
|
|
544
615
|
*
|
|
545
616
|
* **Example** (Running an atom again on click)
|
|
546
617
|
*
|
|
@@ -613,12 +684,18 @@ const orderedDelivery = (f) => {
|
|
|
613
684
|
};
|
|
614
685
|
/**
|
|
615
686
|
* Calls `f` on every change while the component lives, and with the current value first when
|
|
616
|
-
* `immediate` is set. The atom
|
|
617
|
-
*
|
|
618
|
-
*
|
|
619
|
-
*
|
|
620
|
-
* change
|
|
621
|
-
*
|
|
687
|
+
* `immediate` is set. The hook [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) the atom
|
|
688
|
+
* and computes it once the component mounts, never on the server, so a derived or effect atom that
|
|
689
|
+
* nothing else reads still runs and reports its changes.
|
|
690
|
+
*
|
|
691
|
+
* A change raised while another component is reading an atom reaches `f` on a microtask, so `f` can
|
|
692
|
+
* write `$state` (Svelte forbids that during a read). Changes after it wait their turn, so `f` sees
|
|
693
|
+
* every change in order; any other change reaches it synchronously. Nothing reaches `f` once the
|
|
694
|
+
* component is destroyed, not even a change still waiting for its microtask.
|
|
695
|
+
*
|
|
696
|
+
* If the atom's first computation throws, the error is left to the atom's readers and `f` hears the
|
|
697
|
+
* atom once it recovers; with `immediate`, it throws in the component, as there is no value to call
|
|
698
|
+
* `f` with.
|
|
622
699
|
*
|
|
623
700
|
* **Example** (Saving every change)
|
|
624
701
|
*
|
|
@@ -644,15 +721,15 @@ export const useAtomSubscribe = (input, f, options) => {
|
|
|
644
721
|
const atom = current;
|
|
645
722
|
// `immediate` calls `f` now, inside this effect; what `f` reads must not re-run it.
|
|
646
723
|
return untrack(() => {
|
|
647
|
-
// registry.subscribe does not compute a node that has never been read, so an atom nothing
|
|
648
|
-
// else reads would never run, and a derived atom would never hear its sources. Reading it
|
|
649
|
-
// first builds it.
|
|
650
|
-
const value = duringRead(() => registry.get(atom));
|
|
651
724
|
if (options?.immediate === true) {
|
|
652
|
-
f(
|
|
725
|
+
f(duringRead(() => registry.get(atom)));
|
|
653
726
|
}
|
|
654
727
|
const deliver = orderedDelivery(f);
|
|
655
|
-
|
|
728
|
+
// Since Effect 4.1, registry.subscribe computes an atom nothing has read yet, so an atom
|
|
729
|
+
// nothing else reads still runs and a derived atom hears its sources. A first computation
|
|
730
|
+
// that throws is left for the atom's readers to report, and `f` hears the atom once it
|
|
731
|
+
// recovers. It counts as a read, so a change the computation raises waits for its microtask.
|
|
732
|
+
const cancel = duringRead(() => registry.subscribe(atom, deliver));
|
|
656
733
|
dropInitialValueMark(registry, atom);
|
|
657
734
|
return () => {
|
|
658
735
|
deliver.stop();
|
|
@@ -676,20 +753,30 @@ const initialValuesApplied = new WeakSet();
|
|
|
676
753
|
// does, so a request ending doesn't let a request starting overwrite the value another still renders.
|
|
677
754
|
const serverHolders = new WeakMap();
|
|
678
755
|
/**
|
|
679
|
-
* Sets starting values as `AtomRegistry.make({ initialValues })` would
|
|
680
|
-
* (a wrapper such as `withRefresh` passes it to its source), kept as the value of the atom's first
|
|
681
|
-
* build, which still reads and follows the atom's sources. The atoms are not computed here: each
|
|
682
|
-
* keeps its value, uncomputed, while this component lives, and the first component to read it
|
|
683
|
-
* computes it from there, so a value set in a layout is still there when a page reads it later, and
|
|
684
|
-
* an atom that can only compute in the browser can start from a value on the server.
|
|
756
|
+
* Sets starting values from a component, as `AtomRegistry.make({ initialValues })` would.
|
|
685
757
|
*
|
|
686
|
-
*
|
|
687
|
-
*
|
|
688
|
-
*
|
|
689
|
-
* to
|
|
690
|
-
*
|
|
691
|
-
*
|
|
692
|
-
*
|
|
758
|
+
* - **Once while the atom is held.** Each atom takes the first value a component gives it. Another
|
|
759
|
+
* call while something still holds the atom, as from a component mounting again or a second
|
|
760
|
+
* component with its own value, doesn't set it again; once the atom has been disposed, the next
|
|
761
|
+
* component to start it sets it again. An atom already in use without a value, read by another
|
|
762
|
+
* component, is set to it, as `@effect/atom-react` does.
|
|
763
|
+
* - **Held while the component lives.** The hook
|
|
764
|
+
* [holds](https://atom.jarrednorris.dev/lifetimes#held-atoms) its atoms without computing them:
|
|
765
|
+
* the first component to read an atom computes it, starting from the value, so a value set in a
|
|
766
|
+
* layout is still there when a page reads it later.
|
|
767
|
+
* - **Once per render on the server.** Each server render sets its values again and renders them
|
|
768
|
+
* without running the atom, so an atom that can only compute in the browser can start from a
|
|
769
|
+
* value on the server. Renders at the same time on a shared registry share the value the first
|
|
770
|
+
* one applied, until the last of them ends.
|
|
771
|
+
* - **Wrapped and derived atoms.** A wrapper such as `Atom.withRefresh`, `Atom.swr` or
|
|
772
|
+
* `Atom.debounce` passes the value to its source. The atom starts from the value and still reads
|
|
773
|
+
* its sources, so a derived atom computes again when one of them changes.
|
|
774
|
+
* - **Effect and stream atoms.** In the browser, an atom that runs an effect or a stream still runs
|
|
775
|
+
* it when it is first read, as with `AtomRegistry.make`, and shows the value until the run
|
|
776
|
+
* finishes. To keep the value instead, as for data a `load` function already fetched, pass the
|
|
777
|
+
* entry as `Atom.initialValue(atom, value, { skipInitialRun: true })` (Effect 4.1): the atom then
|
|
778
|
+
* runs once it is refreshed, or once an atom its function reads before returning the effect
|
|
779
|
+
* changes.
|
|
693
780
|
*
|
|
694
781
|
* **Example** (Starting an atom from a prop)
|
|
695
782
|
*
|
|
@@ -717,11 +804,11 @@ export const useAtomInitialValues = (initialValues) => {
|
|
|
717
804
|
release();
|
|
718
805
|
}
|
|
719
806
|
});
|
|
720
|
-
for (const [atom, value] of initialValues) {
|
|
721
|
-
const node = registry
|
|
807
|
+
for (const [atom, value, options] of initialValues) {
|
|
808
|
+
const node = nodeOf(registry, initialValueTarget(atom));
|
|
722
809
|
if (!initialValuesApplied.has(node)) {
|
|
723
810
|
initialValuesApplied.add(node);
|
|
724
|
-
node.setInitialValue(value);
|
|
811
|
+
node.setInitialValue(value, options?.skipInitialRun);
|
|
725
812
|
}
|
|
726
813
|
if (!BROWSER) {
|
|
727
814
|
// A registry passed in by the caller outlives the request, and its node may not be swept
|
|
@@ -807,7 +894,7 @@ export const useAtomRefPropValue = (input, prop) => {
|
|
|
807
894
|
const propRef = $derived(getRef().prop(prop));
|
|
808
895
|
return useAtomRef(() => propRef);
|
|
809
896
|
};
|
|
810
|
-
const notStartedError = (hook) => new Error(`${hook} read an atom that has not started on the server: its result is Initial and nothing is running it, as for an Atom.fn that has not been called, so the render would wait for it forever. Read it with useAtomValue, which renders Initial, or inside a <svelte:boundary> with a pending snippet, which the server renders instead
|
|
897
|
+
const notStartedError = (hook) => new Error(`${hook} read an atom that has not started on the server: its result is Initial and nothing is running it, as for an Atom.fn that has not been called, so the render would wait for it forever. Read it with useAtomValue, which renders Initial, or inside a <svelte:boundary> with a pending snippet, which the server renders instead. ${troubleshooting("read-an-atom-that-has-not-started-on-the-server")}`);
|
|
811
898
|
/**
|
|
812
899
|
* Puts the server's value in the registry as current, so nothing fetches it again (JND-19). Seeding
|
|
813
900
|
* through `setSerializable` would not: for an atom that wraps another, such as a query with
|
|
@@ -836,6 +923,9 @@ const settledSeeds = new WeakSet();
|
|
|
836
923
|
* registry, so later requests would skip embedding their seed (JND-17).
|
|
837
924
|
*/
|
|
838
925
|
const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) => {
|
|
926
|
+
// The atom whose key and schema carry the result: `atom`, or the source a wrapper such as
|
|
927
|
+
// Atom.swr passes its value to. Its own value is sent, as the browser applies the seed to it.
|
|
928
|
+
const owner = serializableOf(atom) ?? atom;
|
|
839
929
|
// Mounted until the render ends, so the settled node is what the render reads.
|
|
840
930
|
const release = serverMount(registry, atom);
|
|
841
931
|
// A render ends before its seeds settle only when it fails, as when a later reader throws during
|
|
@@ -864,8 +954,12 @@ const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) =>
|
|
|
864
954
|
// Not waited for if nothing has started it: the hook rejects once seeded. Waited for as the hook
|
|
865
955
|
// waits, so with suspendOnWaiting the seed is the settled result the render shows, not one the
|
|
866
956
|
// browser would run again because it was still waiting.
|
|
867
|
-
|
|
868
|
-
|
|
957
|
+
// A later reader of the key that has already asked for the settled result counts too: a
|
|
958
|
+
// HydrationBoundary's waiting value is waited for only then (see initialNodeOnServer).
|
|
959
|
+
let settled = suspendOnWaiting ||
|
|
960
|
+
(claim.first !== undefined && settledSeeds.has(claim.first));
|
|
961
|
+
if (!initialOnServer(registry, atom, settled) &&
|
|
962
|
+
!notStarted(registry.get(atom))) {
|
|
869
963
|
await awaitResult(registry, atom, { suspendOnWaiting: settled });
|
|
870
964
|
// A later reader of the key may want the settled result once this one's wait has begun.
|
|
871
965
|
if (!settled && claim.first && settledSeeds.has(claim.first)) {
|
|
@@ -876,7 +970,7 @@ const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) =>
|
|
|
876
970
|
if (ended) {
|
|
877
971
|
return noSeed;
|
|
878
972
|
}
|
|
879
|
-
return encodeSeed(key, encode, serverGet(registry,
|
|
973
|
+
return encodeSeed(key, encode, serverGet(registry, owner));
|
|
880
974
|
})();
|
|
881
975
|
return claim.own;
|
|
882
976
|
});
|
|
@@ -884,11 +978,12 @@ const seedOnServer = (registry, atom, key, encode, suspendOnWaiting = false) =>
|
|
|
884
978
|
if (suspendOnWaiting) {
|
|
885
979
|
settledSeeds.add(encoded);
|
|
886
980
|
}
|
|
981
|
+
// Wrappers of one serializable atom, such as two Atom.swr of one query, send the same result.
|
|
887
982
|
const claimed = serverSeeds.get(encoded);
|
|
888
|
-
if (claimed && claimed !==
|
|
983
|
+
if (claimed && claimed !== owner) {
|
|
889
984
|
throw new Error(`Two different atoms share the serialization key "${key}", so the server can't tell whose result to send. Put what tells the copies apart into the key, such as an id, and define atoms at module level. ${troubleshooting("two-different-atoms-share-the-serialization-key")}`);
|
|
890
985
|
}
|
|
891
|
-
serverSeeds.set(encoded,
|
|
986
|
+
serverSeeds.set(encoded, owner);
|
|
892
987
|
return (async () => {
|
|
893
988
|
await encoded;
|
|
894
989
|
})();
|
|
@@ -965,10 +1060,11 @@ revalidateOption, suspendOnWaiting = false) => {
|
|
|
965
1060
|
const atom = getAtom();
|
|
966
1061
|
// The server never computes an atom with a server value, so it has no value to pass on, and the
|
|
967
1062
|
// browser must not ask for one: hydratable throws for a key the server didn't write (JND-58).
|
|
968
|
-
|
|
1063
|
+
const source = serializableOf(atom);
|
|
1064
|
+
if (!source || hasServerValue(atom)) {
|
|
969
1065
|
return undefined;
|
|
970
1066
|
}
|
|
971
|
-
const { decode, encode, key } =
|
|
1067
|
+
const { decode, encode, key } = source[Atom.SerializableTypeId];
|
|
972
1068
|
if (!BROWSER) {
|
|
973
1069
|
return {
|
|
974
1070
|
done: seedOnServer(registry, atom, key, encode, suspendOnWaiting),
|
|
@@ -1075,11 +1171,18 @@ revalidateOption, suspendOnWaiting = false) => {
|
|
|
1075
1171
|
};
|
|
1076
1172
|
/**
|
|
1077
1173
|
* Awaits an async atom's first result, then returns a live handle to its `AsyncResult`. Use it as
|
|
1078
|
-
* a top-level `await` in a component script; server rendering waits for it
|
|
1079
|
-
*
|
|
1080
|
-
*
|
|
1081
|
-
*
|
|
1082
|
-
*
|
|
1174
|
+
* a top-level `await` in a component script; server rendering waits for it. With a serialization
|
|
1175
|
+
* key the browser starts from the server's result instead of running the atom again, unless
|
|
1176
|
+
* `revalidateOnHydrate` is set, the server's result was still `waiting`, or the atom is a
|
|
1177
|
+
* `staleTime` (`Atom.swr`) query that is stale or failed with no earlier success.
|
|
1178
|
+
*
|
|
1179
|
+
* Call it before the script's first `await` (for several atoms, in one `Promise.all`); an atom
|
|
1180
|
+
* read after that `await` runs again in the browser. See
|
|
1181
|
+
* [Call hooks before the first await](https://atom.jarrednorris.dev/hydration#call-hooks-before-the-first-await).
|
|
1182
|
+
*
|
|
1183
|
+
* With a getter, only the first atom is awaited: when the getter picks another atom the handle
|
|
1184
|
+
* follows it, starting from that atom's current result (often `Initial`), and the component's
|
|
1185
|
+
* await does not run again. On the server, an atom with a `withServerValue` override
|
|
1083
1186
|
* reads as that value and is never computed. An atom that has not started, whose result is
|
|
1084
1187
|
* `Initial` with nothing running, as an `Atom.fn` nothing has called, keeps the await pending in the
|
|
1085
1188
|
* browser until something writes it; on the server, where nothing will during the render, the
|
|
@@ -1132,7 +1235,7 @@ export const useAtomResult = async (input, options) => {
|
|
|
1132
1235
|
return value;
|
|
1133
1236
|
}
|
|
1134
1237
|
// On the server, an initial value is what the render shows, with nothing to wait for.
|
|
1135
|
-
if (initialOnServer(registry, atom)) {
|
|
1238
|
+
if (initialOnServer(registry, atom, options?.suspendOnWaiting)) {
|
|
1136
1239
|
release = serverMount(registry, atom);
|
|
1137
1240
|
return value;
|
|
1138
1241
|
}
|
|
@@ -1187,11 +1290,19 @@ const fromServerValue = (current, options) => {
|
|
|
1187
1290
|
}
|
|
1188
1291
|
};
|
|
1189
1292
|
const suspend = async (registry, atom, current, options, signal) => {
|
|
1190
|
-
|
|
1293
|
+
// On the server, an initial value is what the render shows, as for useAtomResult: a waiting one
|
|
1294
|
+
// isn't waited for, even with suspendOnWaiting. Waiting would build the atom, running its read,
|
|
1295
|
+
// and the build keeps the initial value, so a synchronous result would be dropped and the wait
|
|
1296
|
+
// would never end (#106). A HydrationBoundary's waiting value isn't an initial value here (see
|
|
1297
|
+
// initialNodeOnServer).
|
|
1298
|
+
const waits = !BROWSER && initialOnServer(registry, atom, options.suspendOnWaiting)
|
|
1299
|
+
? { ...options, suspendOnWaiting: false }
|
|
1300
|
+
: options;
|
|
1301
|
+
if (isPending(current, waits)) {
|
|
1191
1302
|
if (!BROWSER && notStarted(current)) {
|
|
1192
1303
|
throw notStartedError("useAtomSuspense");
|
|
1193
1304
|
}
|
|
1194
|
-
const exit = await awaitSettled(registry, atom, { suspendOnWaiting:
|
|
1305
|
+
const exit = await awaitSettled(registry, atom, { suspendOnWaiting: waits.suspendOnWaiting }, signal);
|
|
1195
1306
|
// Abandoned: rejects with the reason its last reader's signal was aborted with. For a re-run
|
|
1196
1307
|
// that is Svelte's STALE_REACTION, which it ignores, so a pending render that still awaits this
|
|
1197
1308
|
// wait keeps waiting for its next run instead of showing the interruption (JND-22).
|
|
@@ -1,22 +1,10 @@
|
|
|
1
1
|
<!--
|
|
2
2
|
@component
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
That needs Svelte's `experimental.async`: without it, the browser can't tell that it is hydrating,
|
|
9
|
-
and atoms that already exist, as one read above the boundary, are updated after the first render.
|
|
10
|
-
|
|
11
|
-
With `experimental.async` on, custom server rendering must `await render(...)`, as SvelteKit does,
|
|
12
|
-
so the boundary's `hydratable` entry is written into the page. Otherwise a production build of
|
|
13
|
-
Svelte logs `hydratable_missing_but_expected` once per boundary as the page hydrates.
|
|
14
|
-
|
|
15
|
-
A value for an atom nobody reads waits in the registry until something does. When the boundary
|
|
16
|
-
is destroyed, as at the end of a server render, the values it brought that are still unread are
|
|
17
|
-
dropped, as is a promise-encoded value that lands afterwards, so a registry that outlives the
|
|
18
|
-
boundary doesn't hand them to a later reader. In the browser, a reader that already held the atom
|
|
19
|
-
when the boundary ended and still holds it, as a layout's reader above it, gets the late value.
|
|
3
|
+
Puts the state from `Hydration.dehydrate` (returned by a `load` or remote function) into the
|
|
4
|
+
registry, for the components inside it.
|
|
5
|
+
|
|
6
|
+
Unlike the hooks, an effect or stream atom it hydrates runs again in the browser once read; set
|
|
7
|
+
`skipInitialRun: true` in `Atom.serializable` to keep the hydrated result.
|
|
20
8
|
|
|
21
9
|
**Example** (Hydrating the state a load function dehydrated)
|
|
22
10
|
|
|
@@ -34,6 +22,25 @@
|
|
|
34
22
|
<TodoList />
|
|
35
23
|
</HydrationBoundary>
|
|
36
24
|
```
|
|
25
|
+
|
|
26
|
+
- **When atoms are updated.** Atoms new to the registry, or holding only an initial value nobody
|
|
27
|
+
has read yet, are hydrated before children render. In the browser, atoms that already exist are
|
|
28
|
+
updated after render, so current UI does not jump to the incoming data mid-render. On the
|
|
29
|
+
server, where nothing renders again, and in the browser while it hydrates the server's markup,
|
|
30
|
+
they are updated at once.
|
|
31
|
+
- **Without `experimental.async`.** The boundary still works, but can't update atoms that already
|
|
32
|
+
exist while the page hydrates: the browser can't tell that it is hydrating, so an atom that
|
|
33
|
+
already exists, as one read above the boundary, is updated after the first render.
|
|
34
|
+
- **Custom server rendering.** With `experimental.async` on, a server that renders the page
|
|
35
|
+
itself must `await render(...)`, as SvelteKit does, so the boundary's `hydratable` entry is
|
|
36
|
+
written into the page. Otherwise a production build of Svelte logs
|
|
37
|
+
`hydratable_missing_but_expected` once per boundary as the page hydrates.
|
|
38
|
+
- **Values nobody reads.** A value for an atom nobody reads waits in the registry until something
|
|
39
|
+
does. When the boundary is destroyed, as at the end of a server render, the values it brought
|
|
40
|
+
that are still unread are dropped, as is a promise-encoded value that lands afterwards, so a
|
|
41
|
+
registry that outlives the boundary doesn't hand them to a later reader. In the browser, a
|
|
42
|
+
reader that already held the atom when the boundary ended and still holds it, as a layout's
|
|
43
|
+
reader above it, gets the late value.
|
|
37
44
|
-->
|
|
38
45
|
<script lang="ts">
|
|
39
46
|
import { Hydration } from "effect/reactivity";
|
|
@@ -5,23 +5,11 @@ interface Props {
|
|
|
5
5
|
readonly children: Snippet;
|
|
6
6
|
}
|
|
7
7
|
/**
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* hydrated before children render; in the browser, atoms that already exist are updated after
|
|
11
|
-
* render, so current UI does not jump to the incoming data mid-render. On the server, where nothing
|
|
12
|
-
* renders again, and in the browser while it hydrates the server's markup, they are updated at once.
|
|
13
|
-
* That needs Svelte's `experimental.async`: without it, the browser can't tell that it is hydrating,
|
|
14
|
-
* and atoms that already exist, as one read above the boundary, are updated after the first render.
|
|
8
|
+
* Puts the state from `Hydration.dehydrate` (returned by a `load` or remote function) into the
|
|
9
|
+
* registry, for the components inside it.
|
|
15
10
|
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
* Svelte logs `hydratable_missing_but_expected` once per boundary as the page hydrates.
|
|
19
|
-
*
|
|
20
|
-
* A value for an atom nobody reads waits in the registry until something does. When the boundary
|
|
21
|
-
* is destroyed, as at the end of a server render, the values it brought that are still unread are
|
|
22
|
-
* dropped, as is a promise-encoded value that lands afterwards, so a registry that outlives the
|
|
23
|
-
* boundary doesn't hand them to a later reader. In the browser, a reader that already held the atom
|
|
24
|
-
* when the boundary ended and still holds it, as a layout's reader above it, gets the late value.
|
|
11
|
+
* Unlike the hooks, an effect or stream atom it hydrates runs again in the browser once read; set
|
|
12
|
+
* `skipInitialRun: true` in `Atom.serializable` to keep the hydrated result.
|
|
25
13
|
*
|
|
26
14
|
* **Example** (Hydrating the state a load function dehydrated)
|
|
27
15
|
*
|
|
@@ -39,6 +27,25 @@ interface Props {
|
|
|
39
27
|
* <TodoList />
|
|
40
28
|
* </HydrationBoundary>
|
|
41
29
|
* ```
|
|
30
|
+
*
|
|
31
|
+
* - **When atoms are updated.** Atoms new to the registry, or holding only an initial value nobody
|
|
32
|
+
* has read yet, are hydrated before children render. In the browser, atoms that already exist are
|
|
33
|
+
* updated after render, so current UI does not jump to the incoming data mid-render. On the
|
|
34
|
+
* server, where nothing renders again, and in the browser while it hydrates the server's markup,
|
|
35
|
+
* they are updated at once.
|
|
36
|
+
* - **Without `experimental.async`.** The boundary still works, but can't update atoms that already
|
|
37
|
+
* exist while the page hydrates: the browser can't tell that it is hydrating, so an atom that
|
|
38
|
+
* already exists, as one read above the boundary, is updated after the first render.
|
|
39
|
+
* - **Custom server rendering.** With `experimental.async` on, a server that renders the page
|
|
40
|
+
* itself must `await render(...)`, as SvelteKit does, so the boundary's `hydratable` entry is
|
|
41
|
+
* written into the page. Otherwise a production build of Svelte logs
|
|
42
|
+
* `hydratable_missing_but_expected` once per boundary as the page hydrates.
|
|
43
|
+
* - **Values nobody reads.** A value for an atom nobody reads waits in the registry until something
|
|
44
|
+
* does. When the boundary is destroyed, as at the end of a server render, the values it brought
|
|
45
|
+
* that are still unread are dropped, as is a promise-encoded value that lands afterwards, so a
|
|
46
|
+
* registry that outlives the boundary doesn't hand them to a later reader. In the browser, a
|
|
47
|
+
* reader that already held the atom when the boundary ended and still holds it, as a layout's
|
|
48
|
+
* reader above it, gets the late value.
|
|
42
49
|
*/
|
|
43
50
|
declare const HydrationBoundary: import("svelte").Component<Props, {}, "">;
|
|
44
51
|
type HydrationBoundary = ReturnType<typeof HydrationBoundary>;
|