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

main
ts 385 lines 12 KB
Raw
1 /**
2 * Solid hooks for using Effect Atoms from components and computations. The
3 * hooks read and write atoms through the current `RegistryContext`, mount atoms
4 * for cleanup, subscribe callbacks, seed initial values, expose `AsyncResult`
5 * atoms as Solid resources, and read values from `AtomRef` references.
6 *
7 * @stability unstable
8 * @since 4.0.0
9 */
10 import * as Cause from "effect/Cause"
11 import * as Effect from "effect/Effect"
12 import * as Exit from "effect/Exit"
13 import * as AsyncResult from "effect/reactivity/AsyncResult"
14 import * as Atom from "effect/reactivity/Atom"
15 import type * as AtomRef from "effect/reactivity/AtomRef"
16 import * as AtomRegistry from "effect/reactivity/AtomRegistry"
17 import type { Accessor, ResourceOptions, ResourceReturn } from "solid-js"
18 import { createComputed, createEffect, createMemo, createResource, createSignal, onCleanup, useContext } from "solid-js"
19 import { RegistryContext } from "./RegistryContext.ts"
20
21 const initialValuesSet = new WeakMap<AtomRegistry.AtomRegistry, WeakSet<Atom.Atom<any>>>()
22
23 /**
24 * Seeds initial atom values in the current Solid atom registry.
25 *
26 * **When to use**
27 *
28 * Use to seed atom values from a Solid component after the current registry
29 * already exists.
30 *
31 * **Details**
32 *
33 * For each atom in the current registry, this hook applies the first value
34 * supplied through the hook. Later calls for the same atom in that registry are
35 * ignored.
36 *
37 * @stability unstable
38 * @category hooks
39 * @since 4.0.0
40 */
41 export const useAtomInitialValues = (initialValues: Iterable<readonly [Atom.Atom<any>, any]>): void => {
42 const registry = useContext(RegistryContext)
43 let set = initialValuesSet.get(registry)
44 if (set === undefined) {
45 set = new WeakSet()
46 initialValuesSet.set(registry, set)
47 }
48 for (const [atom, value] of initialValues) {
49 if (!set.has(atom)) {
50 set.add(atom)
51 ;(registry as any).ensureNode(atom).setValue(value)
52 }
53 }
54 }
55
56 /**
57 * Subscribes to an atom in the current Solid registry and returns its value as
58 * a Solid accessor.
59 *
60 * @stability unstable
61 * @category hooks
62 * @since 4.0.0
63 */
64 export const useAtomValue: {
65 <A>(atom: () => Atom.Atom<A>): Accessor<A>
66 <A, B>(atom: () => Atom.Atom<A>, f: (_: A) => B): Accessor<B>
67 } = <A>(atom: () => Atom.Atom<A>, f?: (_: A) => A): Accessor<A> => {
68 const registry = useContext(RegistryContext)
69 return createAtomAccessor(registry, f ? () => Atom.map(atom(), f) : atom)
70 }
71
72 function createAtomAccessor<A>(registry: AtomRegistry.AtomRegistry, atom: () => Atom.Atom<A>): Accessor<A> {
73 const [value, setValue] = createSignal<A>(null as any)
74 createComputed(() => {
75 onCleanup(registry.subscribe(atom(), setValue as any, constImmediate))
76 })
77 return value
78 }
79
80 const constImmediate = { immediate: true }
81
82 function mountAtom<A>(registry: AtomRegistry.AtomRegistry, atom: () => Atom.Atom<A>): void {
83 createComputed(() => {
84 onCleanup(registry.mount(atom()))
85 })
86 }
87
88 function setAtom<R, W, Mode extends "value" | "promise" | "promiseExit" = never>(
89 registry: AtomRegistry.AtomRegistry,
90 atom: () => Atom.Writable<R, W>,
91 options?: {
92 readonly mode?: ([R] extends [AsyncResult.AsyncResult<any, any>] ? Mode : "value") | undefined
93 }
94 ): "promise" extends Mode ? (
95 (value: W) => Promise<AsyncResult.AsyncResult.Success<R>>
96 ) :
97 "promiseExit" extends Mode ? (
98 (value: W) => Promise<Exit.Exit<AsyncResult.AsyncResult.Success<R>, AsyncResult.AsyncResult.Failure<R>>>
99 ) :
100 ((value: W | ((value: R) => W)) => void)
101 {
102 const memo = createMemo(atom)
103 if (options?.mode === "promise" || options?.mode === "promiseExit") {
104 return ((value: W) => {
105 registry.set(memo(), value)
106 const promise = Effect.runPromiseExit(
107 AtomRegistry.getResult(registry, memo() as Atom.Atom<AsyncResult.AsyncResult<any, any>>, {
108 suspendOnWaiting: true
109 })
110 )
111 return options!.mode === "promise" ? promise.then(flattenExit) : promise
112 }) as any
113 }
114 return ((value: W | ((value: R) => W)) => {
115 registry.set(memo(), typeof value === "function" ? (value as any)(registry.get(memo())) : value)
116 }) as any
117 }
118
119 const flattenExit = <A, E>(exit: Exit.Exit<A, E>): A => {
120 if (Exit.isSuccess(exit)) return exit.value
121 throw Cause.squash(exit.cause)
122 }
123
124 /**
125 * Mounts an atom in the current Solid registry for the lifetime of the current
126 * Solid computation.
127 *
128 * **When to use**
129 *
130 * Use to keep an atom mounted from a Solid owner without reading, writing, or
131 * refreshing it.
132 *
133 * **Details**
134 *
135 * The hook uses the current `RegistryContext`, mounts inside a Solid
136 * computation, and releases the mount through Solid cleanup when the
137 * computation changes or the owner is disposed.
138 *
139 * @see {@link useAtomSet} for mounting a writable atom while returning a setter
140 * @see {@link useAtomRefresh} for mounting an atom while returning a refresh callback
141 *
142 * @stability unstable
143 * @category hooks
144 * @since 4.0.0
145 */
146 export const useAtomMount = <A>(atom: () => Atom.Atom<A>): void => {
147 const registry = useContext(RegistryContext)
148 mountAtom(registry, atom)
149 }
150
151 /**
152 * Returns a setter for a writable atom without subscribing to its value.
153 *
154 * **Gotchas**
155 *
156 * In `promise` and `promiseExit` modes, the setter observes the atom's next
157 * settled result, not a result correlated with that write. Overlapping writes
158 * can resolve with another write's result. Serialize writes when each caller
159 * needs its own result.
160 *
161 * @stability unstable
162 * @category hooks
163 * @since 4.0.0
164 */
165 export const useAtomSet = <
166 R,
167 W,
168 Mode extends "value" | "promise" | "promiseExit" = never
169 >(
170 atom: () => Atom.Writable<R, W>,
171 options?: {
172 readonly mode?: ([R] extends [AsyncResult.AsyncResult<any, any>] ? Mode : "value") | undefined
173 }
174 ): "promise" extends Mode ? (
175 (value: W) => Promise<AsyncResult.AsyncResult.Success<R>>
176 ) :
177 "promiseExit" extends Mode ? (
178 (value: W) => Promise<Exit.Exit<AsyncResult.AsyncResult.Success<R>, AsyncResult.AsyncResult.Failure<R>>>
179 ) :
180 ((value: W | ((value: R) => W)) => void) =>
181 {
182 const registry = useContext(RegistryContext)
183 mountAtom(registry, atom)
184 return setAtom(registry, atom, options)
185 }
186
187 /**
188 * Mounts an atom and returns a callback that refreshes the current atom.
189 *
190 * @stability unstable
191 * @category hooks
192 * @since 4.0.0
193 */
194 export const useAtomRefresh = <A>(atom: () => Atom.Atom<A>): () => void => {
195 const registry = useContext(RegistryContext)
196 mountAtom(registry, atom)
197 const memo = createMemo(atom)
198 return () => registry.refresh(memo())
199 }
200
201 /**
202 * Returns a Solid accessor for a writable atom together with a setter for
203 * updating it.
204 *
205 * **When to use**
206 *
207 * Use when a Solid component or computation needs both a reactive accessor for
208 * a writable atom and a write function for that same atom.
209 *
210 * **Details**
211 *
212 * The setter accepts either a write value or an updater function. For
213 * `AsyncResult` atoms, `promise` and `promiseExit` modes return promises for the
214 * success value or full `Exit`.
215 *
216 * **Gotchas**
217 *
218 * In `promise` and `promiseExit` modes, the setter observes the atom's next
219 * settled result, not a result correlated with that write. Overlapping writes
220 * can resolve with another write's result. Serialize writes when each caller
221 * needs its own result.
222 *
223 * @see {@link useAtomValue} for subscribing to an atom without a setter
224 * @see {@link useAtomSet} for updating a writable atom without subscribing to its value
225 *
226 * @stability unstable
227 * @category hooks
228 * @since 4.0.0
229 */
230 export const useAtom = <R, W, const Mode extends "value" | "promise" | "promiseExit" = never>(
231 atom: () => Atom.Writable<R, W>,
232 options?: {
233 readonly mode?: ([R] extends [AsyncResult.AsyncResult<any, any>] ? Mode : "value") | undefined
234 }
235 ): readonly [
236 value: Accessor<R>,
237 write: "promise" extends Mode ? (
238 (value: W) => Promise<AsyncResult.AsyncResult.Success<R>>
239 ) :
240 "promiseExit" extends Mode ? (
241 (value: W) => Promise<Exit.Exit<AsyncResult.AsyncResult.Success<R>, AsyncResult.AsyncResult.Failure<R>>>
242 ) :
243 ((value: W | ((value: R) => W)) => void)
244 ] => {
245 const registry = useContext(RegistryContext)
246 return [
247 createAtomAccessor(registry, atom),
248 setAtom(registry, atom, options)
249 ] as const
250 }
251
252 /**
253 * Subscribes a callback to an atom in the current Solid registry.
254 *
255 * @stability unstable
256 * @category hooks
257 * @since 4.0.0
258 */
259 export const useAtomSubscribe = <A>(
260 atom: () => Atom.Atom<A>,
261 f: (_: A) => void,
262 options?: { readonly immediate?: boolean }
263 ): void => {
264 const registry = useContext(RegistryContext)
265 createEffect(() => {
266 onCleanup(registry.subscribe(atom(), f, options))
267 })
268 }
269
270 /**
271 * Converts an `AsyncResult` atom into a Solid resource.
272 *
273 * @stability unstable
274 * @category hooks
275 * @since 4.0.0
276 */
277 export const useAtomResource = <A, E>(
278 atom: () => Atom.Atom<AsyncResult.AsyncResult<A, E>>,
279 options?: ResourceOptions<A> & {
280 readonly suspendOnWaiting?: boolean | undefined
281 }
282 ): ResourceReturn<A, void> => {
283 const result = useAtomValue(atom)
284 return createResource(result, (result) => {
285 if (AsyncResult.isInitial(result) || (options?.suspendOnWaiting && result.waiting)) {
286 return constUnresolvedPromise
287 } else if (AsyncResult.isSuccess(result)) {
288 return Promise.resolve(result.value)
289 }
290 return Promise.reject(Cause.squash(result.cause))
291 })
292 }
293
294 const constUnresolvedPromise = new Promise<never>(() => {})
295
296 /**
297 * Subscribes to an atom ref and returns its value as a Solid accessor.
298 *
299 * **When to use**
300 *
301 * Use when a Solid component or computation should render from an
302 * `AtomRef.ReadonlyRef` directly instead of reading an atom through the current
303 * registry.
304 *
305 * **Details**
306 *
307 * The hook accepts a thunk for the ref, reads `ref().value`, subscribes with
308 * `ref.subscribe`, and releases the subscription through Solid cleanup when
309 * the selected ref changes or the owner is disposed.
310 *
311 * @see {@link useAtomValue} for reading an `Atom` from the current registry
312 * @see {@link useAtomRefPropValue} for reading a property ref value
313 *
314 * @stability unstable
315 * @category hooks
316 * @since 4.0.0
317 */
318 export const useAtomRef = <A>(ref: () => AtomRef.ReadonlyRef<A>): Accessor<A> => {
319 const [value, setValue] = createSignal(null as A)
320 createComputed(() => {
321 const r = ref()
322 setValue(r.value as any)
323 onCleanup(r.subscribe(setValue))
324 })
325 return value
326 }
327
328 /**
329 * Returns a Solid accessor for a property ref derived from an atom ref.
330 *
331 * **When to use**
332 *
333 * Use to derive an `AtomRef` for one property of an object-shaped atom ref in a
334 * Solid computation.
335 *
336 * **Details**
337 *
338 * The returned accessor memoizes `ref().prop(prop)`, updating when the source
339 * ref thunk produces a different ref.
340 *
341 * **Gotchas**
342 *
343 * The `prop` argument is captured as a plain value. Recreate the hook call when
344 * the property key should change.
345 *
346 * @see {@link useAtomRef} for subscribing to an atom ref value
347 * @see {@link useAtomRefPropValue} for subscribing directly to a property value
348 *
349 * @stability unstable
350 * @category hooks
351 * @since 4.0.0
352 */
353 export const useAtomRefProp = <A, K extends keyof A>(
354 ref: () => AtomRef.AtomRef<A>,
355 prop: K
356 ): Accessor<AtomRef.AtomRef<A[K]>> => createMemo(() => ref().prop(prop))
357
358 /**
359 * Returns a Solid accessor for the value of a property ref derived from an atom
360 * ref.
361 *
362 * **When to use**
363 *
364 * Use when a Solid component or computation needs the value of one property
365 * from an object-shaped `AtomRef` without keeping the intermediate property ref.
366 *
367 * **Details**
368 *
369 * The hook composes `useAtomRefProp(ref, prop)` with `useAtomRef`, returning a
370 * Solid accessor for the selected property value.
371 *
372 * **Gotchas**
373 *
374 * The `prop` argument is captured as a plain value. Recreate the hook call when
375 * the property key should change.
376 *
377 * @see {@link useAtomRef} for subscribing to a whole atom ref value
378 * @see {@link useAtomRefProp} for returning the property ref directly
379 *
380 * @stability unstable
381 * @category hooks
382 * @since 4.0.0
383 */
384 export const useAtomRefPropValue = <A, K extends keyof A>(ref: () => AtomRef.AtomRef<A>, prop: K): Accessor<A[K]> =>
385 useAtomRef(useAtomRefProp(ref, prop))