import { raw } from '../helper/html'
import type { HtmlEscapedString } from '../utils/html'
import { JSXFragmentNode } from './base'
import { DOM_RENDERER } from './constants'
import { createContextProviderFunction } from './dom/context'
import type { FC, PropsWithChildren } from './'
export interface Context extends FC> {
values: T[]
Provider: FC>
}
export const globalContexts: Context[] = []
export const createContext = (defaultValue: T): Context => {
const values = [defaultValue]
const context: Context = ((props): HtmlEscapedString | Promise => {
values.push(props.value)
let string
try {
string = props.children
? (Array.isArray(props.children)
? new JSXFragmentNode('', {}, props.children)
: props.children
).toString()
: ''
} catch (e) {
values.pop()
throw e
}
if (string instanceof Promise) {
return string
.finally(() => values.pop())
.then((resString) => raw(resString, (resString as HtmlEscapedString).callbacks))
} else {
values.pop()
return raw(string)
}
}) as Context
context.values = values
context.Provider = context
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(context as any)[DOM_RENDERER] = createContextProviderFunction(values)
globalContexts.push(context as Context)
return context
}
export const useContext = (context: Context): T => {
return context.values.at(-1) as T
}