@@ -0,0 +1,71 @@
|
||||
/** biome-ignore-all lint/complexity/useArrowFunction: React component names are intentional */
|
||||
import { Context, Layer, ManagedRuntime, Predicate } from "effect"
|
||||
import * as React from "react"
|
||||
import * as ErrorObserver from "./ErrorObserver.js"
|
||||
import * as QueryClient from "./QueryClient.js"
|
||||
|
||||
|
||||
export const TypeId: unique symbol = Symbol.for("@effect-fc/ReactRuntime/ReactRuntime")
|
||||
export type TypeId = typeof TypeId
|
||||
|
||||
export interface ReactRuntime<R, ER> {
|
||||
new(_: never): Record<string, never>
|
||||
readonly [TypeId]: TypeId
|
||||
readonly runtime: ManagedRuntime.ManagedRuntime<R, ER>
|
||||
readonly context: React.Context<Context.Context<R>>
|
||||
}
|
||||
|
||||
const ReactRuntimeProto = Object.freeze({ [TypeId]: TypeId } as const)
|
||||
|
||||
export const Prelude: Layer.Layer<ErrorObserver.ErrorObserver | QueryClient.QueryClient> = Layer.merge(
|
||||
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<R | ErrorObserver.ErrorObserver | QueryClient.QueryClient, ER> => Object.setPrototypeOf(
|
||||
Object.assign(function() {}, {
|
||||
runtime: ManagedRuntime.make(Layer.merge(layer, Prelude), { memoMap }),
|
||||
// biome-ignore lint/style/noNonNullAssertion: initialized by Provider before consumers render
|
||||
context: React.createContext<Context.Context<R | ErrorObserver.ErrorObserver | QueryClient.QueryClient>>(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 => {
|
||||
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 => {
|
||||
const context = React.use(promise)
|
||||
React.useEffect(() => () => {
|
||||
void runtime.runtime.dispose()
|
||||
}, [runtime])
|
||||
|
||||
return React.createElement(runtime.context, { value: context }, children)
|
||||
}
|
||||
Reference in New Issue
Block a user