-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathroot.tsx
More file actions
60 lines (49 loc) · 2 KB
/
root.tsx
File metadata and controls
60 lines (49 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
'use client'
import { createContext, type ReactNode, useContext } from 'react'
import type { ClientConfig, Collection, ServerConfig } from '@kivotos/core'
import { Toast } from '../intentui/ui/toast'
import type { ServerFunction } from '../server-function'
type RootContextValue<TServerConfig extends ServerConfig = ServerConfig> = {
clientConfig: ClientConfig
serverFunction: ServerFunction<TServerConfig>
}
const RootContext = createContext<RootContextValue>(null!)
export const useRootContext = <TServerConfig extends ServerConfig>() => {
const context = useContext(RootContext)
if (!context) throw new Error('useRootContext must be used within a RootProvider')
return context as unknown as RootContextValue<TServerConfig>
}
export const useCollection = <TCollection extends Collection>(slug: string) => {
const context = useContext(RootContext)
if (!context) throw new Error('useCollection must be used within a RootProvider')
const collection = context.clientConfig.collections[slug] as TCollection | undefined
if (!collection) throw new Error(`Collection ${slug} not found`)
return collection as TCollection // TODO: Fix this to infer from slug
}
export const useClientConfig = () => {
const context = useContext(RootContext)
if (!context) throw new Error('useClientConfig must be used within a RootProvider')
return context.clientConfig
}
export const useServerFunction = <TServerConfig extends ServerConfig>() => {
const context = useContext(RootContext)
if (!context) throw new Error('useCollectionServerFunctions must be used within a RootProvider')
return context.serverFunction as unknown as ServerFunction<TServerConfig>
}
export const RootProvider = (props: {
clientConfig: ClientConfig
serverFunction: ServerFunction<ServerConfig>
children: ReactNode
}) => {
return (
<RootContext.Provider
value={{
clientConfig: props.clientConfig,
serverFunction: props.serverFunction,
}}
>
<Toast />
{props.children}
</RootContext.Provider>
)
}