Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

create-ui-contexts.tsx

57 lines1.9 KB

1import { createContext, useContext } from 'react'
2import type { Context } from 'react'
3import type {
4 ChatUIInterrupt,
5 ChatUISelectedPart,
6} from '@tanstack/ai-client/ui'
7import type { UseChatReturn } from '../types'
8​
9/**
10 * Scoped chat, part, and interrupt contexts plus matching context hooks.
11 * Pass these into {@link createChatHook} when widgets live in other files, or
12 * when two chat trees nest and must not share the default contexts.
13 */
14export interface ChatUIContexts {
15 chatContext: Context<UseChatReturn<any, any, any> | null>
16 partContext: Context<ChatUISelectedPart | null>
17 interruptContext: Context<ChatUIInterrupt | null>
18 useChatContext: () => UseChatReturn<any, any, any>
20​
21/**
22 * Create a fresh set of chat UI contexts. This matches Form
23 * `createFormHookContexts` and Table `createTableHookContexts`.
24 *
25 * Most apps can skip this. `createChatHook` uses shared module contexts by
26 * default. The hooks on this object are the escape hatch for a widget file
27 * that cannot import the `createChatHook` result (circular import), or for
28 * nested chats that need isolated providers.
29 *
30 * Prefer the `useChatContext` hook returned from `createChatHook` when you
31 * can import that result. That hook knows the `chatComponents` types. Part
32 * and interrupt widgets take `part` / `interrupt` as props.
33 */
34export function createChatHookContexts(): ChatUIContexts {
35 const chatContext = createContext<UseChatReturn<any, any, any> | null>(null)
36 const partContext = createContext<ChatUISelectedPart | null>(null)
37 const interruptContext = createContext<ChatUIInterrupt | null>(null)
38​
39 function useChatContext() {
40 const chat = useContext(chatContext)
41 if (!chat) {
42 throw new Error(
43 '`useChatContext` must be used within `UI.Provider` or `UI.Chat`.',
44 )
45 }
46 return chat
47 }
48​
49 return {
50 chatContext,
51 partContext,
52 interruptContext,
53 useChatContext,
54 }
56​
57export const defaultChatUIContexts = createChatHookContexts()