@anvia/react-ui 1.2.2 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/attachment/index.d.ts +3 -21
  2. package/dist/attachment/index.js +3 -12
  3. package/dist/attachment-DsKTPumt.js +89 -0
  4. package/dist/attachment-DsKTPumt.js.map +1 -0
  5. package/dist/chat/index.d.ts +3 -144
  6. package/dist/chat/index.js +3 -25
  7. package/dist/chat-CAnvUEAv.js +1210 -0
  8. package/dist/chat-CAnvUEAv.js.map +1 -0
  9. package/dist/completion/index.d.ts +3 -29
  10. package/dist/completion/index.js +3 -16
  11. package/dist/completion-DDTKoZRJ.js +124 -0
  12. package/dist/completion-DDTKoZRJ.js.map +1 -0
  13. package/dist/connection-DeNq8wHS.js +203 -0
  14. package/dist/connection-DeNq8wHS.js.map +1 -0
  15. package/dist/contexts-B4ijG24z.js +212 -0
  16. package/dist/contexts-B4ijG24z.js.map +1 -0
  17. package/dist/elements-D4vmkkF8.js +19 -0
  18. package/dist/elements-D4vmkkF8.js.map +1 -0
  19. package/dist/graph-explorer/index.d.ts +54 -73
  20. package/dist/graph-explorer/index.d.ts.map +1 -0
  21. package/dist/graph-explorer/index.js +181 -248
  22. package/dist/graph-explorer/index.js.map +1 -1
  23. package/dist/human-input/index.d.ts +3 -78
  24. package/dist/human-input/index.js +3 -21
  25. package/dist/human-input-CsCbZomZ.js +314 -0
  26. package/dist/human-input-CsCbZomZ.js.map +1 -0
  27. package/dist/image/index.d.ts +3 -40
  28. package/dist/image/index.js +3 -12
  29. package/dist/image-D_7vaQCR.js +302 -0
  30. package/dist/image-D_7vaQCR.js.map +1 -0
  31. package/dist/index-B1Qs2Cjv.d.ts +145 -0
  32. package/dist/index-B1Qs2Cjv.d.ts.map +1 -0
  33. package/dist/index-BCBVcl0D.d.ts +277 -0
  34. package/dist/index-BCBVcl0D.d.ts.map +1 -0
  35. package/dist/index-CE22tsua.d.ts +20 -0
  36. package/dist/index-CE22tsua.d.ts.map +1 -0
  37. package/dist/index-CGqtpc6b.d.ts +25 -0
  38. package/dist/index-CGqtpc6b.d.ts.map +1 -0
  39. package/dist/index-DqdyM0Jm.d.ts +7 -0
  40. package/dist/index-DqdyM0Jm.d.ts.map +1 -0
  41. package/dist/index-Mw3ltwSG.d.ts +318 -0
  42. package/dist/index-Mw3ltwSG.d.ts.map +1 -0
  43. package/dist/index.d.ts +7 -40
  44. package/dist/index.js +34 -118
  45. package/dist/index.js.map +1 -1
  46. package/dist/message/index.d.ts +3 -105
  47. package/dist/message/index.js +3 -20
  48. package/dist/message-Dn3wW6yy.js +783 -0
  49. package/dist/message-Dn3wW6yy.js.map +1 -0
  50. package/dist/primitives-xfE7zfwJ.js +15 -0
  51. package/dist/primitives-xfE7zfwJ.js.map +1 -0
  52. package/dist/refs-Djj9rSvB.js +10 -0
  53. package/dist/refs-Djj9rSvB.js.map +1 -0
  54. package/dist/sandbox-desktop/index.d.ts +100 -104
  55. package/dist/sandbox-desktop/index.d.ts.map +1 -0
  56. package/dist/sandbox-desktop/index.js +344 -342
  57. package/dist/sandbox-desktop/index.js.map +1 -1
  58. package/dist/sandbox-terminal/index.d.ts +52 -56
  59. package/dist/sandbox-terminal/index.d.ts.map +1 -0
  60. package/dist/sandbox-terminal/index.js +217 -208
  61. package/dist/sandbox-terminal/index.js.map +1 -1
  62. package/dist/selection-toolbar/index.d.ts +3 -21
  63. package/dist/selection-toolbar/index.js +3 -13
  64. package/dist/selection-toolbar-CIkOoM-7.js +171 -0
  65. package/dist/selection-toolbar-CIkOoM-7.js.map +1 -0
  66. package/dist/shared-BSYElFU2.d.ts +2 -0
  67. package/dist/shared.d.ts +4 -14
  68. package/dist/shared.js +1 -43
  69. package/dist/stream/index.d.ts +2 -22
  70. package/dist/stream/index.js +1 -8
  71. package/dist/stream-CAO0x8_1.js +298 -0
  72. package/dist/stream-CAO0x8_1.js.map +1 -0
  73. package/dist/thread-list/index.d.ts +3 -47
  74. package/dist/thread-list/index.js +3 -18
  75. package/dist/thread-list-xJbGXFrE.js +228 -0
  76. package/dist/thread-list-xJbGXFrE.js.map +1 -0
  77. package/dist/ticket-CoJHBpdF.d.ts +32 -0
  78. package/dist/ticket-CoJHBpdF.d.ts.map +1 -0
  79. package/dist/value-BGGrx72L.js +13 -0
  80. package/dist/value-BGGrx72L.js.map +1 -0
  81. package/package.json +22 -22
  82. package/dist/attachment/index.js.map +0 -1
  83. package/dist/attachment-mbjsroli.d.ts +0 -9
  84. package/dist/chat/index.js.map +0 -1
  85. package/dist/chat-PSj1Fo4W.d.ts +0 -88
  86. package/dist/chunk-22EZJUPM.js +0 -120
  87. package/dist/chunk-22EZJUPM.js.map +0 -1
  88. package/dist/chunk-5FZKTDZR.js +0 -201
  89. package/dist/chunk-5FZKTDZR.js.map +0 -1
  90. package/dist/chunk-6XOJFLX4.js +0 -22
  91. package/dist/chunk-6XOJFLX4.js.map +0 -1
  92. package/dist/chunk-CKA4CE26.js +0 -25
  93. package/dist/chunk-CKA4CE26.js.map +0 -1
  94. package/dist/chunk-DLBNFBXQ.js +0 -425
  95. package/dist/chunk-DLBNFBXQ.js.map +0 -1
  96. package/dist/chunk-E73S3SOF.js +0 -404
  97. package/dist/chunk-E73S3SOF.js.map +0 -1
  98. package/dist/chunk-F6AKBUO3.js +0 -380
  99. package/dist/chunk-F6AKBUO3.js.map +0 -1
  100. package/dist/chunk-HGOPGZNQ.js +0 -195
  101. package/dist/chunk-HGOPGZNQ.js.map +0 -1
  102. package/dist/chunk-KHB5CHAU.js +0 -220
  103. package/dist/chunk-KHB5CHAU.js.map +0 -1
  104. package/dist/chunk-LHABOAOP.js +0 -316
  105. package/dist/chunk-LHABOAOP.js.map +0 -1
  106. package/dist/chunk-N5XQU36W.js +0 -410
  107. package/dist/chunk-N5XQU36W.js.map +0 -1
  108. package/dist/chunk-T3ZFZ3NP.js +0 -30
  109. package/dist/chunk-T3ZFZ3NP.js.map +0 -1
  110. package/dist/chunk-W2AHKMRS.js +0 -1092
  111. package/dist/chunk-W2AHKMRS.js.map +0 -1
  112. package/dist/chunk-Y2KAMPVJ.js +0 -1582
  113. package/dist/chunk-Y2KAMPVJ.js.map +0 -1
  114. package/dist/completion/index.js.map +0 -1
  115. package/dist/completion-input-DHlwrhxB.d.ts +0 -24
  116. package/dist/composer-6iCSIq6L.d.ts +0 -111
  117. package/dist/human-input/index.js.map +0 -1
  118. package/dist/human-input-CkLrZ8IC.d.ts +0 -27
  119. package/dist/image/index.js.map +0 -1
  120. package/dist/image-VZv6Ddsn.d.ts +0 -14
  121. package/dist/message/index.js.map +0 -1
  122. package/dist/message-CNRnZQwU.d.ts +0 -14
  123. package/dist/render-CRKWam2v.d.ts +0 -8
  124. package/dist/selection-toolbar/index.js.map +0 -1
  125. package/dist/selection-toolbar-Cwjbuv5S.d.ts +0 -14
  126. package/dist/shared.js.map +0 -1
  127. package/dist/stream/index.js.map +0 -1
  128. package/dist/thread-Bz6-1zaJ.d.ts +0 -12
  129. package/dist/thread-list/index.js.map +0 -1
  130. package/dist/thread-list-On8db4XL.d.ts +0 -34
  131. package/dist/ticket-pexI1zIa.d.ts +0 -33
@@ -1,1582 +0,0 @@
1
- import {
2
- MessagePrimitive,
3
- isComposerEntityData,
4
- shiftComposerEntityRanges
5
- } from "./chunk-W2AHKMRS.js";
6
- import {
7
- AttachmentPrimitive
8
- } from "./chunk-22EZJUPM.js";
9
- import {
10
- composeRefs,
11
- renderPrimitive
12
- } from "./chunk-T3ZFZ3NP.js";
13
- import {
14
- InternalAttachmentProvider,
15
- InternalComposerProvider,
16
- InternalMessageProvider,
17
- InternalThreadProvider,
18
- useChatContext,
19
- useComposer,
20
- useThread
21
- } from "./chunk-E73S3SOF.js";
22
-
23
- // src/chat/composer.tsx
24
- import { mergeAttributes } from "@tiptap/core";
25
- import Document from "@tiptap/extension-document";
26
- import HardBreak from "@tiptap/extension-hard-break";
27
- import Mention from "@tiptap/extension-mention";
28
- import Paragraph from "@tiptap/extension-paragraph";
29
- import Placeholder from "@tiptap/extension-placeholder";
30
- import Text from "@tiptap/extension-text";
31
- import { PluginKey } from "@tiptap/pm/state";
32
- import { EditorContent, useEditor } from "@tiptap/react";
33
- import {
34
- forwardRef,
35
- useCallback,
36
- useEffect,
37
- useMemo,
38
- useRef,
39
- useState
40
- } from "react";
41
- import { Fragment, jsx, jsxs } from "react/jsx-runtime";
42
- var ComposerRoot = forwardRef(function ComposerRoot2({
43
- attachments: attachmentsProp,
44
- defaultAttachments,
45
- defaultEntities,
46
- defaultInput = "",
47
- defaultQuote,
48
- entities: entitiesProp,
49
- input: inputProp,
50
- onAttachmentsChange,
51
- onEntitiesChange,
52
- onInputChange,
53
- onQuoteChange,
54
- quote: quoteProp,
55
- submitMessage,
56
- triggers: triggersProp,
57
- onSubmit,
58
- ...props
59
- }, ref) {
60
- const chat = useChatContext();
61
- const [uncontrolledInput, setUncontrolledInput] = useState(defaultInput);
62
- const [uncontrolledAttachments, setUncontrolledAttachments] = useState(() => [
63
- ...defaultAttachments ?? []
64
- ]);
65
- const [uncontrolledEntities, setUncontrolledEntities] = useState(() => [
66
- ...defaultEntities ?? []
67
- ]);
68
- const [uncontrolledQuote, setUncontrolledQuote] = useState(
69
- defaultQuote
70
- );
71
- const [activeTrigger, setActiveTriggerState] = useState();
72
- const input = inputProp ?? uncontrolledInput;
73
- const attachments = attachmentsProp ?? uncontrolledAttachments;
74
- const entities = entitiesProp ?? uncontrolledEntities;
75
- const triggers = triggersProp ?? EMPTY_COMPOSER_TRIGGERS;
76
- const rawQuote = quoteProp ?? uncontrolledQuote;
77
- const rawQuoteMessageId = rawQuote?.messageId;
78
- const rawQuoteText = rawQuote?.text;
79
- const quote = useMemo(
80
- () => rawQuoteMessageId === void 0 || rawQuoteText === void 0 ? void 0 : { messageId: rawQuoteMessageId, text: rawQuoteText },
81
- [rawQuoteMessageId, rawQuoteText]
82
- );
83
- const attachmentsRef = useRef(attachments);
84
- attachmentsRef.current = attachments;
85
- const entitiesRef = useRef(entities);
86
- entitiesRef.current = entities;
87
- const defaultSubmissionInFlightRef = useRef(false);
88
- const inputControlled = inputProp !== void 0;
89
- const attachmentsControlled = attachmentsProp !== void 0;
90
- const entitiesControlled = entitiesProp !== void 0;
91
- const quoteControlled = quoteProp !== void 0;
92
- const hasMessageContent = input.trim().length > 0 || attachments.length > 0 || entities.length > 0 || quote !== void 0;
93
- const active = chat.status === "submitted" || chat.status === "streaming";
94
- const canSubmit = hasMessageContent && !active;
95
- const canStop = active;
96
- const setInput = useCallback(
97
- (nextInput) => {
98
- if (!inputControlled) {
99
- setUncontrolledInput(nextInput);
100
- }
101
- onInputChange?.(nextInput);
102
- },
103
- [inputControlled, onInputChange]
104
- );
105
- const setAttachments = useCallback(
106
- (update) => {
107
- const nextAttachments = typeof update === "function" ? update(attachmentsRef.current) : update;
108
- attachmentsRef.current = nextAttachments;
109
- if (!attachmentsControlled) {
110
- setUncontrolledAttachments(nextAttachments);
111
- }
112
- onAttachmentsChange?.(nextAttachments);
113
- },
114
- [attachmentsControlled, onAttachmentsChange]
115
- );
116
- const setEntities = useCallback(
117
- (update) => {
118
- const nextEntities = typeof update === "function" ? update(entitiesRef.current) : update;
119
- entitiesRef.current = nextEntities;
120
- if (!entitiesControlled) {
121
- setUncontrolledEntities(nextEntities);
122
- }
123
- onEntitiesChange?.(nextEntities);
124
- },
125
- [entitiesControlled, onEntitiesChange]
126
- );
127
- const setQuote = useCallback(
128
- (nextQuote) => {
129
- const normalizedQuote = normalizeQuote(nextQuote);
130
- if (!quoteControlled) {
131
- setUncontrolledQuote(normalizedQuote);
132
- }
133
- onQuoteChange?.(normalizedQuote);
134
- },
135
- [onQuoteChange, quoteControlled]
136
- );
137
- const addAttachment = useCallback(
138
- async (attachment) => {
139
- const normalized = isFileAttachmentInput(attachment) ? await attachmentFromFile(attachment) : createAttachment(attachment);
140
- setAttachments((current) => [...current, normalized]);
141
- },
142
- [setAttachments]
143
- );
144
- const removeAttachment = useCallback(
145
- (id) => {
146
- setAttachments((current) => current.filter((attachment) => attachment.id !== id));
147
- },
148
- [setAttachments]
149
- );
150
- const clearAttachments = useCallback(() => {
151
- setAttachments([]);
152
- }, [setAttachments]);
153
- const clearQuote = useCallback(() => {
154
- setQuote(void 0);
155
- }, [setQuote]);
156
- const clear = useCallback(() => {
157
- setInput("");
158
- setAttachments([]);
159
- setEntities([]);
160
- setActiveTriggerState(void 0);
161
- clearQuote();
162
- }, [clearQuote, setAttachments, setEntities, setInput]);
163
- const submit = useCallback(async () => {
164
- const prompt = input;
165
- if (prompt.trim().length === 0 && attachments.length === 0 && entities.length === 0 && quote === void 0 || chat.status === "submitted" || chat.status === "streaming") {
166
- return;
167
- }
168
- assertComposerEntitiesData(entities);
169
- if (submitMessage !== void 0) {
170
- await submitMessage({
171
- input: prompt,
172
- attachments,
173
- entities,
174
- chat,
175
- quote,
176
- clear
177
- });
178
- return;
179
- }
180
- if (defaultSubmissionInFlightRef.current) {
181
- return;
182
- }
183
- const submittedAttachments = [...attachments];
184
- const submittedQuote = quote === void 0 ? void 0 : { ...quote };
185
- const formattedPrompt = submittedQuote === void 0 ? { text: prompt, prefixLength: 0 } : promptWithQuote(prompt, submittedQuote);
186
- const submittedEntities = shiftComposerEntityRanges(
187
- [...entities],
188
- formattedPrompt.prefixLength
189
- );
190
- const submittedText = formattedPrompt.text;
191
- const metadata = composerSubmitMetadata(submittedQuote, submittedEntities);
192
- let payload;
193
- if (submittedAttachments.length === 0) {
194
- payload = metadata === void 0 ? { text: submittedText } : { text: submittedText, metadata };
195
- } else {
196
- const attachmentPayload = {
197
- text: submittedText,
198
- attachments: submittedAttachments
199
- };
200
- if (metadata !== void 0) attachmentPayload.metadata = metadata;
201
- payload = attachmentPayload;
202
- }
203
- defaultSubmissionInFlightRef.current = true;
204
- try {
205
- const submission = chat.sendMessage(payload);
206
- clear();
207
- await submission;
208
- } finally {
209
- defaultSubmissionInFlightRef.current = false;
210
- }
211
- }, [attachments, chat, clear, entities, input, quote, submitMessage]);
212
- const setActiveTrigger = useCallback((update) => {
213
- setActiveTriggerState(update);
214
- }, []);
215
- const value = useMemo(
216
- () => ({
217
- input,
218
- setInput,
219
- attachments,
220
- setAttachments,
221
- addAttachment,
222
- removeAttachment,
223
- clearAttachments,
224
- entities,
225
- setEntities,
226
- quote,
227
- setQuote,
228
- clearQuote,
229
- triggers,
230
- activeTrigger,
231
- setActiveTrigger,
232
- submit,
233
- stop: chat.stop,
234
- status: chat.status,
235
- canSubmit,
236
- canStop
237
- }),
238
- [
239
- addAttachment,
240
- attachments,
241
- activeTrigger,
242
- canStop,
243
- canSubmit,
244
- chat.status,
245
- chat.stop,
246
- clearAttachments,
247
- clearQuote,
248
- entities,
249
- input,
250
- quote,
251
- removeAttachment,
252
- setAttachments,
253
- setActiveTrigger,
254
- setEntities,
255
- setInput,
256
- setQuote,
257
- submit,
258
- triggers
259
- ]
260
- );
261
- const handleSubmit = useCallback(
262
- (event) => {
263
- onSubmit?.(event);
264
- if (event.defaultPrevented) {
265
- return;
266
- }
267
- event.preventDefault();
268
- void submit();
269
- },
270
- [onSubmit, submit]
271
- );
272
- return /* @__PURE__ */ jsx(InternalComposerProvider, { value, children: renderPrimitive(
273
- "form",
274
- {
275
- ...props,
276
- onSubmit: handleSubmit,
277
- "data-state": chat.status
278
- },
279
- ref
280
- ) });
281
- });
282
- var ComposerQuotePreview = forwardRef(
283
- function ComposerQuotePreview2({ children, ...props }, ref) {
284
- const composer = useComposer();
285
- const quote = composer.quote;
286
- if (quote === void 0) {
287
- return null;
288
- }
289
- const renderedChildren = typeof children === "function" ? children(quote) : children ?? quote.text;
290
- return renderPrimitive(
291
- "blockquote",
292
- {
293
- ...props,
294
- children: renderedChildren
295
- },
296
- ref
297
- );
298
- }
299
- );
300
- var ComposerClearQuote = forwardRef(
301
- function ComposerClearQuote2({ onClick, ...props }, ref) {
302
- const composer = useComposer();
303
- const disabled = props.disabled ?? composer.quote === void 0;
304
- const handleClick = useCallback(
305
- (event) => {
306
- onClick?.(event);
307
- if (event.defaultPrevented || disabled) {
308
- return;
309
- }
310
- composer.clearQuote();
311
- },
312
- [composer, disabled, onClick]
313
- );
314
- return renderPrimitive(
315
- "button",
316
- {
317
- ...props,
318
- children: props.children ?? "Clear quote",
319
- disabled,
320
- onClick: handleClick,
321
- type: props.type ?? "button",
322
- "data-state": disabled ? "disabled" : "enabled"
323
- },
324
- ref
325
- );
326
- }
327
- );
328
- var ComposerInput = forwardRef(function ComposerInput2({
329
- autoResize = true,
330
- disabled,
331
- maxRows: maxRowsProp,
332
- minRows: minRowsProp,
333
- onKeyDown,
334
- placeholder,
335
- style,
336
- ...props
337
- }, ref) {
338
- const composer = useComposer();
339
- const composerRef = useRef(composer);
340
- composerRef.current = composer;
341
- const editorReadyRef = useRef(false);
342
- const syncingFromEditorRef = useRef(false);
343
- const triggers = composer.triggers;
344
- const minRows = normalizeRows(minRowsProp ?? 1, 1);
345
- const maxRows = normalizeRows(maxRowsProp ?? 6, minRows);
346
- const extensions = useMemo(
347
- () => composerInputExtensions({
348
- composerRef,
349
- placeholder,
350
- triggers
351
- }),
352
- [placeholder, triggers]
353
- );
354
- const editor = useEditor(
355
- {
356
- extensions,
357
- content: plainTextToComposerContent(composer.input),
358
- editable: composer.status !== "submitted" && composer.status !== "streaming",
359
- editorProps: {
360
- attributes: {
361
- "aria-label": props["aria-label"] ?? "Message",
362
- "aria-multiline": "true",
363
- role: "textbox"
364
- },
365
- handleKeyDown: (_view, event) => submitComposerFromEditorKeyDown(event, composerRef)
366
- },
367
- onUpdate: ({ editor: updatedEditor }) => {
368
- if (!editorReadyRef.current) {
369
- return;
370
- }
371
- const snapshot = composerSnapshotFromEditor(
372
- updatedEditor,
373
- composerRef.current.entities,
374
- composerRef.current.triggers
375
- );
376
- syncingFromEditorRef.current = true;
377
- composerRef.current.setInput(snapshot.input);
378
- composerRef.current.setEntities(snapshot.entities);
379
- }
380
- },
381
- [extensions]
382
- );
383
- const ariaDisabled = props["aria-disabled"] === true || props["aria-disabled"] === "true";
384
- const composerDisabled = disabled === true || ariaDisabled || composer.status === "submitted" || composer.status === "streaming";
385
- const inputStyle = useMemo(() => {
386
- if (!autoResize) {
387
- return style;
388
- }
389
- const rowsStyle = {
390
- ["--anvia-composer-min-rows"]: minRows,
391
- ["--anvia-composer-max-rows"]: maxRows
392
- };
393
- return style === void 0 ? rowsStyle : { ...rowsStyle, ...style };
394
- }, [autoResize, maxRows, minRows, style]);
395
- const handleKeyDown = useCallback(
396
- (event) => {
397
- onKeyDown?.(event);
398
- if (event.defaultPrevented || event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) {
399
- return;
400
- }
401
- event.preventDefault();
402
- void composerRef.current.submit();
403
- },
404
- [onKeyDown]
405
- );
406
- useEffect(() => {
407
- if (editor === null) {
408
- return;
409
- }
410
- editor.setEditable(!composerDisabled, false);
411
- }, [composerDisabled, editor]);
412
- useEffect(() => {
413
- if (editor === null) {
414
- return;
415
- }
416
- editor.commands.setContent(plainTextToComposerContent(composerRef.current.input), {
417
- emitUpdate: false
418
- });
419
- editorReadyRef.current = true;
420
- return () => {
421
- editorReadyRef.current = false;
422
- };
423
- }, [editor]);
424
- useEffect(() => {
425
- if (editor === null || !editorReadyRef.current) {
426
- return;
427
- }
428
- if (syncingFromEditorRef.current) {
429
- syncingFromEditorRef.current = false;
430
- return;
431
- }
432
- const snapshot = composerSnapshotFromEditor(editor, composer.entities, composer.triggers);
433
- if (snapshot.input === composer.input) {
434
- return;
435
- }
436
- editor.commands.setContent(plainTextToComposerContent(composer.input), {
437
- emitUpdate: false
438
- });
439
- }, [composer, editor]);
440
- return renderPrimitive(
441
- "div",
442
- {
443
- ...props,
444
- children: /* @__PURE__ */ jsx(EditorContent, { editor }),
445
- "aria-disabled": composerDisabled ? true : props["aria-disabled"],
446
- "data-role": "editor",
447
- "data-state": composerDisabled ? "disabled" : "enabled",
448
- onKeyDown: handleKeyDown,
449
- style: inputStyle
450
- },
451
- ref
452
- );
453
- });
454
- var ComposerTextareaInput = forwardRef(
455
- function ComposerTextareaInput2({
456
- autoResize = true,
457
- maxRows: maxRowsProp,
458
- minRows: minRowsProp,
459
- onChange,
460
- onKeyDown,
461
- rows,
462
- ...props
463
- }, ref) {
464
- const composer = useComposer();
465
- const inputRef = useRef(null);
466
- const wasAutoResizeRef = useRef(autoResize);
467
- const composedInputRef = useMemo(() => composeRefs(inputRef, ref), [ref]);
468
- const minRows = normalizeRows(minRowsProp ?? rows ?? 1, 1);
469
- const maxRows = normalizeRows(maxRowsProp ?? 6, minRows);
470
- useEffect(() => {
471
- const wasAutoResize = wasAutoResizeRef.current;
472
- wasAutoResizeRef.current = autoResize;
473
- if (!autoResize) {
474
- if (wasAutoResize) {
475
- resetComposerInputSize(inputRef.current);
476
- }
477
- return;
478
- }
479
- resizeComposerInput(inputRef.current, { maxRows, minRows });
480
- });
481
- const handleChange = useCallback(
482
- (event) => {
483
- onChange?.(event);
484
- if (!event.defaultPrevented) {
485
- composer.setInput(event.currentTarget.value);
486
- composer.setEntities([]);
487
- if (autoResize) {
488
- resizeComposerInput(event.currentTarget, { maxRows, minRows });
489
- }
490
- }
491
- },
492
- [autoResize, composer, maxRows, minRows, onChange]
493
- );
494
- const handleKeyDown = useCallback(
495
- (event) => {
496
- onKeyDown?.(event);
497
- if (event.defaultPrevented || event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) {
498
- return;
499
- }
500
- event.preventDefault();
501
- void composer.submit();
502
- },
503
- [composer, onKeyDown]
504
- );
505
- return renderPrimitive(
506
- "textarea",
507
- {
508
- ...props,
509
- "aria-label": props["aria-label"] ?? "Message",
510
- disabled: props.disabled ?? (composer.status === "submitted" || composer.status === "streaming"),
511
- onChange: handleChange,
512
- onKeyDown: handleKeyDown,
513
- rows: autoResize ? minRows : rows,
514
- value: composer.input
515
- },
516
- composedInputRef
517
- );
518
- }
519
- );
520
- var COMPOSER_ENTITY_NODE = "composerEntity";
521
- var EMPTY_COMPOSER_TRIGGERS = [];
522
- var ComposerEntityExtension = Mention.extend({
523
- name: COMPOSER_ENTITY_NODE,
524
- addAttributes() {
525
- return {
526
- id: {
527
- default: null,
528
- parseHTML: (element) => element.getAttribute("data-id"),
529
- renderHTML: (attributes) => attributes.id === void 0 || attributes.id === null ? {} : { "data-id": String(attributes.id) }
530
- },
531
- label: {
532
- default: null,
533
- parseHTML: (element) => element.getAttribute("data-label"),
534
- renderHTML: (attributes) => attributes.label === void 0 || attributes.label === null ? {} : { "data-label": String(attributes.label) }
535
- },
536
- mentionSuggestionChar: {
537
- default: "@",
538
- parseHTML: (element) => element.getAttribute("data-mention-suggestion-char"),
539
- renderHTML: (attributes) => ({
540
- "data-mention-suggestion-char": attributes.mentionSuggestionChar
541
- })
542
- },
543
- triggerId: {
544
- default: null,
545
- parseHTML: (element) => element.getAttribute("data-trigger-id"),
546
- renderHTML: (attributes) => attributes.triggerId === void 0 || attributes.triggerId === null ? {} : { "data-trigger-id": String(attributes.triggerId) }
547
- },
548
- text: {
549
- default: null,
550
- parseHTML: (element) => element.getAttribute("data-text"),
551
- renderHTML: (attributes) => attributes.text === void 0 || attributes.text === null ? {} : { "data-text": String(attributes.text) }
552
- },
553
- data: {
554
- default: void 0,
555
- parseHTML: (element) => dataFromAttribute(element.getAttribute("data-entity-data")),
556
- renderHTML: (attributes) => {
557
- if (attributes.data === void 0) return {};
558
- if (!isComposerEntityData(attributes.data)) {
559
- throw new TypeError("Composer entity data must be a JSON value.");
560
- }
561
- return { "data-entity-data": JSON.stringify(attributes.data) };
562
- }
563
- }
564
- };
565
- }
566
- });
567
- function composerInputExtensions({
568
- composerRef,
569
- placeholder,
570
- triggers
571
- }) {
572
- return [
573
- Document,
574
- Paragraph,
575
- Text,
576
- HardBreak,
577
- Placeholder.configure(placeholder === void 0 ? {} : { placeholder }),
578
- ComposerEntityExtension.configure({
579
- HTMLAttributes: {},
580
- deleteTriggerWithBackspace: true,
581
- renderText: ({ node }) => composerEntityText(node.attrs),
582
- renderHTML: ({ node, options }) => [
583
- "span",
584
- mergeAttributes(options.HTMLAttributes, {}),
585
- composerEntityText(node.attrs)
586
- ],
587
- suggestions: triggers.map((trigger) => composerSuggestion(trigger, composerRef))
588
- })
589
- ];
590
- }
591
- function submitComposerFromEditorKeyDown(event, composerRef) {
592
- if (event.defaultPrevented || event.key !== "Enter" || event.shiftKey || event.isComposing || composerRef.current.activeTrigger !== void 0) {
593
- return false;
594
- }
595
- event.preventDefault();
596
- void composerRef.current.submit();
597
- return true;
598
- }
599
- function composerSuggestion(trigger, composerRef) {
600
- const pluginKey = new PluginKey(`anvia-composer-trigger-${trigger.id}`);
601
- const suggestion = {
602
- pluginKey,
603
- char: trigger.char,
604
- items: ({ query, signal }) => resolveTriggerItems(trigger, query, composerRef.current, signal),
605
- command: ({
606
- editor,
607
- range,
608
- props
609
- }) => {
610
- const nodeAfter = editor.state.selection.$to.nodeAfter;
611
- const overrideSpace = nodeAfter?.text?.startsWith(" ");
612
- const insertRange = {
613
- from: range.from,
614
- to: overrideSpace ? range.to + 1 : range.to
615
- };
616
- editor.chain().focus().insertContentAt(insertRange, [
617
- {
618
- type: COMPOSER_ENTITY_NODE,
619
- attrs: props
620
- },
621
- {
622
- type: "text",
623
- text: " "
624
- }
625
- ]).run();
626
- composerEditorOwnerDocument(editor)?.defaultView?.getSelection()?.collapseToEnd();
627
- composerRef.current.setActiveTrigger(void 0);
628
- },
629
- render: () => ({
630
- onStart: (props) => {
631
- updateComposerTriggerState(trigger, props, composerRef);
632
- },
633
- onUpdate: (props) => {
634
- updateComposerTriggerState(trigger, props, composerRef);
635
- },
636
- onExit: () => {
637
- composerRef.current.setActiveTrigger(
638
- (current) => current?.trigger.id === trigger.id ? void 0 : current
639
- );
640
- },
641
- onKeyDown: (props) => handleComposerTriggerKeyDown(trigger, props, composerRef)
642
- })
643
- };
644
- if (trigger.allowSpaces !== void 0) suggestion.allowSpaces = trigger.allowSpaces;
645
- if (trigger.allowedPrefixes !== void 0) {
646
- suggestion.allowedPrefixes = trigger.allowedPrefixes;
647
- }
648
- if (trigger.startOfLine !== void 0) suggestion.startOfLine = trigger.startOfLine;
649
- if (trigger.minQueryLength !== void 0) {
650
- suggestion.minQueryLength = trigger.minQueryLength;
651
- }
652
- return suggestion;
653
- }
654
- function resolveTriggerItems(trigger, query, composer, signal) {
655
- if (Array.isArray(trigger.items)) {
656
- const normalizedQuery = query.toLowerCase();
657
- return trigger.items.filter((item) => item.label.toLowerCase().includes(normalizedQuery));
658
- }
659
- return trigger.items({
660
- trigger,
661
- query,
662
- input: composer.input,
663
- entities: composer.entities,
664
- signal
665
- });
666
- }
667
- function composerEditorOwnerDocument(editor) {
668
- const element = editor.options.element;
669
- if (element === null || typeof element === "function") {
670
- return void 0;
671
- }
672
- return "mount" in element ? element.mount.ownerDocument : element.ownerDocument;
673
- }
674
- function updateComposerTriggerState(trigger, props, composerRef) {
675
- const current = composerRef.current.activeTrigger;
676
- const selectedIndex = current?.trigger.id === trigger.id ? clampIndex(current.selectedIndex, props.items.length) : 0;
677
- const rect = rectFromSuggestion(props);
678
- const state = {
679
- trigger,
680
- query: props.query,
681
- items: props.items,
682
- loading: props.loading,
683
- selectedIndex,
684
- selectItem: (item) => {
685
- if (item.disabled) {
686
- return;
687
- }
688
- props.command(triggerItemToEntityAttrs(trigger, item));
689
- },
690
- setSelectedIndex: (index) => {
691
- composerRef.current.setActiveTrigger(
692
- (active) => active?.trigger.id === trigger.id ? { ...active, selectedIndex: clampIndex(index, active.items.length) } : active
693
- );
694
- }
695
- };
696
- if (rect !== void 0) state.rect = rect;
697
- composerRef.current.setActiveTrigger(state);
698
- }
699
- function handleComposerTriggerKeyDown(trigger, { event }, composerRef) {
700
- const activeTrigger = composerRef.current.activeTrigger;
701
- if (activeTrigger?.trigger.id !== trigger.id) {
702
- return false;
703
- }
704
- if (event.key === "ArrowDown") {
705
- event.preventDefault();
706
- activeTrigger.setSelectedIndex(activeTrigger.selectedIndex + 1);
707
- return true;
708
- }
709
- if (event.key === "ArrowUp") {
710
- event.preventDefault();
711
- activeTrigger.setSelectedIndex(activeTrigger.selectedIndex - 1);
712
- return true;
713
- }
714
- if (event.key === "Enter" || event.key === "Tab") {
715
- event.preventDefault();
716
- const item = activeTrigger.items[activeTrigger.selectedIndex];
717
- if (item !== void 0) {
718
- activeTrigger.selectItem(item);
719
- }
720
- return true;
721
- }
722
- if (event.key === "Escape") {
723
- composerRef.current.setActiveTrigger(void 0);
724
- return false;
725
- }
726
- return false;
727
- }
728
- function triggerItemToEntityAttrs(trigger, item) {
729
- if (item.data !== void 0 && !isComposerEntityData(item.data)) {
730
- throw new TypeError("Composer trigger item data must be a JSON value.");
731
- }
732
- return {
733
- id: item.id,
734
- label: item.label,
735
- mentionSuggestionChar: trigger.char,
736
- triggerId: trigger.id,
737
- text: triggerItemText(trigger, item),
738
- data: item.data
739
- };
740
- }
741
- function triggerItemText(trigger, item) {
742
- return item.text ?? `${trigger.char}${item.label}`;
743
- }
744
- function rectFromSuggestion(props) {
745
- const rect = props.clientRect?.();
746
- if (rect === void 0 || rect === null) {
747
- return void 0;
748
- }
749
- return {
750
- top: rect.top,
751
- right: rect.right,
752
- bottom: rect.bottom,
753
- left: rect.left,
754
- width: rect.width,
755
- height: rect.height
756
- };
757
- }
758
- function clampIndex(index, length) {
759
- if (length <= 0) {
760
- return 0;
761
- }
762
- return (index + length) % length;
763
- }
764
- function plainTextToComposerContent(input) {
765
- const lines = input.length === 0 ? [""] : input.split(/\r?\n/);
766
- return {
767
- type: "doc",
768
- content: lines.map((line) => {
769
- const paragraph = { type: "paragraph" };
770
- if (line.length > 0) {
771
- paragraph.content = [{ type: "text", text: line }];
772
- }
773
- return paragraph;
774
- })
775
- };
776
- }
777
- function composerSnapshotFromEditor(editor, previousEntities, triggers) {
778
- return composerSnapshotFromContent(editor.getJSON(), previousEntities, triggers);
779
- }
780
- function composerSnapshotFromContent(content, previousEntities, triggers) {
781
- const entities = [];
782
- let input = "";
783
- let blockIndex = 0;
784
- const appendNode = (node) => {
785
- if (node.type === "doc") {
786
- for (const child of node.content ?? []) {
787
- appendNode(child);
788
- }
789
- return;
790
- }
791
- if (node.type === "paragraph") {
792
- if (blockIndex > 0) {
793
- input += "\n";
794
- }
795
- blockIndex += 1;
796
- for (const child of node.content ?? []) {
797
- appendNode(child);
798
- }
799
- return;
800
- }
801
- if (node.type === "text") {
802
- input += node.text ?? "";
803
- return;
804
- }
805
- if (node.type === "hardBreak") {
806
- input += "\n";
807
- return;
808
- }
809
- if (node.type === COMPOSER_ENTITY_NODE) {
810
- const attrs = node.attrs;
811
- const entity = composerEntityFromAttrs(attrs, input.length, previousEntities, triggers);
812
- input += entity.text;
813
- entities.push(entity);
814
- return;
815
- }
816
- for (const child of node.content ?? []) {
817
- appendNode(child);
818
- }
819
- };
820
- appendNode(content);
821
- return { input, entities };
822
- }
823
- function composerEntityFromAttrs(attrs, from, previousEntities, triggers) {
824
- const id = stringAttr(attrs?.id) ?? "";
825
- const trigger = stringAttr(attrs?.mentionSuggestionChar) ?? "@";
826
- const triggerId = stringAttr(attrs?.triggerId) ?? triggers.find((candidate) => candidate.char === trigger)?.id ?? trigger;
827
- const label = stringAttr(attrs?.label) ?? id;
828
- const text = composerEntityText(attrs);
829
- const previous = previousEntities.find(
830
- (entity2) => entity2.id === id && entity2.triggerId === triggerId && entity2.trigger === trigger
831
- );
832
- const data = attrs?.data === void 0 ? previous?.data : attrs.data;
833
- const entity = {
834
- id,
835
- triggerId,
836
- trigger,
837
- label,
838
- text,
839
- range: {
840
- from,
841
- to: from + text.length
842
- }
843
- };
844
- if (data !== void 0) entity.data = data;
845
- return entity;
846
- }
847
- function composerEntityText(attrs) {
848
- const text = stringAttr(attrs?.text);
849
- if (text !== void 0) {
850
- return text;
851
- }
852
- const trigger = stringAttr(attrs?.mentionSuggestionChar) ?? "@";
853
- return `${trigger}${stringAttr(attrs?.label) ?? stringAttr(attrs?.id) ?? ""}`;
854
- }
855
- function stringAttr(value) {
856
- return typeof value === "string" ? value : void 0;
857
- }
858
- function dataFromAttribute(value) {
859
- if (value === null) {
860
- return void 0;
861
- }
862
- try {
863
- const parsed = JSON.parse(value);
864
- return isComposerEntityData(parsed) ? parsed : void 0;
865
- } catch {
866
- return void 0;
867
- }
868
- }
869
- function resizeComposerInput(input, { maxRows, minRows }) {
870
- if (input === null) {
871
- return;
872
- }
873
- const style = getComputedStyle(input);
874
- const lineHeight = lineHeightFromStyle(style);
875
- const paddingHeight = pixelValue(style.paddingTop) + pixelValue(style.paddingBottom);
876
- const borderHeight = pixelValue(style.borderTopWidth) + pixelValue(style.borderBottomWidth);
877
- const minContentHeight = lineHeight * minRows;
878
- const maxContentHeight = Math.max(minContentHeight, lineHeight * maxRows);
879
- input.style.height = "auto";
880
- const scrollContentHeight = Math.max(input.scrollHeight - paddingHeight, 0);
881
- const contentHeight = clamp(scrollContentHeight, minContentHeight, maxContentHeight);
882
- const nextHeight = style.boxSizing === "border-box" ? contentHeight + paddingHeight + borderHeight : contentHeight;
883
- input.style.height = `${Math.ceil(nextHeight)}px`;
884
- input.style.overflowY = scrollContentHeight > maxContentHeight ? "auto" : "hidden";
885
- }
886
- function resetComposerInputSize(input) {
887
- if (input === null) {
888
- return;
889
- }
890
- input.style.height = "";
891
- input.style.overflowY = "";
892
- }
893
- function normalizeRows(value, min) {
894
- if (!Number.isFinite(value)) {
895
- return min;
896
- }
897
- return Math.max(min, Math.floor(value));
898
- }
899
- function lineHeightFromStyle(style) {
900
- return pixelValue(style.lineHeight) || (pixelValue(style.fontSize) || 16) * 1.2;
901
- }
902
- function pixelValue(value) {
903
- const parsed = Number.parseFloat(value);
904
- return Number.isFinite(parsed) ? parsed : 0;
905
- }
906
- function clamp(value, min, max) {
907
- return Math.min(Math.max(value, min), max);
908
- }
909
- function promptWithQuote(prompt, quote) {
910
- const quotedText = quote.text.split(/\r?\n/).map((line) => `> ${line}`).join("\n");
911
- if (prompt.trim().length === 0) {
912
- return { text: quotedText, prefixLength: 0 };
913
- }
914
- const prefix = `${quotedText}
915
-
916
- `;
917
- return { text: `${prefix}${prompt}`, prefixLength: prefix.length };
918
- }
919
- function normalizeQuote(quote) {
920
- if (quote === void 0) {
921
- return void 0;
922
- }
923
- return {
924
- text: quote.text,
925
- messageId: quote.messageId
926
- };
927
- }
928
- function composerSubmitMetadata(quote, entities) {
929
- if (quote === void 0 && entities.length === 0) {
930
- return void 0;
931
- }
932
- const metadata = {};
933
- if (quote !== void 0) metadata.quote = quote;
934
- if (entities.length > 0) {
935
- metadata.composer = { entities: entities.map(composerEntityMetadata) };
936
- }
937
- return metadata;
938
- }
939
- function assertComposerEntitiesData(entities) {
940
- for (const entity of entities) {
941
- if (entity.data !== void 0 && !isComposerEntityData(entity.data)) {
942
- throw new TypeError("Composer entity data must be a JSON value.");
943
- }
944
- }
945
- }
946
- function composerEntityMetadata(entity) {
947
- const metadata = {
948
- id: entity.id,
949
- triggerId: entity.triggerId,
950
- trigger: entity.trigger,
951
- label: entity.label,
952
- text: entity.text,
953
- range: { from: entity.range.from, to: entity.range.to }
954
- };
955
- if (entity.data !== void 0) {
956
- metadata.data = entity.data;
957
- }
958
- return metadata;
959
- }
960
- var ComposerSubmit = forwardRef(
961
- function ComposerSubmit2(props, ref) {
962
- const composer = useComposer();
963
- const disabled = props.disabled ?? !composer.canSubmit;
964
- return renderPrimitive(
965
- "button",
966
- {
967
- ...props,
968
- children: props.children ?? "Send",
969
- disabled,
970
- type: props.type ?? "submit",
971
- "data-state": disabled ? "disabled" : "enabled"
972
- },
973
- ref
974
- );
975
- }
976
- );
977
- var ComposerStop = forwardRef(function ComposerStop2({ onClick, ...props }, ref) {
978
- const composer = useComposer();
979
- const disabled = props.disabled ?? !composer.canStop;
980
- const handleClick = useCallback(
981
- (event) => {
982
- onClick?.(event);
983
- if (event.defaultPrevented || disabled) {
984
- return;
985
- }
986
- composer.stop();
987
- },
988
- [composer, disabled, onClick]
989
- );
990
- return renderPrimitive(
991
- "button",
992
- {
993
- ...props,
994
- children: props.children ?? "Stop",
995
- disabled,
996
- onClick: handleClick,
997
- type: props.type ?? "button",
998
- "data-state": disabled ? "disabled" : "enabled"
999
- },
1000
- ref
1001
- );
1002
- });
1003
- var ComposerTriggerMenu = forwardRef(
1004
- function ComposerTriggerMenu2({ children, keepMounted = false, style, ...props }, ref) {
1005
- const composer = useComposer();
1006
- const activeTrigger = composer.activeTrigger;
1007
- const empty = activeTrigger === void 0;
1008
- if (empty && !keepMounted) {
1009
- return null;
1010
- }
1011
- const menuStyle = activeTrigger?.rect === void 0 ? style : {
1012
- position: "fixed",
1013
- top: activeTrigger.rect.bottom,
1014
- left: activeTrigger.rect.left,
1015
- ...style
1016
- };
1017
- const renderedChildren = activeTrigger === void 0 ? typeof children === "function" ? null : children : typeof children === "function" ? children(activeTrigger) : children ?? activeTrigger.items.map((item, index) => /* @__PURE__ */ jsx(ComposerTriggerItem, { index }, `${item.id}:${index.toString()}`));
1018
- return renderPrimitive(
1019
- "div",
1020
- {
1021
- ...props,
1022
- children: renderedChildren,
1023
- role: props.role ?? "listbox",
1024
- style: menuStyle,
1025
- "data-state": activeTrigger === void 0 ? "closed" : activeTrigger.loading ? "loading" : empty ? "empty" : "open"
1026
- },
1027
- ref
1028
- );
1029
- }
1030
- );
1031
- var ComposerTriggerItem = forwardRef(
1032
- function ComposerTriggerItem2({ children, index, item: itemProp, onClick, onMouseEnter, ...props }, ref) {
1033
- const composer = useComposer();
1034
- const activeTrigger = composer.activeTrigger;
1035
- const itemIndex = index ?? 0;
1036
- const item = itemProp ?? activeTrigger?.items[itemIndex];
1037
- if (activeTrigger === void 0 || item === void 0) {
1038
- return null;
1039
- }
1040
- const selected = activeTrigger.selectedIndex === itemIndex;
1041
- const disabled = props.disabled ?? item.disabled ?? false;
1042
- const renderedChildren = typeof children === "function" ? children(item, activeTrigger) : children ?? item.label;
1043
- const handleMouseEnter = (event) => {
1044
- onMouseEnter?.(event);
1045
- if (!event.defaultPrevented && !disabled) {
1046
- activeTrigger.setSelectedIndex(itemIndex);
1047
- }
1048
- };
1049
- const handleClick = (event) => {
1050
- onClick?.(event);
1051
- if (!event.defaultPrevented && !disabled) {
1052
- activeTrigger.selectItem(item);
1053
- }
1054
- };
1055
- return renderPrimitive(
1056
- "button",
1057
- {
1058
- ...props,
1059
- children: renderedChildren,
1060
- disabled,
1061
- onClick: handleClick,
1062
- onMouseEnter: handleMouseEnter,
1063
- role: props.role ?? "option",
1064
- type: props.type ?? "button",
1065
- "aria-selected": selected,
1066
- "data-state": disabled ? "disabled" : selected ? "selected" : "idle"
1067
- },
1068
- ref
1069
- );
1070
- }
1071
- );
1072
- var ComposerAttachments = forwardRef(
1073
- function ComposerAttachments2({ children, keepMounted = false, ...props }, ref) {
1074
- const composer = useComposer();
1075
- const empty = composer.attachments.length === 0;
1076
- if (empty && !keepMounted) {
1077
- return null;
1078
- }
1079
- return renderPrimitive(
1080
- "div",
1081
- {
1082
- ...props,
1083
- children: composer.attachments.map((attachment) => /* @__PURE__ */ jsx(
1084
- InternalAttachmentProvider,
1085
- {
1086
- value: {
1087
- attachment,
1088
- remove: () => {
1089
- composer.removeAttachment(attachment.id);
1090
- }
1091
- },
1092
- children: typeof children === "function" ? children(attachment) : children ?? /* @__PURE__ */ jsx(AttachmentPrimitive.Root, {})
1093
- },
1094
- attachment.id
1095
- )),
1096
- "data-role": "attachments",
1097
- "data-state": empty ? "empty" : "populated"
1098
- },
1099
- ref
1100
- );
1101
- }
1102
- );
1103
- var ComposerAttachmentInput = forwardRef(
1104
- function ComposerAttachmentInput2({ onChange, ...props }, ref) {
1105
- const composer = useComposer();
1106
- const disabled = props.disabled ?? (composer.status === "submitted" || composer.status === "streaming");
1107
- const handleChange = useCallback(
1108
- async (event) => {
1109
- onChange?.(event);
1110
- if (event.defaultPrevented) {
1111
- return;
1112
- }
1113
- const files = Array.from(event.currentTarget.files ?? []);
1114
- event.currentTarget.value = "";
1115
- for (const file of files) {
1116
- await composer.addAttachment(file);
1117
- }
1118
- },
1119
- [composer, onChange]
1120
- );
1121
- return renderPrimitive(
1122
- "input",
1123
- {
1124
- ...props,
1125
- disabled,
1126
- onChange: (event) => {
1127
- void handleChange(event);
1128
- },
1129
- type: "file",
1130
- "data-state": disabled ? "disabled" : "enabled"
1131
- },
1132
- ref
1133
- );
1134
- }
1135
- );
1136
- var ComposerAddAttachment = forwardRef(
1137
- function ComposerAddAttachment2({ accept, multiple = false, onClick, ...props }, ref) {
1138
- const composer = useComposer();
1139
- const inputRef = useRef(null);
1140
- const disabled = props.disabled ?? (composer.status === "submitted" || composer.status === "streaming");
1141
- const handleClick = useCallback(
1142
- (event) => {
1143
- onClick?.(event);
1144
- if (event.defaultPrevented || disabled) {
1145
- return;
1146
- }
1147
- inputRef.current?.click();
1148
- },
1149
- [disabled, onClick]
1150
- );
1151
- return /* @__PURE__ */ jsxs(Fragment, { children: [
1152
- renderPrimitive(
1153
- "button",
1154
- {
1155
- ...props,
1156
- children: props.children ?? "Attach",
1157
- disabled,
1158
- onClick: handleClick,
1159
- type: props.type ?? "button",
1160
- "data-state": disabled ? "disabled" : "enabled"
1161
- },
1162
- ref
1163
- ),
1164
- /* @__PURE__ */ jsx(
1165
- ComposerAttachmentInput,
1166
- {
1167
- accept,
1168
- "aria-hidden": "true",
1169
- hidden: true,
1170
- multiple,
1171
- ref: inputRef,
1172
- tabIndex: -1
1173
- }
1174
- )
1175
- ] });
1176
- }
1177
- );
1178
- var ComposerAttachmentDropzone = forwardRef(
1179
- function ComposerAttachmentDropzone2({ disabled: disabledProp = false, onDragLeave, onDragOver, onDrop, ...props }, ref) {
1180
- const composer = useComposer();
1181
- const [dragging, setDragging] = useState(false);
1182
- const disabled = disabledProp || composer.status === "submitted" || composer.status === "streaming";
1183
- const handleDragOver = useCallback(
1184
- (event) => {
1185
- onDragOver?.(event);
1186
- if (event.defaultPrevented || disabled) {
1187
- return;
1188
- }
1189
- event.preventDefault();
1190
- setDragging(true);
1191
- },
1192
- [disabled, onDragOver]
1193
- );
1194
- const handleDragLeave = useCallback(
1195
- (event) => {
1196
- onDragLeave?.(event);
1197
- if (!event.defaultPrevented) {
1198
- setDragging(false);
1199
- }
1200
- },
1201
- [onDragLeave]
1202
- );
1203
- const handleDrop = useCallback(
1204
- (event) => {
1205
- onDrop?.(event);
1206
- if (event.defaultPrevented || disabled) {
1207
- return;
1208
- }
1209
- event.preventDefault();
1210
- setDragging(false);
1211
- const files = Array.from(event.dataTransfer.files);
1212
- void Promise.all(files.map((file) => composer.addAttachment(file)));
1213
- },
1214
- [composer, disabled, onDrop]
1215
- );
1216
- return renderPrimitive(
1217
- "div",
1218
- {
1219
- ...props,
1220
- onDragLeave: handleDragLeave,
1221
- onDragOver: handleDragOver,
1222
- onDrop: handleDrop,
1223
- "data-state": disabled ? "disabled" : dragging ? "dragging" : "enabled"
1224
- },
1225
- ref
1226
- );
1227
- }
1228
- );
1229
- function createAttachment(attachment) {
1230
- return {
1231
- ...attachment,
1232
- id: attachment.id ?? createAttachmentId()
1233
- };
1234
- }
1235
- function isFileAttachmentInput(attachment) {
1236
- return typeof File !== "undefined" && attachment instanceof File;
1237
- }
1238
- async function attachmentFromFile(file) {
1239
- return {
1240
- id: createAttachmentId(),
1241
- type: file.type.startsWith("image/") ? "image" : "document",
1242
- name: file.name,
1243
- mediaType: file.type.length > 0 ? file.type : "application/octet-stream",
1244
- data: await readFileData(file)
1245
- };
1246
- }
1247
- async function readFileData(file) {
1248
- const dataUrl = await new Promise((resolve, reject) => {
1249
- const reader = new FileReader();
1250
- reader.addEventListener("load", () => {
1251
- resolve(String(reader.result ?? ""));
1252
- });
1253
- reader.addEventListener("error", () => {
1254
- reject(reader.error ?? new Error("Failed to read attachment."));
1255
- });
1256
- reader.readAsDataURL(file);
1257
- });
1258
- return dataUrl.includes(",") ? dataUrl.slice(dataUrl.indexOf(",") + 1) : dataUrl;
1259
- }
1260
- var nextAttachmentId = 0;
1261
- function createAttachmentId() {
1262
- const random = globalThis.crypto?.randomUUID?.();
1263
- if (random !== void 0) {
1264
- return `attachment_${random}`;
1265
- }
1266
- nextAttachmentId += 1;
1267
- return `attachment_${nextAttachmentId.toString(36)}`;
1268
- }
1269
- var ComposerPrimitive = {
1270
- Root: ComposerRoot,
1271
- Quote: ComposerQuotePreview,
1272
- ClearQuote: ComposerClearQuote,
1273
- Input: ComposerInput,
1274
- TextareaInput: ComposerTextareaInput,
1275
- TriggerMenu: ComposerTriggerMenu,
1276
- TriggerItem: ComposerTriggerItem,
1277
- Attachments: ComposerAttachments,
1278
- AddAttachment: ComposerAddAttachment,
1279
- AttachmentInput: ComposerAttachmentInput,
1280
- AttachmentDropzone: ComposerAttachmentDropzone,
1281
- Submit: ComposerSubmit,
1282
- Stop: ComposerStop
1283
- };
1284
-
1285
- // src/chat/thread.tsx
1286
- import {
1287
- Fragment as Fragment2,
1288
- forwardRef as forwardRef2,
1289
- useCallback as useCallback2,
1290
- useEffect as useEffect2,
1291
- useMemo as useMemo2,
1292
- useRef as useRef2,
1293
- useState as useState2
1294
- } from "react";
1295
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
1296
- var ThreadRoot = forwardRef2(
1297
- function ThreadRoot2(props, ref) {
1298
- const chat = useChatContext();
1299
- const viewportRef = useRef2(null);
1300
- const messagesRef = useRef2(null);
1301
- const [atBottom, setAtBottom] = useState2(true);
1302
- const scrollToBottom = useCallback2((behavior = "smooth") => {
1303
- const viewport = viewportRef.current;
1304
- if (viewport === null) {
1305
- return;
1306
- }
1307
- viewport.scrollTo({ top: viewport.scrollHeight, behavior });
1308
- }, []);
1309
- const thread = useMemo2(
1310
- () => ({ viewportRef, messagesRef, atBottom, setAtBottom, scrollToBottom }),
1311
- [atBottom, scrollToBottom]
1312
- );
1313
- return /* @__PURE__ */ jsx2(InternalThreadProvider, { value: thread, children: renderPrimitive(
1314
- "div",
1315
- {
1316
- ...props,
1317
- "data-state": chat.status
1318
- },
1319
- ref
1320
- ) });
1321
- }
1322
- );
1323
- var ThreadViewport = forwardRef2(function ThreadViewport2({ autoScroll = true, onScroll, ...props }, ref) {
1324
- const chat = useChatContext();
1325
- const thread = useThread();
1326
- const messages = chat.messages;
1327
- const composedRef = useMemo2(
1328
- () => composeRefs(ref, (node) => {
1329
- thread.viewportRef.current = node;
1330
- }),
1331
- [ref, thread.viewportRef]
1332
- );
1333
- useEffect2(() => {
1334
- const hasMessages = messages.length > 0;
1335
- if (autoScroll && (thread.atBottom || !hasMessages)) {
1336
- thread.scrollToBottom("auto");
1337
- }
1338
- }, [autoScroll, messages, thread]);
1339
- useEffect2(() => {
1340
- const viewport = thread.viewportRef.current;
1341
- if (viewport === null || !autoScroll || typeof ResizeObserver !== "function") {
1342
- return;
1343
- }
1344
- const content = thread.messagesRef.current;
1345
- if (content === null) {
1346
- return;
1347
- }
1348
- const observer = new ResizeObserver(() => {
1349
- if (thread.atBottom) {
1350
- thread.scrollToBottom("auto");
1351
- }
1352
- });
1353
- observer.observe(viewport);
1354
- observer.observe(content);
1355
- return () => observer.disconnect();
1356
- }, [autoScroll, thread]);
1357
- const handleScroll = useCallback2(
1358
- (event) => {
1359
- onScroll?.(event);
1360
- const node = event.currentTarget;
1361
- const distanceFromBottom = node.scrollHeight - node.scrollTop - node.clientHeight;
1362
- thread.setAtBottom(distanceFromBottom < 80);
1363
- },
1364
- [onScroll, thread]
1365
- );
1366
- return renderPrimitive(
1367
- "div",
1368
- {
1369
- ...props,
1370
- onScroll: handleScroll,
1371
- "data-state": thread.atBottom ? "bottom" : "away"
1372
- },
1373
- composedRef
1374
- );
1375
- });
1376
- var ThreadViewportFooter = forwardRef2(
1377
- function ThreadViewportFooter2(props, ref) {
1378
- return renderPrimitive(
1379
- "div",
1380
- {
1381
- ...props
1382
- },
1383
- ref
1384
- );
1385
- }
1386
- );
1387
- var ThreadEmpty = forwardRef2(
1388
- function ThreadEmpty2(props, ref) {
1389
- const chat = useChatContext();
1390
- if (chat.messages.length > 0) {
1391
- return null;
1392
- }
1393
- return renderPrimitive(
1394
- "div",
1395
- {
1396
- ...props
1397
- },
1398
- ref
1399
- );
1400
- }
1401
- );
1402
- var ThreadStatus = forwardRef2(function ThreadStatus2({ children, ...props }, ref) {
1403
- const chat = useChatContext();
1404
- const renderedChildren = typeof children === "function" ? children(chat.status) : children;
1405
- return renderPrimitive(
1406
- "div",
1407
- {
1408
- ...props,
1409
- children: renderedChildren ?? chat.status,
1410
- "data-state": chat.status
1411
- },
1412
- ref
1413
- );
1414
- });
1415
- var ThreadLoading = forwardRef2(
1416
- function ThreadLoading2(props, ref) {
1417
- const chat = useChatContext();
1418
- if (chat.status !== "submitted" && chat.status !== "streaming") {
1419
- return null;
1420
- }
1421
- return renderPrimitive(
1422
- "div",
1423
- {
1424
- ...props,
1425
- children: props.children ?? "Loading"
1426
- },
1427
- ref
1428
- );
1429
- }
1430
- );
1431
- var ThreadError = forwardRef2(function ThreadError2({ children, ...props }, ref) {
1432
- const chat = useChatContext();
1433
- if (chat.status !== "error" && chat.error === void 0) {
1434
- return null;
1435
- }
1436
- const renderedChildren = typeof children === "function" ? children(chat.error) : children;
1437
- return renderPrimitive(
1438
- "div",
1439
- {
1440
- ...props,
1441
- children: renderedChildren ?? errorMessage(chat.error),
1442
- role: props.role ?? "alert"
1443
- },
1444
- ref
1445
- );
1446
- });
1447
- var ThreadMessages = forwardRef2(function ThreadMessages2({ children, keepMounted = true, ...props }, ref) {
1448
- const chat = useChatContext();
1449
- const thread = useThread();
1450
- const composedRef = useMemo2(
1451
- () => composeRefs(ref, (node) => {
1452
- thread.messagesRef.current = node;
1453
- }),
1454
- [ref, thread.messagesRef]
1455
- );
1456
- const empty = chat.messages.length === 0;
1457
- if (empty && !keepMounted) {
1458
- return null;
1459
- }
1460
- return renderPrimitive(
1461
- "div",
1462
- {
1463
- ...props,
1464
- children: chat.messages.map((message) => /* @__PURE__ */ jsx2(InternalMessageProvider, { message, children: typeof children === "function" ? children(message) : children ?? defaultMessage() }, message.id)),
1465
- "data-state": empty ? "empty" : "populated"
1466
- },
1467
- composedRef
1468
- );
1469
- });
1470
- var ThreadSuggestions = forwardRef2(
1471
- function ThreadSuggestions2({ children, keepMounted = false, ...props }, ref) {
1472
- const chat = useChatContext();
1473
- const suggestions = chat.suggestions ?? [];
1474
- const empty = suggestions.length === 0;
1475
- if (empty && !keepMounted) {
1476
- return null;
1477
- }
1478
- return renderPrimitive(
1479
- "div",
1480
- {
1481
- ...props,
1482
- children: suggestions.map(
1483
- (suggestion) => typeof children === "function" ? /* @__PURE__ */ jsx2(Fragment2, { children: children(suggestion) }, suggestion.id) : /* @__PURE__ */ jsx2(ThreadSuggestion, { suggestion, children }, suggestion.id)
1484
- ),
1485
- "data-role": "suggestions",
1486
- "data-state": empty ? "empty" : "populated"
1487
- },
1488
- ref
1489
- );
1490
- }
1491
- );
1492
- var ThreadSuggestion = forwardRef2(
1493
- function ThreadSuggestion2({ onClick, prompt, suggestion, ...props }, ref) {
1494
- const chat = useChatContext();
1495
- const suggestionPrompt = prompt ?? suggestion?.prompt ?? "";
1496
- const disabled = props.disabled ?? (suggestionPrompt.length === 0 || chat.status === "submitted" || chat.status === "streaming");
1497
- const handleClick = useCallback2(
1498
- (event) => {
1499
- onClick?.(event);
1500
- if (event.defaultPrevented || disabled) {
1501
- return;
1502
- }
1503
- void chat.sendMessage({ text: suggestionPrompt });
1504
- },
1505
- [chat, disabled, onClick, suggestionPrompt]
1506
- );
1507
- return renderPrimitive(
1508
- "button",
1509
- {
1510
- ...props,
1511
- children: props.children ?? suggestion?.label ?? suggestionPrompt,
1512
- disabled,
1513
- onClick: handleClick,
1514
- type: props.type ?? "button",
1515
- "data-state": disabled ? "disabled" : "enabled"
1516
- },
1517
- ref
1518
- );
1519
- }
1520
- );
1521
- var ThreadScrollToBottom = forwardRef2(
1522
- function ThreadScrollToBottom2({ onClick, ...props }, ref) {
1523
- const thread = useThread();
1524
- const disabled = props.disabled ?? thread.atBottom;
1525
- const handleClick = useCallback2(
1526
- (event) => {
1527
- onClick?.(event);
1528
- if (event.defaultPrevented || disabled) {
1529
- return;
1530
- }
1531
- thread.scrollToBottom();
1532
- },
1533
- [disabled, onClick, thread]
1534
- );
1535
- return renderPrimitive(
1536
- "button",
1537
- {
1538
- ...props,
1539
- children: props.children ?? "Scroll to bottom",
1540
- disabled,
1541
- onClick: handleClick,
1542
- type: props.type ?? "button",
1543
- "data-state": thread.atBottom ? "bottom" : "away"
1544
- },
1545
- ref
1546
- );
1547
- }
1548
- );
1549
- function defaultMessage() {
1550
- return /* @__PURE__ */ jsxs2(MessagePrimitive.Root, { children: [
1551
- /* @__PURE__ */ jsx2(MessagePrimitive.Content, { children: /* @__PURE__ */ jsx2(MessagePrimitive.Parts, {}) }),
1552
- /* @__PURE__ */ jsx2(MessagePrimitive.Actions, {})
1553
- ] });
1554
- }
1555
- function errorMessage(error) {
1556
- if (error instanceof Error) {
1557
- return error.message;
1558
- }
1559
- if (typeof error === "string") {
1560
- return error;
1561
- }
1562
- return "Something went wrong.";
1563
- }
1564
- var ThreadPrimitive = {
1565
- Root: ThreadRoot,
1566
- Viewport: ThreadViewport,
1567
- ViewportFooter: ThreadViewportFooter,
1568
- Messages: ThreadMessages,
1569
- Empty: ThreadEmpty,
1570
- Status: ThreadStatus,
1571
- Loading: ThreadLoading,
1572
- Error: ThreadError,
1573
- Suggestions: ThreadSuggestions,
1574
- Suggestion: ThreadSuggestion,
1575
- ScrollToBottom: ThreadScrollToBottom
1576
- };
1577
-
1578
- export {
1579
- ComposerPrimitive,
1580
- ThreadPrimitive
1581
- };
1582
- //# sourceMappingURL=chunk-Y2KAMPVJ.js.map