@plaisolutions/react 0.1.0 → 0.2.0

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.
package/dist/index.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { PlaiChat } from "@plaisolutions/client";
2
- import { useEffect, useMemo, useRef, useState } from "react";
2
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
3
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
4
 
4
5
  //#region src/use-chat.ts
5
6
  function useChat(options) {
@@ -40,5 +41,896 @@ function useChat(options) {
40
41
  }
41
42
 
42
43
  //#endregion
43
- export { useChat };
44
+ //#region src/components/internal/join-classes.ts
45
+ function joinClasses(...classes) {
46
+ return classes.filter(Boolean).join(" ");
47
+ }
48
+
49
+ //#endregion
50
+ //#region src/components/tool-result-email-send-card.tsx
51
+ function formatStatus(status) {
52
+ if (status === "pending") return "pending";
53
+ if (status === "error") return "error";
54
+ return "completed";
55
+ }
56
+ function asObject(value) {
57
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
58
+ return value;
59
+ }
60
+ function toStringOrNull(value) {
61
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
62
+ }
63
+ function toNumberOrNull(value) {
64
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
65
+ }
66
+ function parseEmailSendInput(part) {
67
+ const input = asObject(part.input);
68
+ if (!input) return {
69
+ to: [],
70
+ subject: null,
71
+ text: null
72
+ };
73
+ return {
74
+ to: Array.isArray(input.to) ? input.to.filter((item) => typeof item === "string") : [],
75
+ subject: toStringOrNull(input.subject),
76
+ text: toStringOrNull(input.text)
77
+ };
78
+ }
79
+ function parseEmailSendResult(part) {
80
+ const initial = {
81
+ status: null,
82
+ recipientsCount: null,
83
+ subject: null,
84
+ receiptProvider: null,
85
+ receiptMessageId: null,
86
+ receiptRawStatus: null,
87
+ raw: null
88
+ };
89
+ if (part.result === void 0 || part.result === null) return initial;
90
+ let resultObject = asObject(part.result);
91
+ let raw = null;
92
+ if (!resultObject && typeof part.result === "string") try {
93
+ resultObject = asObject(JSON.parse(part.result));
94
+ } catch {
95
+ raw = part.result;
96
+ }
97
+ if (!resultObject) return {
98
+ ...initial,
99
+ raw
100
+ };
101
+ const receipt = asObject(resultObject.receipt);
102
+ return {
103
+ status: toStringOrNull(resultObject.status),
104
+ recipientsCount: toNumberOrNull(resultObject.recipients_count),
105
+ subject: toStringOrNull(resultObject.subject),
106
+ receiptProvider: receipt ? toStringOrNull(receipt.provider) : null,
107
+ receiptMessageId: receipt ? toStringOrNull(receipt.message_id) : null,
108
+ receiptRawStatus: receipt ? toStringOrNull(receipt.raw_status) : null,
109
+ raw
110
+ };
111
+ }
112
+ function ToolResultEmailSendCard({ part, className }) {
113
+ const [isExpanded, setIsExpanded] = useState(false);
114
+ const emailInput = parseEmailSendInput(part);
115
+ const emailResult = parseEmailSendResult(part);
116
+ const statusClass = part.state === "error" ? "border-rose-200 bg-rose-50 text-rose-800" : part.state === "pending" ? "border-amber-200 bg-amber-50 text-amber-800" : "border-emerald-200 bg-emerald-50 text-emerald-800";
117
+ return /* @__PURE__ */ jsxs("section", {
118
+ className: joinClasses("space-y-4 rounded-lg border border-slate-200 bg-slate-50 p-3", className),
119
+ "data-tool-call-id": part.id,
120
+ "data-tool-call-state": part.state,
121
+ children: [
122
+ /* @__PURE__ */ jsxs("header", {
123
+ className: "flex items-center justify-between gap-2",
124
+ children: [/* @__PURE__ */ jsx("h4", {
125
+ className: "text-sm font-semibold text-slate-900",
126
+ children: "Email"
127
+ }), /* @__PURE__ */ jsxs("div", {
128
+ className: "flex items-center gap-2",
129
+ children: [/* @__PURE__ */ jsx("span", {
130
+ className: joinClasses("rounded-full border px-2 py-0.5 text-xs font-medium", statusClass),
131
+ children: formatStatus(part.state)
132
+ }), /* @__PURE__ */ jsx("button", {
133
+ type: "button",
134
+ "aria-expanded": isExpanded,
135
+ "aria-controls": `tool-email-details-${part.id}`,
136
+ className: "inline-flex h-6 w-6 items-center justify-center rounded border border-slate-300 bg-white text-xs text-slate-700 hover:bg-slate-100",
137
+ onClick: () => setIsExpanded((previous) => !previous),
138
+ children: /* @__PURE__ */ jsx("span", {
139
+ className: "inline-block",
140
+ children: isExpanded ? "^" : "v"
141
+ })
142
+ })]
143
+ })]
144
+ }),
145
+ emailInput.subject ? /* @__PURE__ */ jsxs("div", {
146
+ className: "space-y-1",
147
+ children: [/* @__PURE__ */ jsx("p", {
148
+ className: "text-xs font-semibold text-slate-600",
149
+ children: "Subject"
150
+ }), /* @__PURE__ */ jsx("p", {
151
+ className: "text-sm text-slate-900",
152
+ children: emailInput.subject
153
+ })]
154
+ }) : null,
155
+ /* @__PURE__ */ jsxs("div", {
156
+ className: "space-y-1",
157
+ children: [/* @__PURE__ */ jsx("p", {
158
+ className: "text-xs font-semibold text-slate-600",
159
+ children: "To"
160
+ }), emailInput.to.length > 0 ? /* @__PURE__ */ jsx("div", {
161
+ className: "flex flex-wrap gap-2",
162
+ children: emailInput.to.map((recipient) => /* @__PURE__ */ jsx("span", {
163
+ className: "rounded-full border border-slate-300 bg-slate-100 px-2 py-0.5 text-xs text-slate-700",
164
+ children: recipient
165
+ }, recipient))
166
+ }) : /* @__PURE__ */ jsx("p", {
167
+ className: "text-sm text-slate-500",
168
+ children: "No recipients provided."
169
+ })]
170
+ }),
171
+ /* @__PURE__ */ jsxs("div", {
172
+ id: `tool-email-details-${part.id}`,
173
+ "data-testid": "email-send-details",
174
+ className: joinClasses(isExpanded ? "block space-y-4" : "hidden"),
175
+ children: [emailInput.text ? /* @__PURE__ */ jsxs("div", {
176
+ className: "space-y-1",
177
+ children: [/* @__PURE__ */ jsx("p", {
178
+ className: "text-xs font-semibold text-slate-600",
179
+ children: "Body"
180
+ }), /* @__PURE__ */ jsx("p", {
181
+ className: "whitespace-pre-wrap rounded border border-slate-200 bg-slate-50 p-2 text-sm text-slate-700",
182
+ children: emailInput.text
183
+ })]
184
+ }) : null, part.result !== void 0 ? /* @__PURE__ */ jsxs("div", {
185
+ className: "space-y-2 rounded border border-slate-200 bg-white p-3",
186
+ children: [
187
+ /* @__PURE__ */ jsx("p", {
188
+ className: "text-xs font-semibold uppercase tracking-wide text-slate-500",
189
+ children: "Delivery"
190
+ }),
191
+ emailResult.status ? /* @__PURE__ */ jsxs("p", {
192
+ className: "text-sm text-slate-700",
193
+ children: [
194
+ /* @__PURE__ */ jsx("span", {
195
+ className: "font-semibold text-slate-900",
196
+ children: "Status:"
197
+ }),
198
+ " ",
199
+ emailResult.status
200
+ ]
201
+ }) : null,
202
+ emailResult.recipientsCount !== null ? /* @__PURE__ */ jsxs("p", {
203
+ className: "text-sm text-slate-700",
204
+ children: [
205
+ /* @__PURE__ */ jsx("span", {
206
+ className: "font-semibold text-slate-900",
207
+ children: "Recipients:"
208
+ }),
209
+ " ",
210
+ emailResult.recipientsCount
211
+ ]
212
+ }) : null,
213
+ emailResult.receiptProvider ? /* @__PURE__ */ jsxs("p", {
214
+ className: "text-sm text-slate-700",
215
+ children: [
216
+ /* @__PURE__ */ jsx("span", {
217
+ className: "font-semibold text-slate-900",
218
+ children: "Provider:"
219
+ }),
220
+ " ",
221
+ emailResult.receiptProvider
222
+ ]
223
+ }) : null,
224
+ emailResult.receiptMessageId ? /* @__PURE__ */ jsxs("p", {
225
+ className: "break-all text-sm text-slate-700",
226
+ children: [
227
+ /* @__PURE__ */ jsx("span", {
228
+ className: "font-semibold text-slate-900",
229
+ children: "Message ID:"
230
+ }),
231
+ " ",
232
+ emailResult.receiptMessageId
233
+ ]
234
+ }) : null,
235
+ emailResult.receiptRawStatus ? /* @__PURE__ */ jsxs("p", {
236
+ className: "text-sm text-slate-700",
237
+ children: [
238
+ /* @__PURE__ */ jsx("span", {
239
+ className: "font-semibold text-slate-900",
240
+ children: "Raw status:"
241
+ }),
242
+ " ",
243
+ emailResult.receiptRawStatus
244
+ ]
245
+ }) : null,
246
+ emailResult.raw ? /* @__PURE__ */ jsx("p", {
247
+ className: "whitespace-pre-wrap text-sm text-slate-700",
248
+ children: emailResult.raw
249
+ }) : null
250
+ ]
251
+ }) : null]
252
+ }),
253
+ part.errorDetails ? /* @__PURE__ */ jsxs("p", {
254
+ className: "rounded border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-700",
255
+ children: [
256
+ /* @__PURE__ */ jsx("span", {
257
+ className: "font-semibold",
258
+ children: "Error details:"
259
+ }),
260
+ " ",
261
+ part.errorDetails
262
+ ]
263
+ }) : null
264
+ ]
265
+ });
266
+ }
267
+
268
+ //#endregion
269
+ //#region src/components/tool-result-card.tsx
270
+ function formatJson(value) {
271
+ return JSON.stringify(value, null, 2);
272
+ }
273
+ function getOfficeDocumentMediaFiles(part) {
274
+ if (part.toolType !== "office_documents") return [];
275
+ if (!part.metadata || typeof part.metadata !== "object") return [];
276
+ const metadata = part.metadata;
277
+ if (!Array.isArray(metadata.media_files)) return [];
278
+ return metadata.media_files.filter((file) => Boolean(file) && typeof file === "object" && typeof file.id === "string");
279
+ }
280
+ function ToolResultCard({ part, className, detailsOpen = true }) {
281
+ const officeMediaFiles = getOfficeDocumentMediaFiles(part);
282
+ if (part.toolType === "email_send") return /* @__PURE__ */ jsx(ToolResultEmailSendCard, {
283
+ part,
284
+ className
285
+ });
286
+ const statusClass = part.state === "error" ? "border-rose-200 bg-rose-50 text-rose-800" : part.state === "pending" ? "border-amber-200 bg-amber-50 text-amber-800" : "border-emerald-200 bg-emerald-50 text-emerald-800";
287
+ const statusLabel = part.state === "pending" ? "pending" : part.state === "error" ? "error" : "completed";
288
+ return /* @__PURE__ */ jsxs("section", {
289
+ className: joinClasses("space-y-3 rounded-lg border border-slate-200 bg-slate-50 p-3", className),
290
+ "data-tool-call-id": part.id,
291
+ "data-tool-call-state": part.state,
292
+ children: [
293
+ /* @__PURE__ */ jsxs("header", {
294
+ className: "flex items-center justify-between gap-2",
295
+ children: [/* @__PURE__ */ jsx("h4", {
296
+ className: "text-sm font-semibold text-slate-900",
297
+ children: part.name
298
+ }), /* @__PURE__ */ jsx("span", {
299
+ className: joinClasses("rounded-full border px-2 py-0.5 text-xs font-medium", statusClass),
300
+ children: statusLabel
301
+ })]
302
+ }),
303
+ part.toolType ? /* @__PURE__ */ jsxs("p", {
304
+ className: "text-xs text-slate-600",
305
+ children: [
306
+ /* @__PURE__ */ jsx("span", {
307
+ className: "font-semibold",
308
+ children: "Type:"
309
+ }),
310
+ " ",
311
+ part.toolType
312
+ ]
313
+ }) : null,
314
+ /* @__PURE__ */ jsxs("details", {
315
+ open: detailsOpen,
316
+ className: "space-y-2",
317
+ children: [/* @__PURE__ */ jsx("summary", {
318
+ className: "cursor-pointer text-xs font-semibold text-slate-600",
319
+ children: "Input"
320
+ }), /* @__PURE__ */ jsx("pre", {
321
+ className: "overflow-x-auto rounded bg-slate-900 p-2 text-xs text-slate-100",
322
+ children: formatJson(part.input)
323
+ })]
324
+ }),
325
+ part.result !== void 0 ? /* @__PURE__ */ jsxs("details", {
326
+ open: detailsOpen,
327
+ className: "space-y-2",
328
+ children: [
329
+ /* @__PURE__ */ jsx("summary", {
330
+ className: "cursor-pointer text-xs font-semibold text-slate-600",
331
+ children: "Output"
332
+ }),
333
+ officeMediaFiles.length > 0 ? /* @__PURE__ */ jsxs("div", {
334
+ className: "space-y-2 rounded border border-slate-200 bg-white p-3",
335
+ children: [/* @__PURE__ */ jsx("p", {
336
+ className: "text-xs font-semibold text-slate-700",
337
+ children: "Generated files"
338
+ }), /* @__PURE__ */ jsx("ul", {
339
+ className: "space-y-1",
340
+ children: officeMediaFiles.map((file) => {
341
+ const label = file.name || file.pathname || file.id;
342
+ return /* @__PURE__ */ jsx("li", {
343
+ className: "text-xs text-slate-700",
344
+ children: file.url ? /* @__PURE__ */ jsx("a", {
345
+ href: file.url,
346
+ target: "_blank",
347
+ rel: "noreferrer noopener",
348
+ className: "hover:underline",
349
+ children: label
350
+ }) : /* @__PURE__ */ jsx("span", { children: label })
351
+ }, file.id);
352
+ })
353
+ })]
354
+ }) : null,
355
+ /* @__PURE__ */ jsx("pre", {
356
+ className: "overflow-x-auto rounded bg-slate-900 p-2 text-xs text-slate-100",
357
+ children: formatJson(part.result)
358
+ })
359
+ ]
360
+ }) : null,
361
+ part.errorDetails ? /* @__PURE__ */ jsxs("p", {
362
+ className: "rounded border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-700",
363
+ children: [
364
+ /* @__PURE__ */ jsx("span", {
365
+ className: "font-semibold",
366
+ children: "Error details:"
367
+ }),
368
+ " ",
369
+ part.errorDetails
370
+ ]
371
+ }) : null
372
+ ]
373
+ });
374
+ }
375
+
376
+ //#endregion
377
+ //#region src/components/message.tsx
378
+ const DEFAULT_COLLAPSE_THRESHOLD = 600;
379
+ function getFilenameFromUrl(url) {
380
+ try {
381
+ const parsed = new URL(url);
382
+ return decodeURIComponent(parsed.pathname).split("/").pop()?.trim() || void 0;
383
+ } catch {
384
+ return (url.split("?")[0]?.split("#")[0] ?? "").split("/").pop()?.trim() || void 0;
385
+ }
386
+ }
387
+ function getDisplayExtension(label) {
388
+ if (!label) return;
389
+ const ext = label.split(".").pop()?.trim().toUpperCase();
390
+ if (!ext || ext === label.toUpperCase()) return;
391
+ return ext;
392
+ }
393
+ function renderPart(part, index) {
394
+ if (part.type === "text") return /* @__PURE__ */ jsx("p", {
395
+ className: "whitespace-pre-wrap text-sm leading-6",
396
+ children: part.text
397
+ }, `text-${index}`);
398
+ if (part.type === "input_image") {
399
+ const title = part.metadata?.originalFileName || part.title || getFilenameFromUrl(part.url);
400
+ return /* @__PURE__ */ jsxs("a", {
401
+ href: part.url,
402
+ target: "_blank",
403
+ rel: "noreferrer noopener",
404
+ className: "block w-fit rounded-lg border border-slate-200 bg-white p-2",
405
+ children: [/* @__PURE__ */ jsx("img", {
406
+ src: part.url,
407
+ alt: title || "Uploaded image",
408
+ className: "max-h-56 rounded-md object-contain"
409
+ }), title ? /* @__PURE__ */ jsx("p", {
410
+ className: "mt-2 max-w-xs truncate text-xs font-medium text-slate-700",
411
+ children: title
412
+ }) : null]
413
+ }, `image-${index}`);
414
+ }
415
+ if (part.type === "input_file") {
416
+ const fileName = part.metadata?.originalFileName || part.title || getFilenameFromUrl(part.fileUrl) || "Document";
417
+ const extension = getDisplayExtension(fileName);
418
+ return /* @__PURE__ */ jsxs("a", {
419
+ href: part.fileUrl,
420
+ target: "_blank",
421
+ rel: "noreferrer noopener",
422
+ className: "flex w-fit items-center gap-3 rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-left",
423
+ children: [/* @__PURE__ */ jsx("span", {
424
+ className: "rounded bg-slate-900 px-2 py-1 text-[10px] font-semibold uppercase tracking-wide text-white",
425
+ children: extension ?? "File"
426
+ }), /* @__PURE__ */ jsxs("div", {
427
+ className: "min-w-0",
428
+ children: [/* @__PURE__ */ jsx("p", {
429
+ className: "max-w-xs truncate text-sm font-medium text-slate-900",
430
+ children: fileName
431
+ }), part.mimeType ? /* @__PURE__ */ jsx("p", {
432
+ className: "text-xs text-slate-500",
433
+ children: part.mimeType
434
+ }) : null]
435
+ })]
436
+ }, `file-${index}`);
437
+ }
438
+ if (part.type === "tool-call") return /* @__PURE__ */ jsx(ToolResultCard, { part }, `tool-${part.id}-${index}`);
439
+ if (part.type === "guardrail") return /* @__PURE__ */ jsx("p", {
440
+ className: "rounded-lg border border-amber-300 bg-amber-50 px-3 py-2 text-sm text-amber-900",
441
+ children: part.content
442
+ }, `guardrail-${index}`);
443
+ return null;
444
+ }
445
+ function Message({ message, className, showRole = true, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD }) {
446
+ const roleLabel = message.role.charAt(0).toUpperCase() + message.role.slice(1);
447
+ const [isExpanded, setIsExpanded] = useState(false);
448
+ const textContent = useMemo(() => {
449
+ return message.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n");
450
+ }, [message.parts]);
451
+ const canCollapse = message.role === "user" && message.parts.every((part) => part.type === "text") && textContent.length > collapseThreshold;
452
+ const previewText = canCollapse ? `${textContent.slice(0, collapseThreshold).trimEnd()}...` : textContent;
453
+ return /* @__PURE__ */ jsxs("article", {
454
+ className: joinClasses("space-y-3 rounded-xl border border-slate-200 bg-white p-4 shadow-sm", className),
455
+ "data-message-role": message.role,
456
+ children: [
457
+ showRole ? /* @__PURE__ */ jsx("header", {
458
+ className: "text-xs font-semibold uppercase tracking-wide text-slate-500",
459
+ children: roleLabel
460
+ }) : null,
461
+ /* @__PURE__ */ jsx("div", {
462
+ className: "space-y-2",
463
+ children: canCollapse && !isExpanded ? /* @__PURE__ */ jsx("p", {
464
+ className: "whitespace-pre-wrap text-sm leading-6",
465
+ children: previewText
466
+ }) : message.parts.map((part, index) => renderPart(part, index))
467
+ }),
468
+ canCollapse ? /* @__PURE__ */ jsx("button", {
469
+ type: "button",
470
+ className: "text-left text-xs font-medium text-slate-600 hover:text-slate-900",
471
+ onClick: () => setIsExpanded((previous) => !previous),
472
+ children: isExpanded ? "Read less" : "Read more"
473
+ }) : null
474
+ ]
475
+ });
476
+ }
477
+
478
+ //#endregion
479
+ //#region src/components/icons/arrow.tsx
480
+ function ArrowUp(props) {
481
+ return /* @__PURE__ */ jsxs("svg", {
482
+ ...props,
483
+ xmlns: "http://www.w3.org/2000/svg",
484
+ width: "24",
485
+ height: "24",
486
+ viewBox: "0 0 24 24",
487
+ fill: "none",
488
+ stroke: "currentColor",
489
+ strokeWidth: "2",
490
+ strokeLinecap: "round",
491
+ strokeLinejoin: "round",
492
+ "aria-hidden": "true",
493
+ children: [/* @__PURE__ */ jsx("path", { d: "m5 12 7-7 7 7" }), /* @__PURE__ */ jsx("path", { d: "M12 19V5" })]
494
+ });
495
+ }
496
+
497
+ //#endregion
498
+ //#region src/components/icons/loader.tsx
499
+ function Loader(props) {
500
+ return /* @__PURE__ */ jsx("svg", {
501
+ ...props,
502
+ xmlns: "http://www.w3.org/2000/svg",
503
+ width: "24",
504
+ height: "24",
505
+ viewBox: "0 0 24 24",
506
+ fill: "none",
507
+ stroke: "currentColor",
508
+ strokeWidth: "2",
509
+ strokeLinecap: "round",
510
+ strokeLinejoin: "round",
511
+ "aria-hidden": "true",
512
+ children: /* @__PURE__ */ jsx("path", { d: "M21 12a9 9 0 1 1-6.219-8.56" })
513
+ });
514
+ }
515
+
516
+ //#endregion
517
+ //#region src/components/icons/microphone.tsx
518
+ function Microphone(props) {
519
+ return /* @__PURE__ */ jsxs("svg", {
520
+ ...props,
521
+ xmlns: "http://www.w3.org/2000/svg",
522
+ width: "24",
523
+ height: "24",
524
+ viewBox: "0 0 24 24",
525
+ fill: "none",
526
+ stroke: "currentColor",
527
+ strokeWidth: "2",
528
+ strokeLinecap: "round",
529
+ strokeLinejoin: "round",
530
+ "aria-hidden": "true",
531
+ children: [
532
+ /* @__PURE__ */ jsx("path", { d: "M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z" }),
533
+ /* @__PURE__ */ jsx("path", { d: "M19 10v2a7 7 0 0 1-14 0v-2" }),
534
+ /* @__PURE__ */ jsx("path", { d: "M12 19v3" })
535
+ ]
536
+ });
537
+ }
538
+
539
+ //#endregion
540
+ //#region src/components/icons/paperclip.tsx
541
+ function Paperclip(props) {
542
+ return /* @__PURE__ */ jsx("svg", {
543
+ ...props,
544
+ xmlns: "http://www.w3.org/2000/svg",
545
+ width: "24",
546
+ height: "24",
547
+ viewBox: "0 0 24 24",
548
+ fill: "none",
549
+ stroke: "currentColor",
550
+ strokeWidth: "2",
551
+ strokeLinecap: "round",
552
+ strokeLinejoin: "round",
553
+ "aria-hidden": "true",
554
+ children: /* @__PURE__ */ jsx("path", { d: "m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l9.19-9.19a4 4 0 0 1 5.66 5.66l-9.2 9.19a2 2 0 0 1-2.83-2.83l8.49-8.48" })
555
+ });
556
+ }
557
+
558
+ //#endregion
559
+ //#region src/components/icons/stop.tsx
560
+ function Stop(props) {
561
+ return /* @__PURE__ */ jsx("svg", {
562
+ ...props,
563
+ xmlns: "http://www.w3.org/2000/svg",
564
+ width: "24",
565
+ height: "24",
566
+ viewBox: "0 0 24 24",
567
+ fill: "none",
568
+ stroke: "currentColor",
569
+ strokeWidth: "2",
570
+ strokeLinecap: "round",
571
+ strokeLinejoin: "round",
572
+ "aria-hidden": "true",
573
+ children: /* @__PURE__ */ jsx("rect", {
574
+ x: "6",
575
+ y: "6",
576
+ width: "12",
577
+ height: "12",
578
+ rx: "1"
579
+ })
580
+ });
581
+ }
582
+
583
+ //#endregion
584
+ //#region src/components/icons/x.tsx
585
+ function X(props) {
586
+ return /* @__PURE__ */ jsxs("svg", {
587
+ ...props,
588
+ xmlns: "http://www.w3.org/2000/svg",
589
+ width: "24",
590
+ height: "24",
591
+ viewBox: "0 0 24 24",
592
+ fill: "none",
593
+ stroke: "currentColor",
594
+ strokeWidth: "2",
595
+ strokeLinecap: "round",
596
+ strokeLinejoin: "round",
597
+ "aria-hidden": "true",
598
+ children: [/* @__PURE__ */ jsx("path", { d: "M18 6 6 18" }), /* @__PURE__ */ jsx("path", { d: "m6 6 12 12" })]
599
+ });
600
+ }
601
+
602
+ //#endregion
603
+ //#region src/components/prompt-form/file-attachments.ts
604
+ const ALLOWED_EXTENSIONS = new Set([
605
+ ".pdf",
606
+ ".jpg",
607
+ ".jpeg",
608
+ ".png",
609
+ ".gif",
610
+ ".webp",
611
+ ".bmp",
612
+ ".doc",
613
+ ".docx",
614
+ ".xls",
615
+ ".xlsx",
616
+ ".ppt",
617
+ ".pptx"
618
+ ]);
619
+ const PROMPT_FORM_FILE_ACCEPT = "image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx";
620
+ function getFileExtension(filename) {
621
+ const lastDotIndex = filename.lastIndexOf(".");
622
+ if (lastDotIndex <= 0 || lastDotIndex === filename.length - 1) return;
623
+ return filename.slice(lastDotIndex).toLowerCase();
624
+ }
625
+ function isAllowedPromptFormFile(file) {
626
+ const extension = getFileExtension(file.name);
627
+ if (extension && ALLOWED_EXTENSIONS.has(extension)) return true;
628
+ return file.type.startsWith("image/");
629
+ }
630
+ function partitionPromptFormFiles(files) {
631
+ const validFiles = [];
632
+ const invalidFiles = [];
633
+ for (const file of files) {
634
+ if (isAllowedPromptFormFile(file)) {
635
+ validFiles.push(file);
636
+ continue;
637
+ }
638
+ invalidFiles.push({
639
+ file,
640
+ reason: `File type is not supported for "${file.name}".`
641
+ });
642
+ }
643
+ return {
644
+ validFiles,
645
+ invalidFiles
646
+ };
647
+ }
648
+
649
+ //#endregion
650
+ //#region src/components/prompt-form/prompt-form-attach-button.tsx
651
+ function PromptFormAttachButton({ onFilesSelected, onInvalidFiles, accept = PROMPT_FORM_FILE_ACCEPT, disabled = false, label = "Attach file",...props }) {
652
+ const fileInputRef = useRef(null);
653
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("input", {
654
+ ref: fileInputRef,
655
+ type: "file",
656
+ accept,
657
+ multiple: true,
658
+ className: "hidden",
659
+ onChange: (event) => {
660
+ const { validFiles, invalidFiles } = partitionPromptFormFiles(Array.from(event.target.files ?? []));
661
+ if (invalidFiles.length > 0) onInvalidFiles?.(invalidFiles);
662
+ if (validFiles.length > 0) onFilesSelected(validFiles);
663
+ event.currentTarget.value = "";
664
+ }
665
+ }), /* @__PURE__ */ jsx(PromptFormIconButton, {
666
+ type: "button",
667
+ "aria-label": label,
668
+ disabled,
669
+ onClick: () => fileInputRef.current?.click(),
670
+ ...props,
671
+ children: /* @__PURE__ */ jsx(Paperclip, { className: "size-4" })
672
+ })] });
673
+ }
674
+
675
+ //#endregion
676
+ //#region src/components/prompt-form/prompt-form.tsx
677
+ const actionButtonClassName = "inline-flex size-8 shrink-0 items-center justify-center rounded-md bg-neutral-100 text-neutral-600 transition-colors hover:bg-neutral-200 disabled:cursor-not-allowed disabled:opacity-40";
678
+ const defaultMaxRows = 4;
679
+ function resizeTextarea(textarea, maxRows) {
680
+ const styles = getComputedStyle(textarea);
681
+ const lineHeight = Number.parseFloat(styles.lineHeight);
682
+ const paddingTop = Number.parseFloat(styles.paddingTop);
683
+ const paddingBottom = Number.parseFloat(styles.paddingBottom);
684
+ const maxHeight = lineHeight * maxRows + paddingTop + paddingBottom;
685
+ textarea.style.height = "auto";
686
+ textarea.style.height = `${Math.min(textarea.scrollHeight, maxHeight)}px`;
687
+ textarea.style.overflowY = textarea.scrollHeight > maxHeight ? "auto" : "hidden";
688
+ }
689
+ function PromptFormIconButton({ className, type = "button",...props }) {
690
+ return /* @__PURE__ */ jsx("button", {
691
+ type,
692
+ className: joinClasses(actionButtonClassName, className),
693
+ ...props
694
+ });
695
+ }
696
+ function PromptForm({ value, onValueChange, onSubmit, status = "ready", onStop, disabled = false, clearOnSubmit = true, enabledTools, placeholder = "Type a message...", sendLabel = "Send", stopLabel = "Stop", attachLabel = "Attach file", removeFileLabel = "Remove file", enableAttachments = true, files: filesProp, onFilesChange, onInvalidFiles, accept = PROMPT_FORM_FILE_ACCEPT, className, textareaClassName, attachmentsClassName, maxRows = defaultMaxRows, submitButtonClassName, stopButtonClassName, leftSlot, rightSlot }) {
697
+ const textareaRef = useRef(null);
698
+ const [internalFiles, setInternalFiles] = useState([]);
699
+ const [isSubmitting, setIsSubmitting] = useState(false);
700
+ const files = filesProp ?? internalFiles;
701
+ const setFiles = onFilesChange ?? setInternalFiles;
702
+ const isStreaming = status === "streaming" || status === "submitted";
703
+ const hasContent = value.trim().length > 0 || files.length > 0;
704
+ const canSubmit = !disabled && !isSubmitting && !isStreaming && hasContent;
705
+ const isInteractionDisabled = disabled || isSubmitting;
706
+ useLayoutEffect(() => {
707
+ const textarea = textareaRef.current;
708
+ if (textarea) resizeTextarea(textarea, maxRows);
709
+ }, [maxRows]);
710
+ function addFiles(nextFiles) {
711
+ const { validFiles, invalidFiles } = partitionPromptFormFiles(nextFiles);
712
+ if (invalidFiles.length > 0) onInvalidFiles?.(invalidFiles);
713
+ if (validFiles.length > 0) setFiles([...files, ...validFiles]);
714
+ }
715
+ function removeFile(index) {
716
+ setFiles(files.filter((_, fileIndex) => fileIndex !== index));
717
+ }
718
+ return /* @__PURE__ */ jsxs("form", {
719
+ className: joinClasses("flex w-full flex-col overflow-hidden rounded-2xl border border-neutral-200 bg-white", className),
720
+ onSubmit: async (event) => {
721
+ event.preventDefault();
722
+ if (!canSubmit) return;
723
+ setIsSubmitting(true);
724
+ try {
725
+ const text = value.trim();
726
+ const selectedFiles = [...files];
727
+ await onSubmit({
728
+ text,
729
+ ...enabledTools ? { enabledTools } : {},
730
+ files: selectedFiles
731
+ });
732
+ if (clearOnSubmit) {
733
+ onValueChange("");
734
+ setFiles([]);
735
+ }
736
+ } finally {
737
+ setIsSubmitting(false);
738
+ queueMicrotask(() => {
739
+ const textarea = textareaRef.current;
740
+ if (textarea) resizeTextarea(textarea, maxRows);
741
+ });
742
+ }
743
+ },
744
+ children: [/* @__PURE__ */ jsxs("div", {
745
+ className: "flex items-end gap-3 px-4 py-3",
746
+ children: [
747
+ leftSlot ?? null,
748
+ /* @__PURE__ */ jsx("textarea", {
749
+ ref: textareaRef,
750
+ rows: 1,
751
+ className: joinClasses("min-h-10 flex-1 resize-none overflow-hidden border-0 bg-transparent px-0 py-1.5 text-sm leading-6 text-neutral-900 outline-none placeholder:text-neutral-400", textareaClassName),
752
+ value,
753
+ onChange: (event) => {
754
+ onValueChange(event.target.value);
755
+ resizeTextarea(event.currentTarget, maxRows);
756
+ },
757
+ placeholder,
758
+ disabled: isInteractionDisabled
759
+ }),
760
+ /* @__PURE__ */ jsxs("div", {
761
+ className: "flex shrink-0 items-center gap-2",
762
+ children: [
763
+ enableAttachments ? /* @__PURE__ */ jsx(PromptFormAttachButton, {
764
+ accept,
765
+ disabled: isInteractionDisabled,
766
+ label: attachLabel,
767
+ onFilesSelected: addFiles,
768
+ onInvalidFiles
769
+ }) : null,
770
+ rightSlot ?? null,
771
+ isStreaming ? /* @__PURE__ */ jsx(PromptFormIconButton, {
772
+ "aria-label": stopLabel,
773
+ className: stopButtonClassName,
774
+ onClick: onStop,
775
+ disabled: disabled || !onStop,
776
+ children: /* @__PURE__ */ jsx(Stop, { className: "size-4" })
777
+ }) : /* @__PURE__ */ jsx(PromptFormIconButton, {
778
+ type: "submit",
779
+ "aria-label": sendLabel,
780
+ className: submitButtonClassName,
781
+ disabled: !canSubmit,
782
+ children: /* @__PURE__ */ jsx(ArrowUp, { className: "size-4" })
783
+ })
784
+ ]
785
+ })
786
+ ]
787
+ }), files.length > 0 ? /* @__PURE__ */ jsx("div", {
788
+ className: joinClasses("flex flex-wrap gap-2 border-t border-neutral-200 px-4 py-2", attachmentsClassName),
789
+ children: files.map((file, index) => /* @__PURE__ */ jsxs("div", {
790
+ className: "flex max-w-full items-center gap-1.5 rounded-md bg-neutral-100 px-2 py-1 text-xs text-neutral-700",
791
+ children: [/* @__PURE__ */ jsx("span", {
792
+ className: "max-w-[150px] truncate",
793
+ children: file.name
794
+ }), /* @__PURE__ */ jsx("button", {
795
+ type: "button",
796
+ className: "text-neutral-500 transition-colors hover:text-neutral-800 disabled:cursor-not-allowed disabled:opacity-40",
797
+ "aria-label": `${removeFileLabel}: ${file.name}`,
798
+ disabled: isInteractionDisabled,
799
+ onClick: () => removeFile(index),
800
+ children: /* @__PURE__ */ jsx(X, { className: "size-3.5" })
801
+ })]
802
+ }, `${file.name}-${file.lastModified}-${index}`))
803
+ }) : null]
804
+ });
805
+ }
806
+
807
+ //#endregion
808
+ //#region src/components/speech-to-text-toggle/transcribe-audio.ts
809
+ const DUMMY_TRANSCRIPTION = "Hello, this is a demo transcription.";
810
+ async function dummyTranscribeAudio(_audio, signal) {
811
+ await new Promise((resolve, reject) => {
812
+ const timeoutId = setTimeout(resolve, 600);
813
+ signal?.addEventListener("abort", () => {
814
+ clearTimeout(timeoutId);
815
+ reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
816
+ }, { once: true });
817
+ });
818
+ return DUMMY_TRANSCRIPTION;
819
+ }
820
+ async function transcribeAudioViaEndpoint(audio, endpoint, signal) {
821
+ const response = await fetch(endpoint, {
822
+ method: "POST",
823
+ body: audio,
824
+ signal
825
+ });
826
+ if (!response.ok) throw new Error(`Transcription request failed with status ${response.status}`);
827
+ const body = await response.json();
828
+ const text = body.text ?? body.data;
829
+ if (!text) throw new Error("Transcription response did not include text");
830
+ return text;
831
+ }
832
+
833
+ //#endregion
834
+ //#region src/components/speech-to-text-toggle/use-voice-recording.ts
835
+ function useVoiceRecording() {
836
+ const mediaRecorderRef = useRef(null);
837
+ const streamRef = useRef(null);
838
+ const chunksRef = useRef([]);
839
+ const stopTracks = useCallback(() => {
840
+ for (const track of streamRef.current?.getTracks() ?? []) track.stop();
841
+ streamRef.current = null;
842
+ }, []);
843
+ return {
844
+ start: useCallback(async () => {
845
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
846
+ const recorder = new MediaRecorder(stream);
847
+ streamRef.current = stream;
848
+ chunksRef.current = [];
849
+ mediaRecorderRef.current = recorder;
850
+ recorder.addEventListener("dataavailable", (event) => {
851
+ if (event.data.size > 0) chunksRef.current.push(event.data);
852
+ });
853
+ recorder.start();
854
+ }, []),
855
+ stop: useCallback(async () => {
856
+ const recorder = mediaRecorderRef.current;
857
+ if (!recorder || recorder.state === "inactive") throw new Error("No active voice recording");
858
+ const audio = await new Promise((resolve, reject) => {
859
+ recorder.addEventListener("stop", () => {
860
+ stopTracks();
861
+ mediaRecorderRef.current = null;
862
+ resolve(new Blob(chunksRef.current, { type: recorder.mimeType || "audio/webm" }));
863
+ }, { once: true });
864
+ recorder.addEventListener("error", () => {
865
+ stopTracks();
866
+ mediaRecorderRef.current = null;
867
+ reject(/* @__PURE__ */ new Error("Failed to stop voice recording"));
868
+ }, { once: true });
869
+ recorder.stop();
870
+ });
871
+ chunksRef.current = [];
872
+ return audio;
873
+ }, [stopTracks]),
874
+ cancel: useCallback(() => {
875
+ const recorder = mediaRecorderRef.current;
876
+ if (recorder && recorder.state !== "inactive") recorder.stop();
877
+ stopTracks();
878
+ mediaRecorderRef.current = null;
879
+ chunksRef.current = [];
880
+ }, [stopTracks])
881
+ };
882
+ }
883
+
884
+ //#endregion
885
+ //#region src/components/speech-to-text-toggle/speech-to-text-toggle.tsx
886
+ function SpeechToTextToggle({ onTranscriptionComplete, onTranscriptionError, transcribe, transcriptionEndpoint, disabled = false, label = "Voice input", listeningLabel = "Stop recording", loadingLabel = "Transcribing...", className,...props }) {
887
+ const [isListening, setIsListening] = useState(false);
888
+ const [isTranscribing, setIsTranscribing] = useState(false);
889
+ const abortControllerRef = useRef(null);
890
+ const { start, stop } = useVoiceRecording();
891
+ const transcribeAudio = transcribe ?? (transcriptionEndpoint ? (audio, signal) => transcribeAudioViaEndpoint(audio, transcriptionEndpoint, signal) : dummyTranscribeAudio);
892
+ async function handleToggle() {
893
+ if (disabled || isTranscribing) return;
894
+ if (!isListening) {
895
+ try {
896
+ await start();
897
+ setIsListening(true);
898
+ } catch (error) {
899
+ onTranscriptionError?.(error instanceof Error ? error : /* @__PURE__ */ new Error("Microphone access was denied"));
900
+ }
901
+ return;
902
+ }
903
+ setIsListening(false);
904
+ setIsTranscribing(true);
905
+ const abortController = new AbortController();
906
+ abortControllerRef.current = abortController;
907
+ try {
908
+ const text = await transcribeAudio(await stop(), abortController.signal);
909
+ if (text.trim()) onTranscriptionComplete(text);
910
+ } catch (error) {
911
+ if (error instanceof DOMException && error.name === "AbortError") return;
912
+ onTranscriptionError?.(error instanceof Error ? error : /* @__PURE__ */ new Error("Transcription failed"));
913
+ } finally {
914
+ abortControllerRef.current = null;
915
+ setIsTranscribing(false);
916
+ }
917
+ }
918
+ const ariaLabel = isTranscribing ? loadingLabel : isListening ? listeningLabel : label;
919
+ return /* @__PURE__ */ jsx(PromptFormIconButton, {
920
+ type: "button",
921
+ "aria-label": ariaLabel,
922
+ "aria-pressed": isListening,
923
+ "aria-busy": isTranscribing,
924
+ disabled: disabled || isTranscribing,
925
+ className: joinClasses(isListening && !isTranscribing ? "text-red-600" : void 0, className),
926
+ onClick: () => {
927
+ handleToggle();
928
+ },
929
+ ...props,
930
+ children: isTranscribing ? /* @__PURE__ */ jsx(Loader, { className: "size-4 animate-spin" }) : /* @__PURE__ */ jsx(Microphone, { className: "size-4" })
931
+ });
932
+ }
933
+
934
+ //#endregion
935
+ export { ArrowUp, Loader, Message, Microphone, PROMPT_FORM_FILE_ACCEPT, Paperclip, PromptForm, PromptFormAttachButton, PromptFormIconButton, SpeechToTextToggle, Stop, ToolResultCard, X, dummyTranscribeAudio, isAllowedPromptFormFile, partitionPromptFormFiles, transcribeAudioViaEndpoint, useChat };
44
936
  //# sourceMappingURL=index.js.map