81 lines
2.7 KiB
TypeScript
81 lines
2.7 KiB
TypeScript
/** biome-ignore-all lint/complexity/useArrowFunction: necessary for class prototypes */
|
|
import { type Context, Effect, Layer, ManagedRuntime, Predicate } from "effect"
|
|
import * as React from "react"
|
|
import * as Component from "./Component.js"
|
|
import * as ErrorObserver from "./ErrorObserver.js"
|
|
import * as QueryClient from "./QueryClient.js"
|
|
|
|
|
|
export const ReactRuntimeTypeId: unique symbol = Symbol.for("@effect-fc/ReactRuntime/ReactRuntime")
|
|
export type ReactRuntimeTypeId = typeof ReactRuntimeTypeId
|
|
|
|
export interface ReactRuntime<R, ER> {
|
|
new(_: never): Record<string, never>
|
|
readonly [ReactRuntimeTypeId]: ReactRuntimeTypeId
|
|
readonly runtime: ManagedRuntime.ManagedRuntime<R, ER>
|
|
readonly context: React.Context<Context.Context<R>>
|
|
}
|
|
|
|
const ReactRuntimeProto = Object.freeze({ [ReactRuntimeTypeId]: ReactRuntimeTypeId } as const)
|
|
|
|
export const preludeLayer: Layer.Layer<
|
|
| Component.ScopeMap
|
|
| ErrorObserver.ErrorObserver
|
|
| QueryClient.QueryClient
|
|
> = Layer.mergeAll(
|
|
Component.ScopeMap.layer,
|
|
ErrorObserver.layer,
|
|
QueryClient.QueryClient.Default,
|
|
)
|
|
|
|
|
|
export const isReactRuntime = (u: unknown): u is ReactRuntime<unknown, unknown> => Predicate.hasProperty(u, TypeId)
|
|
|
|
export const make = <R, ER>(
|
|
layer: Layer.Layer<R, ER>,
|
|
memoMap?: Layer.MemoMap,
|
|
): ReactRuntime<Layer.Success<typeof layer> | R, ER> => Object.setPrototypeOf(
|
|
Object.assign(function() {}, {
|
|
runtime: ManagedRuntime.make(
|
|
Layer.merge(layer, preludeLayer),
|
|
memoMap,
|
|
),
|
|
// biome-ignore lint/style/noNonNullAssertion: context initialization
|
|
context: React.createContext<Context.Context<R>>(null!),
|
|
}),
|
|
ReactRuntimeProto,
|
|
)
|
|
|
|
|
|
export namespace Provider {
|
|
export interface Props<R, ER> extends React.SuspenseProps {
|
|
readonly runtime: ReactRuntime<R, ER>
|
|
readonly children?: React.ReactNode
|
|
}
|
|
}
|
|
|
|
export const Provider = <R, ER>(
|
|
{ runtime, children, ...suspenseProps }: Provider.Props<R, ER>
|
|
): React.ReactNode => {
|
|
Effect.runSync(Component.useOnChange(
|
|
() => Effect.addFinalizer(() => runtime.runtime.disposeEffect),
|
|
[runtime],
|
|
))
|
|
|
|
const promise = React.useMemo(() => runtime.runtime.context(), [runtime])
|
|
|
|
return React.createElement(
|
|
React.Suspense,
|
|
suspenseProps,
|
|
React.createElement(ProviderInner<R, ER>, { runtime, promise, children }),
|
|
)
|
|
}
|
|
|
|
const ProviderInner = <R, ER>(
|
|
{ runtime, promise, children }: {
|
|
readonly runtime: ReactRuntime<R, ER>
|
|
readonly promise: Promise<Context.Context<R>>
|
|
readonly children?: React.ReactNode
|
|
}
|
|
): React.ReactNode => React.createElement(runtime.context, { value: React.use(promise) }, children)
|