(
input: {
name: string
init: ((input: Props) => T) | (() => T)
} & (T extends { ready: unknown } ? { gate: boolean } : { gate?: boolean }),
)
| 1 | import { createContext, createMemo, Show, useContext, type ParentProps, type Accessor } from "solid-js" |
| 2 | |
| 3 | export function createSimpleContext<T, Props extends Record<string, any>>( |
| 4 | input: { |
| 5 | name: string |
| 6 | init: ((input: Props) => T) | (() => T) |
| 7 | } & (T extends { ready: unknown } ? { gate: boolean } : { gate?: boolean }), |
| 8 | ) { |
| 9 | const ctx = createContext<T>() |
| 10 | |
| 11 | return { |
| 12 | provider: (props: ParentProps<Props>) => { |
| 13 | const init = input.init(props) |
| 14 | const gate = input.gate ?? true |
| 15 | |
| 16 | if (!gate) { |
| 17 | return <ctx.Provider value={init}>{props.children}</ctx.Provider> |
| 18 | } |
| 19 | |
| 20 | // Access init.ready inside the memo to make it reactive for getter properties |
| 21 | const isReady = createMemo(() => { |
| 22 | // @ts-expect-error |
| 23 | const ready = init.ready as Accessor<boolean> | boolean | undefined |
| 24 | return ready === undefined || (typeof ready === "function" ? ready() : ready) |
| 25 | }) |
| 26 | return ( |
| 27 | <Show when={isReady()}> |
| 28 | <ctx.Provider value={init}>{props.children}</ctx.Provider> |
| 29 | </Show> |
| 30 | ) |
| 31 | }, |
| 32 | use() { |
| 33 | const value = useContext(ctx) |
| 34 | if (!value) throw new Error(`${input.name} context must be used within a context provider`) |
| 35 | return value |
| 36 | }, |
| 37 | } |
| 38 | } |
no test coverage detected