|
| 1 | +/** |
| 2 | + * @since 1.0.0 |
| 3 | + */ |
| 4 | +"use client" |
| 5 | +import type * as Atom from "@effect-atom/atom/Atom" |
| 6 | +import * as React from "react" |
| 7 | + |
| 8 | +/** |
| 9 | + * @since 1.0.0 |
| 10 | + * @category Type IDs |
| 11 | + */ |
| 12 | +export type TypeId = "~@effect-atom/atom-react/ScopedAtom" |
| 13 | + |
| 14 | +/** |
| 15 | + * @since 1.0.0 |
| 16 | + * @category Type IDs |
| 17 | + */ |
| 18 | +export const TypeId: TypeId = "~@effect-atom/atom-react/ScopedAtom" |
| 19 | + |
| 20 | +/** |
| 21 | + * @since 1.0.0 |
| 22 | + * @category models |
| 23 | + */ |
| 24 | +export interface ScopedAtom<A extends Atom.Atom<any>, Input = never> { |
| 25 | + readonly [TypeId]: TypeId |
| 26 | + use(): A |
| 27 | + Provider: Input extends never ? React.FC<{ readonly children?: React.ReactNode | undefined }> |
| 28 | + : React.FC<{ readonly children?: React.ReactNode | undefined; readonly value: Input }> |
| 29 | + Context: React.Context<A> |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * @since 1.0.0 |
| 34 | + * @category constructors |
| 35 | + */ |
| 36 | +export const make = <A extends Atom.Atom<any>, Input = never>( |
| 37 | + f: (() => A) | ((input: Input) => A) |
| 38 | +): ScopedAtom<A, Input> => { |
| 39 | + const Context = React.createContext<A>(undefined as unknown as A) |
| 40 | + |
| 41 | + const use = (): A => { |
| 42 | + const atom = React.useContext(Context) |
| 43 | + if (atom === undefined) { |
| 44 | + throw new Error("ScopedAtom used outside of its Provider") |
| 45 | + } |
| 46 | + return atom |
| 47 | + } |
| 48 | + |
| 49 | + const Provider: React.FC<{ readonly children?: React.ReactNode | undefined; readonly value: Input }> = ({ |
| 50 | + children, |
| 51 | + value |
| 52 | + }) => { |
| 53 | + const atom = React.useRef<A | null>(null) |
| 54 | + if (atom.current === null) { |
| 55 | + atom.current = f(value) |
| 56 | + } |
| 57 | + return React.createElement(Context.Provider, { value: atom.current }, children) |
| 58 | + } |
| 59 | + |
| 60 | + return { |
| 61 | + [TypeId]: TypeId, |
| 62 | + use, |
| 63 | + Provider: Provider as any, |
| 64 | + Context |
| 65 | + } |
| 66 | +} |
0 commit comments