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

create-chat-hook.ts

74 lines2.2 KB

1import { assertInInjectionContext } from '@angular/core'
2import type { Type } from '@angular/core'
3import { injectChat } from '@tanstack/ai-angular'
4import type { InjectChatOptions } from '@tanstack/ai-angular'
5import { createChatUI } from './create-ui'
6import type { ChatUIFactoryConfig, ChatUIHost, InputProps } from './create-ui'
7import type {
8 ChatUIInterruptsOf,
9 ChatUISchemaOf,
10 ChatUIToolsOf,
11} from '@tanstack/ai-client/ui'
12import type { InferredClientContext } from '@tanstack/ai-client'
13​
14type HeadlessOptions<TOptions> = InjectChatOptions<
15 ChatUIToolsOf<TOptions>,
16 ChatUISchemaOf<TOptions>,
17 InferredClientContext<ChatUIToolsOf<TOptions>>,
18 ChatUIInterruptsOf<TOptions>
20​
21type ChatInstanceOverrides<TOptions> = {
22 threadId: string
23 live?: HeadlessOptions<TOptions>['live']
24 forwardedProps?: HeadlessOptions<TOptions>['forwardedProps']
25 initialMessages?: HeadlessOptions<TOptions>['initialMessages']
27​
28/**
29 * Bind chat options and Angular widgets once at module scope.
30 *
31 * This matches Form `injectForm` and the React `createChatHook` factory:
32 * widgets register here. The returned `injectAppChat` creates a chat
33 * instance in an injection context. Render `<ai-chat [chat]="chat" />`
34 * with the factory `Chat` component.
35 */
36export function createChatHook<
37 const TOptions,
38 TInput extends Type<unknown> | undefined = Type<unknown> | undefined,
39>({
40 options,
41 ...chatComponents
42}: {
43 options: TOptions
44} & ChatUIFactoryConfig<NoInfer<TOptions>, TInput>) {
45 const ui = createChatUI(
46 options,
47 chatComponents as ChatUIFactoryConfig<NoInfer<TOptions>, TInput>,
48 )
49​
50 function injectAppChat(overrides: ChatInstanceOverrides<TOptions>) {
51 assertInInjectionContext(injectAppChat)
52 const chat = injectChat({
53 ...(options as HeadlessOptions<TOptions>),
54 ...overrides,
55 }) as ChatUIHost<TOptions>
56 return chat
57 }
58​
59 return {
60 injectAppChat,
61 injectChatContext: ui.injectChatContext,
62 Chat: ui.Chat,
63 ChatProvider: ui.ChatProvider,
64 } as {
65 injectAppChat: (
66 overrides: ChatInstanceOverrides<TOptions>,
67 ) => ChatUIHost<TOptions>
68 injectChatContext: () => ChatUIHost<TOptions>
69 Chat: Type<unknown>
70 ChatProvider: Type<unknown>
71 }
73​
74export type { InputProps }