Open History to see the last commit
1import { InjectionToken, inject, signal } from '@angular/core'
2import type { WritableSignal } from '@angular/core'
3import type {
4 ChatUIInterrupt,
5 ChatUISelectedPart,
6} from '@tanstack/ai-client/ui'
7import type { InjectChatResult } from '@tanstack/ai-angular'
8
9/**
10 * Holder for the active chat instance. Factory components inject this
11 * and read `host()`.
12 */
13export class ChatHostRef {
14 readonly host: WritableSignal<InjectChatResult | null> = signal(null)
15}
16
17export interface ChatUITokens {
18 chatRef: InjectionToken<ChatHostRef>
19 part: InjectionToken<ChatUISelectedPart>
20 interrupt: InjectionToken<ChatUIInterrupt>
21 injectChatContext: () => InjectChatResult
22}
23
24/**
25 * Create isolated tokens for nested chat trees, or for widgets in other
26 * files that cannot import the `createChatHook` result.
27 */
28export function createChatHookContexts(): ChatUITokens {
29 const chatRef = new InjectionToken<ChatHostRef>('ChatUIHostRef')
30 const part = new InjectionToken<ChatUISelectedPart>('ChatUIPart')
31 const interrupt = new InjectionToken<ChatUIInterrupt>('ChatUIInterrupt')
32
33 function injectChatContext() {
34 const ref = inject(chatRef)
35 const chat = ref.host()
36 if (!chat) {
37 throw new Error(
38 '`injectChatContext` must be used within `Chat` or `ChatProvider`.',
39 )
40 }
41 return chat
42 }
43
44 return { chatRef, part, interrupt, injectChatContext }
45}
46
47export const defaultChatUITokens = createChatHookContexts()