The best way to control Claude Code, Codex and more from any computer or phone

main
ts 583 lines 18.1 KB
Raw
1 /**
2 * React hooks for working with Effect atoms from components. The hooks read,
3 * write, mount, refresh, and subscribe to atoms from `RegistryContext`, handle
4 * `AsyncResult` atoms with React Suspense, and expose helpers for reading and
5 * deriving `AtomRef` values.
6 *
7 * @stability unstable
8 * @since 4.0.0
9 */
10 "use client"
11
12 import * as Cause from "effect/Cause"
13 import * as Effect from "effect/Effect"
14 import * as Exit from "effect/Exit"
15 import type * as AsyncResult from "effect/reactivity/AsyncResult"
16 import * as Atom from "effect/reactivity/Atom"
17 import type * as AtomRef from "effect/reactivity/AtomRef"
18 import * as AtomRegistry from "effect/reactivity/AtomRegistry"
19 import * as React from "react"
20 import { RegistryContext } from "./RegistryContext.ts"
21
22 interface AtomStore<A> {
23 readonly subscribe: (f: () => void) => () => void
24 readonly snapshot: () => A
25 readonly getServerSnapshot: () => A
26 }
27
28 const storeRegistry = new WeakMap<AtomRegistry.AtomRegistry, WeakMap<Atom.Atom<any>, AtomStore<any>>>()
29
30 // React reads snapshots during render. A first read builds the atom, and its
31 // effect may set other atoms, whose React subscribers must not be notified
32 // mid-render. Those callbacks wait for the reading component's effects, or for
33 // a microtask when that render never commits.
34 let snapshotDepth = 0
35 const deferred = new Set<() => void>()
36
37 function readSnapshot<A>(read: () => A): A {
38 snapshotDepth++
39 try {
40 return read()
41 } finally {
42 snapshotDepth--
43 }
44 }
45
46 function notify(f: () => void): void {
47 if (snapshotDepth === 0) return f()
48 if (deferred.size === 0) queueMicrotask(flushDeferred)
49 deferred.add(f)
50 }
51
52 function flushDeferred(): void {
53 // Set iteration skips callbacks removed by an earlier one and runs added ones
54 for (const f of deferred) {
55 deferred.delete(f)
56 f()
57 }
58 }
59
60 function makeStore<A>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<A>): AtomStore<A> {
61 let stores = storeRegistry.get(registry)
62 if (stores === undefined) {
63 stores = new WeakMap()
64 storeRegistry.set(registry, stores)
65 }
66 const store = stores.get(atom)
67 if (store !== undefined) {
68 return store
69 }
70 // Keep the hydration snapshot while any reader is subscribed, so late
71 // boundaries match the server HTML. SSR has no subscribers and reads fresh values.
72 let subscribers = 0
73 let serverSnapshot: { readonly value: A } | undefined
74 const newStore: AtomStore<A> = {
75 subscribe(f) {
76 subscribers++
77 const unsubscribe = registry.subscribe(atom, () => notify(f))
78 return () => {
79 subscribers--
80 deferred.delete(f)
81 unsubscribe()
82 }
83 },
84 snapshot() {
85 return readSnapshot(() => registry.get(atom))
86 },
87 getServerSnapshot() {
88 if (subscribers === 0 || serverSnapshot === undefined) {
89 serverSnapshot = { value: readSnapshot(() => Atom.getServerValue(atom, registry)) }
90 }
91 return serverSnapshot.value
92 }
93 }
94 stores.set(atom, newStore)
95 return newStore
96 }
97
98 function useStore<A>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<A>): A {
99 const store = makeStore(registry, atom)
100 React.useEffect(flushDeferred)
101 return React.useSyncExternalStore(store.subscribe, store.snapshot, store.getServerSnapshot)
102 }
103
104 function useSelectedStore<A, B>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<A>, f: (_: A) => B): B {
105 const store = makeStore(registry, atom)
106 // Both snapshots must return the same selected value for an unchanged source.
107 const select = React.useMemo(() => {
108 let last: { readonly source: A; readonly value: B } | undefined
109 return (source: A): B => {
110 if (last === undefined || !Object.is(last.source, source)) {
111 last = { source, value: f(source) }
112 }
113 return last.value
114 }
115 }, [f])
116 React.useEffect(flushDeferred)
117 return React.useSyncExternalStore(
118 store.subscribe,
119 () => select(store.snapshot()),
120 () => select(store.getServerSnapshot())
121 )
122 }
123
124 const initialValuesSet = new WeakMap<AtomRegistry.AtomRegistry, WeakSet<Atom.Atom<any>>>()
125
126 /**
127 * Seeds initial atom values in the current React atom registry.
128 *
129 * **When to use**
130 *
131 * Use to seed atom values from a React component after the current registry
132 * already exists.
133 *
134 * **Gotchas**
135 *
136 * Each atom is initialized at most once for a given registry by this hook, so
137 * later calls for the same atom in that registry are ignored.
138 *
139 * @stability unstable
140 * @category hooks
141 * @since 4.0.0
142 */
143 export const useAtomInitialValues = (initialValues: Iterable<readonly [Atom.Atom<any>, any]>): void => {
144 const registry = React.useContext(RegistryContext)
145 let set = initialValuesSet.get(registry)
146 if (set === undefined) {
147 set = new WeakSet()
148 initialValuesSet.set(registry, set)
149 }
150 for (const [atom, value] of initialValues) {
151 if (!set.has(atom)) {
152 set.add(atom)
153 ;(registry as any).ensureNode(atom).setValue(value)
154 }
155 }
156 }
157
158 /**
159 * Subscribes to an atom in the current React registry and returns its current
160 * value, optionally mapped through a selector.
161 *
162 * **When to use**
163 *
164 * Use when a React component needs to render from an atom value without also
165 * returning a setter.
166 *
167 * **Details**
168 *
169 * When a selector is provided, the hook subscribes to the atom and applies the
170 * selector to its value from the current `RegistryContext`.
171 *
172 * **Gotchas**
173 *
174 * Late Suspense boundaries hydrate with the same atom snapshot as earlier
175 * readers, then update to the live value. The snapshot lasts until all readers
176 * unsubscribe. Changes before the first reader hydrates or after the last
177 * unsubscribes can still cause mismatches, as can a derived atom first read
178 * inside a late boundary.
179 *
180 * @see {@link useAtom} for reading and updating a writable atom from one component
181 * @see {@link useAtomRef} for reading an `AtomRef` directly
182 *
183 * @stability unstable
184 * @category hooks
185 * @since 4.0.0
186 */
187 export const useAtomValue: {
188 <A>(atom: Atom.Atom<A>): A
189 <A, B>(atom: Atom.Atom<A>, f: (_: A) => B): B
190 } = <A>(atom: Atom.Atom<A>, f?: (_: A) => A): A => {
191 const registry = React.useContext(RegistryContext)
192 if (f) {
193 return useSelectedStore(registry, atom, f)
194 }
195 return useStore(registry, atom)
196 }
197
198 function mountAtom<A>(registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<A>): void {
199 React.useEffect(() => registry.mount(atom), [atom, registry])
200 }
201
202 function setAtom<R, W, Mode extends "value" | "promise" | "promiseExit" = never>(
203 registry: AtomRegistry.AtomRegistry,
204 atom: Atom.Writable<R, W>,
205 options?: {
206 readonly mode?: ([R] extends [AsyncResult.AsyncResult<any, any>] ? Mode : "value") | undefined
207 }
208 ): "promise" extends Mode ? (
209 (value: W) => Promise<AsyncResult.AsyncResult.Success<R>>
210 ) :
211 "promiseExit" extends Mode ? (
212 (value: W) => Promise<Exit.Exit<AsyncResult.AsyncResult.Success<R>, AsyncResult.AsyncResult.Failure<R>>>
213 ) :
214 ((value: W | ((value: R) => W)) => void)
215 {
216 if (options?.mode === "promise" || options?.mode === "promiseExit") {
217 return React.useCallback((value: W) => {
218 registry.set(atom, value)
219 const promise = Effect.runPromiseExit(
220 AtomRegistry.getResult(registry, atom as Atom.Atom<AsyncResult.AsyncResult<any, any>>, {
221 suspendOnWaiting: true
222 })
223 )
224 return options!.mode === "promise" ? promise.then(flattenExit) : promise
225 }, [registry, atom, options.mode]) as any
226 }
227 return React.useCallback((value: W | ((value: R) => W)) => {
228 registry.set(atom, typeof value === "function" ? (value as any)(registry.get(atom)) : value)
229 }, [registry, atom]) as any
230 }
231
232 const flattenExit = <A, E>(exit: Exit.Exit<A, E>): A => {
233 if (Exit.isSuccess(exit)) return exit.value
234 throw Cause.squash(exit.cause)
235 }
236
237 /**
238 * Mounts an atom in the current React registry for the lifetime of the
239 * component.
240 *
241 * **When to use**
242 *
243 * Use to keep an atom mounted from a React component without reading, writing,
244 * or refreshing it.
245 *
246 * **Details**
247 *
248 * The hook uses the current `RegistryContext` and releases the mount through
249 * React effect cleanup when the component unmounts or when the registry or atom
250 * dependency changes.
251 *
252 * @see {@link useAtomSet} for mounting a writable atom while returning a setter
253 * @see {@link useAtomRefresh} for mounting an atom while returning a refresh callback
254 *
255 * @stability unstable
256 * @category hooks
257 * @since 4.0.0
258 */
259 export const useAtomMount = <A>(atom: Atom.Atom<A>): void => {
260 const registry = React.useContext(RegistryContext)
261 mountAtom(registry, atom)
262 }
263
264 /**
265 * Mounts a writable atom and returns a setter without subscribing to its value.
266 *
267 * **When to use**
268 *
269 * Use when a React component needs to update a writable atom without rendering
270 * from that atom's value.
271 *
272 * **Details**
273 *
274 * The hook mounts the atom and returns a setter. In value mode the setter
275 * accepts a write value or updater function; for `AsyncResult` atoms, `promise`
276 * and `promiseExit` modes return a promise for the success value or full `Exit`.
277 *
278 * **Gotchas**
279 *
280 * In `promise` and `promiseExit` modes, the setter observes the atom's next
281 * settled result, not a result correlated with that write. Overlapping writes
282 * can resolve with another write's result. Serialize writes when each caller
283 * needs its own result.
284 *
285 * @see {@link useAtom} for reading and updating the same writable atom
286 *
287 * @stability unstable
288 * @category hooks
289 * @since 4.0.0
290 */
291 export const useAtomSet = <
292 R,
293 W,
294 Mode extends "value" | "promise" | "promiseExit" = never
295 >(
296 atom: Atom.Writable<R, W>,
297 options?: {
298 readonly mode?: ([R] extends [AsyncResult.AsyncResult<any, any>] ? Mode : "value") | undefined
299 }
300 ): "promise" extends Mode ? (
301 (value: W) => Promise<AsyncResult.AsyncResult.Success<R>>
302 ) :
303 "promiseExit" extends Mode ? (
304 (value: W) => Promise<Exit.Exit<AsyncResult.AsyncResult.Success<R>, AsyncResult.AsyncResult.Failure<R>>>
305 ) :
306 ((value: W | ((value: R) => W)) => void) =>
307 {
308 const registry = React.useContext(RegistryContext)
309 mountAtom(registry, atom)
310 return setAtom(registry, atom, options)
311 }
312
313 /**
314 * Mounts an atom and returns a callback that refreshes it in the current React
315 * registry.
316 *
317 * **When to use**
318 *
319 * Use to expose a React callback that requests a refresh for an atom without
320 * reading or writing its value.
321 *
322 * **Details**
323 *
324 * The hook uses the current `RegistryContext`, mounts the atom for the
325 * component lifetime, and returns a callback that calls `registry.refresh`.
326 *
327 * @see {@link useAtomMount} for mounting an atom without returning a refresh callback
328 *
329 * @stability unstable
330 * @category hooks
331 * @since 4.0.0
332 */
333 export const useAtomRefresh = <A>(atom: Atom.Atom<A>): () => void => {
334 const registry = React.useContext(RegistryContext)
335 mountAtom(registry, atom)
336 return React.useCallback(() => {
337 registry.refresh(atom)
338 }, [registry, atom])
339 }
340
341 /**
342 * Subscribes to a writable atom and returns its current value together with a
343 * setter for updating it.
344 *
345 * **When to use**
346 *
347 * Use when a React component needs both to render the current value of a
348 * writable atom and update it from the same component.
349 *
350 * **Gotchas**
351 *
352 * In `promise` and `promiseExit` modes, the setter observes the atom's next
353 * settled result, not a result correlated with that write. Overlapping writes
354 * can resolve with another write's result. Serialize writes when each caller
355 * needs its own result.
356 *
357 * @see {@link useAtomValue} for subscribing to an atom without a setter
358 * @see {@link useAtomSet} for updating a writable atom without subscribing to its value
359 *
360 * @stability unstable
361 * @category hooks
362 * @since 4.0.0
363 */
364 export const useAtom = <R, W, const Mode extends "value" | "promise" | "promiseExit" = never>(
365 atom: Atom.Writable<R, W>,
366 options?: {
367 readonly mode?: ([R] extends [AsyncResult.AsyncResult<any, any>] ? Mode : "value") | undefined
368 }
369 ): readonly [
370 value: R,
371 write: "promise" extends Mode ? (
372 (value: W) => Promise<AsyncResult.AsyncResult.Success<R>>
373 ) :
374 "promiseExit" extends Mode ? (
375 (value: W) => Promise<Exit.Exit<AsyncResult.AsyncResult.Success<R>, AsyncResult.AsyncResult.Failure<R>>>
376 ) :
377 ((value: W | ((value: R) => W)) => void)
378 ] => {
379 const registry = React.useContext(RegistryContext)
380 return [
381 useStore(registry, atom),
382 setAtom(registry, atom, options)
383 ] as const
384 }
385
386 const atomPromiseMap = {
387 suspendOnWaiting: new WeakMap<
388 AtomRegistry.AtomRegistry,
389 WeakMap<Atom.Atom<any>, Promise<void>>
390 >(),
391 default: new WeakMap<
392 AtomRegistry.AtomRegistry,
393 WeakMap<Atom.Atom<any>, Promise<void>>
394 >()
395 }
396
397 function atomToPromise<A, E>(
398 registry: AtomRegistry.AtomRegistry,
399 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
400 suspendOnWaiting: boolean
401 ) {
402 const registries = suspendOnWaiting ? atomPromiseMap.suspendOnWaiting : atomPromiseMap.default
403 let map = registries.get(registry)
404 if (map === undefined) {
405 map = new WeakMap()
406 registries.set(registry, map)
407 }
408 let promise = map.get(atom)
409 if (promise !== undefined) {
410 return promise
411 }
412 promise = new Promise<void>((resolve) => {
413 const dispose = registry.subscribe(atom, (result) => {
414 if (result._tag === "Initial" || (suspendOnWaiting && result.waiting)) {
415 return
416 }
417 setTimeout(dispose, 1000)
418 resolve()
419 map.delete(atom)
420 })
421 })
422 map.set(atom, promise)
423 return promise
424 }
425
426 function atomResultOrSuspend<A, E>(
427 registry: AtomRegistry.AtomRegistry,
428 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
429 suspendOnWaiting: boolean
430 ) {
431 const value = useStore(registry, atom)
432 if (value._tag === "Initial" || (suspendOnWaiting && value.waiting)) {
433 throw atomToPromise(registry, atom, suspendOnWaiting)
434 }
435 return value
436 }
437
438 /**
439 * Reads an `AsyncResult` atom through React Suspense, suspending while the
440 * result is initial or configured as waiting.
441 *
442 * **When to use**
443 *
444 * Use when a React component should render only after an `AsyncResult` atom has
445 * left its initial state, with loading delegated to a Suspense boundary.
446 *
447 * **Details**
448 *
449 * `suspendOnWaiting` defaults to `false`. When `includeFailure` is `true`, a
450 * failure result is returned instead of being thrown.
451 *
452 * **Gotchas**
453 *
454 * Without `includeFailure`, failure results are thrown with
455 * `Cause.squash(result.cause)`, so callers need an error boundary for failures.
456 *
457 * @see {@link useAtomValue} for reading the raw `AsyncResult` value without Suspense
458 *
459 * @stability unstable
460 * @category hooks
461 * @since 4.0.0
462 */
463 export const useAtomSuspense = <A, E, const IncludeFailure extends boolean = false>(
464 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
465 options?: {
466 readonly suspendOnWaiting?: boolean | undefined
467 readonly includeFailure?: IncludeFailure | undefined
468 }
469 ): AsyncResult.Success<A, E> | (IncludeFailure extends true ? AsyncResult.Failure<A, E> : never) => {
470 const registry = React.useContext(RegistryContext)
471 const result = atomResultOrSuspend(registry, atom, options?.suspendOnWaiting ?? false)
472 if (result._tag === "Failure" && !options?.includeFailure) {
473 throw Cause.squash(result.cause)
474 }
475 return result as any
476 }
477
478 /**
479 * Subscribes a callback to an atom in the current React registry for the
480 * component lifetime.
481 *
482 * **When to use**
483 *
484 * Use when a React component needs to run a callback for atom changes without
485 * reading the atom value during render.
486 *
487 * **Details**
488 *
489 * The subscription is installed in a React effect and cleaned up on unmount or
490 * dependency change. When `options.immediate` is enabled, the callback receives
491 * the current value when the effect subscribes.
492 *
493 * @see {@link useAtomValue} for reading an atom value during render instead of running a callback
494 *
495 * @stability unstable
496 * @category hooks
497 * @since 4.0.0
498 */
499 export const useAtomSubscribe = <A>(
500 atom: Atom.Atom<A>,
501 f: (_: A) => void,
502 options?: { readonly immediate?: boolean }
503 ): void => {
504 const registry = React.useContext(RegistryContext)
505 React.useEffect(
506 () => registry.subscribe(atom, f, options),
507 [registry, atom, f, options?.immediate]
508 )
509 }
510
511 /**
512 * Subscribes to an atom ref and returns its latest value.
513 *
514 * **When to use**
515 *
516 * Use when a React component should render from an `AtomRef.ReadonlyRef`
517 * directly instead of reading an atom through the current registry.
518 *
519 * **Details**
520 *
521 * The hook subscribes with `ref.subscribe`, triggers re-renders through React
522 * state, and returns the current `ref.value`.
523 *
524 * @see {@link useAtomValue} for reading an `Atom` from the current registry
525 * @see {@link useAtomRefPropValue} for reading a property ref value
526 *
527 * @stability unstable
528 * @category hooks
529 * @since 4.0.0
530 */
531 export const useAtomRef = <A>(ref: AtomRef.ReadonlyRef<A>): A => {
532 const [, forceUpdate] = React.useReducer((n) => n + 1, 0)
533 React.useEffect(() => ref.subscribe(forceUpdate), [ref])
534 return ref.value
535 }
536
537 /**
538 * Returns a memoized atom ref for a property of another atom ref.
539 *
540 * **When to use**
541 *
542 * Use to derive an `AtomRef` for one property of an object-shaped atom ref.
543 *
544 * **Details**
545 *
546 * The hook memoizes `ref.prop(prop)` for the `[ref, prop]` dependency pair and
547 * returns the property ref so callers can read, set, update, or subscribe to
548 * that nested property.
549 *
550 * @see {@link useAtomRef} for subscribing to an atom ref value
551 * @see {@link useAtomRefPropValue} for subscribing directly to a property value
552 *
553 * @stability unstable
554 * @category hooks
555 * @since 4.0.0
556 */
557 export const useAtomRefProp = <A, K extends keyof A>(ref: AtomRef.AtomRef<A>, prop: K): AtomRef.AtomRef<A[K]> =>
558 React.useMemo(() => ref.prop(prop), [ref, prop])
559
560 /**
561 * Subscribes to a property ref derived from an atom ref and returns its current
562 * value.
563 *
564 * **When to use**
565 *
566 * Use when a React component needs only the current value of one property from
567 * an object-shaped `AtomRef`.
568 *
569 * **Details**
570 *
571 * The hook composes `useAtomRefProp(ref, prop)` with `useAtomRef`, so the
572 * property ref is memoized for the `[ref, prop]` pair and then subscribed
573 * through `ref.subscribe`.
574 *
575 * @see {@link useAtomRefProp} for returning the property ref directly
576 * @see {@link useAtomRef} for subscribing to a whole atom ref value
577 *
578 * @stability unstable
579 * @category hooks
580 * @since 4.0.0
581 */
582 export const useAtomRefPropValue = <A, K extends keyof A>(ref: AtomRef.AtomRef<A>, prop: K): A[K] =>
583 useAtomRef(useAtomRefProp(ref, prop))