-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChatView.tsx
More file actions
180 lines (160 loc) · 5.84 KB
/
Copy pathChatView.tsx
File metadata and controls
180 lines (160 loc) · 5.84 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import { useRef, useEffect, useCallback } from 'react';
import { useChat, type UseChatOptions } from './chat/use-chat.js';
import { useChatActionLog } from './chat/use-chat-action-log.js';
import { ChatSettings } from './chat/ChatSettings.js';
import { ChatMessage } from './chat/ChatMessage.js';
import { ChatInput } from './chat/ChatInput.js';
import { ChatActionLog } from './chat/ChatActionLog.js';
import { exampleFlows } from './example-flows.js';
import type { MdmaRenderCustomizations } from '@mobile-reality/mdma-renderer-react';
import type { ZodType } from 'zod';
export interface MdmaCustomizations extends MdmaRenderCustomizations {
/** Zod schemas for custom (non-built-in) component types. */
schemas?: Map<string, ZodType>;
}
export interface ChatViewProps {
/** All MDMA customizations bundled in a single prop. */
customizations?: MdmaCustomizations;
/** Custom system prompt. Defaults to the full MDMA author prompt. */
systemPrompt?: string;
/** Suffix appended to user messages. `null` = no suffix. */
userSuffix?: string | null;
/** localStorage key suffix for separate chat histories. */
storageKey?: string;
/** When true, assistant messages can be edited via the Source view. */
editable?: boolean;
}
export function ChatView({ customizations, systemPrompt, userSuffix, storageKey, editable }: ChatViewProps = {}) {
const chatOptions: UseChatOptions = {
...(customizations?.schemas && { parserOptions: { customSchemas: customizations.schemas } }),
...(systemPrompt !== undefined && { systemPrompt }),
...(userSuffix !== undefined && { userSuffix }),
...(storageKey !== undefined && { storageKey }),
};
const {
config,
messages,
input,
setInput,
isGenerating,
error,
inputRef,
updateConfig,
applyPreset,
send,
stop,
clear,
updateMessage,
startFlow,
advanceFlow,
} = useChat(chatOptions);
const advanceFlowRef = useRef(advanceFlow);
advanceFlowRef.current = advanceFlow;
// Subscribe to ACTION_TRIGGERED events on assistant message stores to advance the flow
const subscribedStores = useRef(new Set<import('@mobile-reality/mdma-runtime').DocumentStore>());
useEffect(() => {
for (const msg of messages) {
if (msg.role === 'assistant' && msg.store && !subscribedStores.current.has(msg.store)) {
subscribedStores.current.add(msg.store);
msg.store.getEventBus().on('ACTION_TRIGGERED', () => {
// Small delay so the user sees the interaction before the next step loads
setTimeout(() => advanceFlowRef.current(), 500);
});
}
}
}, [messages]);
// Clean up on unmount
useEffect(() => {
return () => { subscribedStores.current.clear(); };
}, []);
const handleLoadFlow = useCallback((e: React.ChangeEvent<HTMLSelectElement>) => {
const key = e.target.value;
if (!key) return;
const flow = exampleFlows[key];
if (flow) startFlow(flow.steps, flow.customPrompt);
e.target.value = '';
}, [startFlow]);
const { events, isOpen, setIsOpen, clearEvents } = useChatActionLog(messages);
const chatEndRef = useRef<HTMLDivElement>(null);
const prevMsgCountRef = useRef(messages.length);
// Auto-scroll only when new messages are added (not on content edits to existing ones)
useEffect(() => {
if (messages.length > prevMsgCountRef.current) {
chatEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}
prevMsgCountRef.current = messages.length;
}, [messages]);
const handleClear = useCallback(() => {
clear();
clearEvents();
subscribedStores.current.clear();
}, [clear, clearEvents]);
const lastMsgId = messages[messages.length - 1]?.id;
return (
<div className={`chat-layout ${isOpen ? 'chat-layout--with-log' : ''}`}>
<div className="chat-main">
<ChatSettings
config={config}
onUpdate={updateConfig}
onPreset={applyPreset}
/>
<div className="chat-messages">
{messages.length === 0 && (
<div className="chat-empty">
<p className="chat-empty-title">MDMA Chat</p>
<p className="chat-empty-hint">
Describe an interactive document and the AI will generate it, or try an example flow:
</p>
<select
defaultValue=""
onChange={handleLoadFlow}
style={{
padding: '8px 12px',
borderRadius: '6px',
border: '1px solid #d1d5db',
background: '#fff',
color: '#374151',
fontSize: '14px',
cursor: 'pointer',
marginTop: '8px',
minWidth: '220px',
}}
>
<option value="" disabled>Load an example flow…</option>
{Object.entries(exampleFlows).map(([key, flow]) => (
<option key={key} value={key}>{flow.label}</option>
))}
</select>
</div>
)}
{messages.map((msg) => (
<ChatMessage
key={msg.id}
message={msg}
isStreaming={isGenerating && msg.id === lastMsgId}
customizations={customizations}
onEditContent={editable ? updateMessage : undefined}
/>
))}
{error && <div className="chat-error">{error}</div>}
<div ref={chatEndRef} />
</div>
<ChatInput
value={input}
onChange={setInput}
onSend={send}
onStop={stop}
onClear={handleClear}
isGenerating={isGenerating}
hasMessages={messages.length > 0}
inputRef={inputRef}
/>
</div>
<ChatActionLog
events={events}
isOpen={isOpen}
onToggle={() => setIsOpen((prev) => !prev)}
/>
</div>
);
}