reachat 2.1.2 → 2.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.
Files changed (36) hide show
  1. package/dist/{CSVFileRenderer-DXI8PDqR.js → CSVFileRenderer-BOdL4Jte.js} +2 -2
  2. package/dist/{CSVFileRenderer-DXI8PDqR.js.map → CSVFileRenderer-BOdL4Jte.js.map} +1 -1
  3. package/dist/{DefaultFileRenderer-Bi8LNDio.js → DefaultFileRenderer-C2MsQ9wz.js} +3 -3
  4. package/dist/{DefaultFileRenderer-Bi8LNDio.js.map → DefaultFileRenderer-C2MsQ9wz.js.map} +1 -1
  5. package/dist/Markdown/plugins/index.d.ts +2 -0
  6. package/dist/Markdown/plugins/redactMatchers.d.ts +21 -0
  7. package/dist/Markdown/plugins/remarkRedact.d.ts +37 -0
  8. package/dist/SessionMessages/SessionMessage/MessageActions.d.ts +2 -2
  9. package/dist/SessionMessages/SessionMessage/MessageFiles.d.ts +2 -2
  10. package/dist/SessionMessages/SessionMessage/MessageQuestion.d.ts +2 -2
  11. package/dist/SessionMessages/SessionMessage/MessageResponse.d.ts +2 -2
  12. package/dist/SessionMessages/SessionMessage/MessageSources.d.ts +2 -2
  13. package/dist/SessionMessages/SessionMessage/SessionMessage.d.ts +2 -2
  14. package/dist/SessionsList/SessionListItem.d.ts +2 -2
  15. package/dist/docs.json +5 -13
  16. package/dist/{index-CBHNcMyR.js → index-DdRyk11n.js} +783 -1458
  17. package/dist/index-DdRyk11n.js.map +1 -0
  18. package/dist/index.css +6 -1
  19. package/dist/index.d.ts +1 -0
  20. package/dist/index.js +53 -46
  21. package/dist/index.umd.cjs +735 -1412
  22. package/dist/index.umd.cjs.map +1 -1
  23. package/dist/stories/AgUi.stories.tsx +118 -0
  24. package/dist/stories/Chat.stories.tsx +6 -1
  25. package/dist/stories/ChatSuggestions.stories.tsx +9 -81
  26. package/dist/stories/Companion.stories.tsx +7 -1
  27. package/dist/stories/Console.stories.tsx +66 -21
  28. package/dist/stories/EnhancedInput.stories.tsx +7 -1
  29. package/dist/stories/Redact.stories.tsx +175 -0
  30. package/dist/stories/examples.ts +31 -0
  31. package/dist/useAgUi/index.d.ts +4 -0
  32. package/dist/useAgUi/types.d.ts +157 -0
  33. package/dist/useAgUi/useAgUi.d.ts +119 -0
  34. package/dist/useAgUi/useAgUi.spec.d.ts +1 -0
  35. package/package.json +3 -1
  36. package/dist/index-CBHNcMyR.js.map +0 -1
@@ -1,8 +1,9 @@
1
1
  import { jsxs, Fragment, jsx } from "react/jsx-runtime";
2
2
  import * as React from "react";
3
- import { createContext, useContext, useRef, forwardRef, useState, useEffect, useCallback, useImperativeHandle, useMemo, lazy, Suspense, memo, isValidElement, cloneElement } from "react";
4
- import { Button, cn, List, ListItem, Ellipsis, DateFormat, IconButton, Card, useInfinityList, useComponentTheme, ConnectedOverlay } from "reablocks";
3
+ import { createContext, useContext, useRef, forwardRef, useState, useEffect, useCallback, useImperativeHandle, memo, useMemo, lazy, Suspense, isValidElement, cloneElement } from "react";
4
+ import { Button, cn, List, ListItem, Ellipsis, DateFormat, Redact, IconButton, Card, useInfinityList, useComponentTheme, ConnectedOverlay } from "reablocks";
5
5
  import { useEditor, EditorContent, ReactRenderer, posToDOMRect } from "@tiptap/react";
6
+ import { computePosition, shift, flip } from "@floating-ui/dom";
6
7
  import Document from "@tiptap/extension-document";
7
8
  import Paragraph from "@tiptap/extension-paragraph";
8
9
  import Text from "@tiptap/extension-text";
@@ -14,6 +15,7 @@ import { motion, AnimatePresence } from "motion/react";
14
15
  import ReactMarkdown from "react-markdown";
15
16
  import { Prism } from "react-syntax-highlighter";
16
17
  import rehypeKatex from "rehype-katex";
18
+ import rehypeRaw from "rehype-raw";
17
19
  import { SparklineChart, RadialAreaChart, RadialAreaSeries, RadialBarChart, RadialBarSeries, PieChart, PieArcSeries, AreaChart, AreaSeries, LinearYAxis, LinearXAxis, LineChart, LineSeries, BarChart, BarSeries } from "reaviz";
18
20
  import { findAndReplace } from "mdast-util-find-and-replace";
19
21
  import { visit } from "unist-util-visit";
@@ -72,1116 +74,6 @@ const FileInput = ({
72
74
  )
73
75
  ] });
74
76
  };
75
- const min = Math.min;
76
- const max = Math.max;
77
- const round = Math.round;
78
- const createCoords = (v) => ({
79
- x: v,
80
- y: v
81
- });
82
- const oppositeSideMap = {
83
- left: "right",
84
- right: "left",
85
- bottom: "top",
86
- top: "bottom"
87
- };
88
- const oppositeAlignmentMap = {
89
- start: "end",
90
- end: "start"
91
- };
92
- function clamp(start, value, end) {
93
- return max(start, min(value, end));
94
- }
95
- function evaluate(value, param) {
96
- return typeof value === "function" ? value(param) : value;
97
- }
98
- function getSide(placement) {
99
- return placement.split("-")[0];
100
- }
101
- function getAlignment(placement) {
102
- return placement.split("-")[1];
103
- }
104
- function getOppositeAxis(axis) {
105
- return axis === "x" ? "y" : "x";
106
- }
107
- function getAxisLength(axis) {
108
- return axis === "y" ? "height" : "width";
109
- }
110
- const yAxisSides = /* @__PURE__ */ new Set(["top", "bottom"]);
111
- function getSideAxis(placement) {
112
- return yAxisSides.has(getSide(placement)) ? "y" : "x";
113
- }
114
- function getAlignmentAxis(placement) {
115
- return getOppositeAxis(getSideAxis(placement));
116
- }
117
- function getAlignmentSides(placement, rects, rtl) {
118
- if (rtl === void 0) {
119
- rtl = false;
120
- }
121
- const alignment = getAlignment(placement);
122
- const alignmentAxis = getAlignmentAxis(placement);
123
- const length = getAxisLength(alignmentAxis);
124
- let mainAlignmentSide = alignmentAxis === "x" ? alignment === (rtl ? "end" : "start") ? "right" : "left" : alignment === "start" ? "bottom" : "top";
125
- if (rects.reference[length] > rects.floating[length]) {
126
- mainAlignmentSide = getOppositePlacement(mainAlignmentSide);
127
- }
128
- return [mainAlignmentSide, getOppositePlacement(mainAlignmentSide)];
129
- }
130
- function getExpandedPlacements(placement) {
131
- const oppositePlacement = getOppositePlacement(placement);
132
- return [getOppositeAlignmentPlacement(placement), oppositePlacement, getOppositeAlignmentPlacement(oppositePlacement)];
133
- }
134
- function getOppositeAlignmentPlacement(placement) {
135
- return placement.replace(/start|end/g, (alignment) => oppositeAlignmentMap[alignment]);
136
- }
137
- const lrPlacement = ["left", "right"];
138
- const rlPlacement = ["right", "left"];
139
- const tbPlacement = ["top", "bottom"];
140
- const btPlacement = ["bottom", "top"];
141
- function getSideList(side, isStart, rtl) {
142
- switch (side) {
143
- case "top":
144
- case "bottom":
145
- if (rtl) return isStart ? rlPlacement : lrPlacement;
146
- return isStart ? lrPlacement : rlPlacement;
147
- case "left":
148
- case "right":
149
- return isStart ? tbPlacement : btPlacement;
150
- default:
151
- return [];
152
- }
153
- }
154
- function getOppositeAxisPlacements(placement, flipAlignment, direction, rtl) {
155
- const alignment = getAlignment(placement);
156
- let list = getSideList(getSide(placement), direction === "start", rtl);
157
- if (alignment) {
158
- list = list.map((side) => side + "-" + alignment);
159
- if (flipAlignment) {
160
- list = list.concat(list.map(getOppositeAlignmentPlacement));
161
- }
162
- }
163
- return list;
164
- }
165
- function getOppositePlacement(placement) {
166
- return placement.replace(/left|right|bottom|top/g, (side) => oppositeSideMap[side]);
167
- }
168
- function expandPaddingObject(padding) {
169
- return {
170
- top: 0,
171
- right: 0,
172
- bottom: 0,
173
- left: 0,
174
- ...padding
175
- };
176
- }
177
- function getPaddingObject(padding) {
178
- return typeof padding !== "number" ? expandPaddingObject(padding) : {
179
- top: padding,
180
- right: padding,
181
- bottom: padding,
182
- left: padding
183
- };
184
- }
185
- function rectToClientRect(rect) {
186
- const {
187
- x,
188
- y,
189
- width,
190
- height
191
- } = rect;
192
- return {
193
- width,
194
- height,
195
- top: y,
196
- left: x,
197
- right: x + width,
198
- bottom: y + height,
199
- x,
200
- y
201
- };
202
- }
203
- function computeCoordsFromPlacement(_ref, placement, rtl) {
204
- let {
205
- reference,
206
- floating
207
- } = _ref;
208
- const sideAxis = getSideAxis(placement);
209
- const alignmentAxis = getAlignmentAxis(placement);
210
- const alignLength = getAxisLength(alignmentAxis);
211
- const side = getSide(placement);
212
- const isVertical = sideAxis === "y";
213
- const commonX = reference.x + reference.width / 2 - floating.width / 2;
214
- const commonY = reference.y + reference.height / 2 - floating.height / 2;
215
- const commonAlign = reference[alignLength] / 2 - floating[alignLength] / 2;
216
- let coords;
217
- switch (side) {
218
- case "top":
219
- coords = {
220
- x: commonX,
221
- y: reference.y - floating.height
222
- };
223
- break;
224
- case "bottom":
225
- coords = {
226
- x: commonX,
227
- y: reference.y + reference.height
228
- };
229
- break;
230
- case "right":
231
- coords = {
232
- x: reference.x + reference.width,
233
- y: commonY
234
- };
235
- break;
236
- case "left":
237
- coords = {
238
- x: reference.x - floating.width,
239
- y: commonY
240
- };
241
- break;
242
- default:
243
- coords = {
244
- x: reference.x,
245
- y: reference.y
246
- };
247
- }
248
- switch (getAlignment(placement)) {
249
- case "start":
250
- coords[alignmentAxis] -= commonAlign * (rtl && isVertical ? -1 : 1);
251
- break;
252
- case "end":
253
- coords[alignmentAxis] += commonAlign * (rtl && isVertical ? -1 : 1);
254
- break;
255
- }
256
- return coords;
257
- }
258
- const computePosition$1 = async (reference, floating, config) => {
259
- const {
260
- placement = "bottom",
261
- strategy = "absolute",
262
- middleware = [],
263
- platform: platform2
264
- } = config;
265
- const validMiddleware = middleware.filter(Boolean);
266
- const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(floating));
267
- let rects = await platform2.getElementRects({
268
- reference,
269
- floating,
270
- strategy
271
- });
272
- let {
273
- x,
274
- y
275
- } = computeCoordsFromPlacement(rects, placement, rtl);
276
- let statefulPlacement = placement;
277
- let middlewareData = {};
278
- let resetCount = 0;
279
- for (let i = 0; i < validMiddleware.length; i++) {
280
- const {
281
- name,
282
- fn
283
- } = validMiddleware[i];
284
- const {
285
- x: nextX,
286
- y: nextY,
287
- data,
288
- reset
289
- } = await fn({
290
- x,
291
- y,
292
- initialPlacement: placement,
293
- placement: statefulPlacement,
294
- strategy,
295
- middlewareData,
296
- rects,
297
- platform: platform2,
298
- elements: {
299
- reference,
300
- floating
301
- }
302
- });
303
- x = nextX != null ? nextX : x;
304
- y = nextY != null ? nextY : y;
305
- middlewareData = {
306
- ...middlewareData,
307
- [name]: {
308
- ...middlewareData[name],
309
- ...data
310
- }
311
- };
312
- if (reset && resetCount <= 50) {
313
- resetCount++;
314
- if (typeof reset === "object") {
315
- if (reset.placement) {
316
- statefulPlacement = reset.placement;
317
- }
318
- if (reset.rects) {
319
- rects = reset.rects === true ? await platform2.getElementRects({
320
- reference,
321
- floating,
322
- strategy
323
- }) : reset.rects;
324
- }
325
- ({
326
- x,
327
- y
328
- } = computeCoordsFromPlacement(rects, statefulPlacement, rtl));
329
- }
330
- i = -1;
331
- }
332
- }
333
- return {
334
- x,
335
- y,
336
- placement: statefulPlacement,
337
- strategy,
338
- middlewareData
339
- };
340
- };
341
- async function detectOverflow(state, options) {
342
- var _await$platform$isEle;
343
- if (options === void 0) {
344
- options = {};
345
- }
346
- const {
347
- x,
348
- y,
349
- platform: platform2,
350
- rects,
351
- elements,
352
- strategy
353
- } = state;
354
- const {
355
- boundary = "clippingAncestors",
356
- rootBoundary = "viewport",
357
- elementContext = "floating",
358
- altBoundary = false,
359
- padding = 0
360
- } = evaluate(options, state);
361
- const paddingObject = getPaddingObject(padding);
362
- const altContext = elementContext === "floating" ? "reference" : "floating";
363
- const element = elements[altBoundary ? altContext : elementContext];
364
- const clippingClientRect = rectToClientRect(await platform2.getClippingRect({
365
- element: ((_await$platform$isEle = await (platform2.isElement == null ? void 0 : platform2.isElement(element))) != null ? _await$platform$isEle : true) ? element : element.contextElement || await (platform2.getDocumentElement == null ? void 0 : platform2.getDocumentElement(elements.floating)),
366
- boundary,
367
- rootBoundary,
368
- strategy
369
- }));
370
- const rect = elementContext === "floating" ? {
371
- x,
372
- y,
373
- width: rects.floating.width,
374
- height: rects.floating.height
375
- } : rects.reference;
376
- const offsetParent = await (platform2.getOffsetParent == null ? void 0 : platform2.getOffsetParent(elements.floating));
377
- const offsetScale = await (platform2.isElement == null ? void 0 : platform2.isElement(offsetParent)) ? await (platform2.getScale == null ? void 0 : platform2.getScale(offsetParent)) || {
378
- x: 1,
379
- y: 1
380
- } : {
381
- x: 1,
382
- y: 1
383
- };
384
- const elementClientRect = rectToClientRect(platform2.convertOffsetParentRelativeRectToViewportRelativeRect ? await platform2.convertOffsetParentRelativeRectToViewportRelativeRect({
385
- elements,
386
- rect,
387
- offsetParent,
388
- strategy
389
- }) : rect);
390
- return {
391
- top: (clippingClientRect.top - elementClientRect.top + paddingObject.top) / offsetScale.y,
392
- bottom: (elementClientRect.bottom - clippingClientRect.bottom + paddingObject.bottom) / offsetScale.y,
393
- left: (clippingClientRect.left - elementClientRect.left + paddingObject.left) / offsetScale.x,
394
- right: (elementClientRect.right - clippingClientRect.right + paddingObject.right) / offsetScale.x
395
- };
396
- }
397
- const flip$1 = function(options) {
398
- if (options === void 0) {
399
- options = {};
400
- }
401
- return {
402
- name: "flip",
403
- options,
404
- async fn(state) {
405
- var _middlewareData$arrow, _middlewareData$flip;
406
- const {
407
- placement,
408
- middlewareData,
409
- rects,
410
- initialPlacement,
411
- platform: platform2,
412
- elements
413
- } = state;
414
- const {
415
- mainAxis: checkMainAxis = true,
416
- crossAxis: checkCrossAxis = true,
417
- fallbackPlacements: specifiedFallbackPlacements,
418
- fallbackStrategy = "bestFit",
419
- fallbackAxisSideDirection = "none",
420
- flipAlignment = true,
421
- ...detectOverflowOptions
422
- } = evaluate(options, state);
423
- if ((_middlewareData$arrow = middlewareData.arrow) != null && _middlewareData$arrow.alignmentOffset) {
424
- return {};
425
- }
426
- const side = getSide(placement);
427
- const initialSideAxis = getSideAxis(initialPlacement);
428
- const isBasePlacement = getSide(initialPlacement) === initialPlacement;
429
- const rtl = await (platform2.isRTL == null ? void 0 : platform2.isRTL(elements.floating));
430
- const fallbackPlacements = specifiedFallbackPlacements || (isBasePlacement || !flipAlignment ? [getOppositePlacement(initialPlacement)] : getExpandedPlacements(initialPlacement));
431
- const hasFallbackAxisSideDirection = fallbackAxisSideDirection !== "none";
432
- if (!specifiedFallbackPlacements && hasFallbackAxisSideDirection) {
433
- fallbackPlacements.push(...getOppositeAxisPlacements(initialPlacement, flipAlignment, fallbackAxisSideDirection, rtl));
434
- }
435
- const placements = [initialPlacement, ...fallbackPlacements];
436
- const overflow = await detectOverflow(state, detectOverflowOptions);
437
- const overflows = [];
438
- let overflowsData = ((_middlewareData$flip = middlewareData.flip) == null ? void 0 : _middlewareData$flip.overflows) || [];
439
- if (checkMainAxis) {
440
- overflows.push(overflow[side]);
441
- }
442
- if (checkCrossAxis) {
443
- const sides = getAlignmentSides(placement, rects, rtl);
444
- overflows.push(overflow[sides[0]], overflow[sides[1]]);
445
- }
446
- overflowsData = [...overflowsData, {
447
- placement,
448
- overflows
449
- }];
450
- if (!overflows.every((side2) => side2 <= 0)) {
451
- var _middlewareData$flip2, _overflowsData$filter;
452
- const nextIndex = (((_middlewareData$flip2 = middlewareData.flip) == null ? void 0 : _middlewareData$flip2.index) || 0) + 1;
453
- const nextPlacement = placements[nextIndex];
454
- if (nextPlacement) {
455
- const ignoreCrossAxisOverflow = checkCrossAxis === "alignment" ? initialSideAxis !== getSideAxis(nextPlacement) : false;
456
- if (!ignoreCrossAxisOverflow || // We leave the current main axis only if every placement on that axis
457
- // overflows the main axis.
458
- overflowsData.every((d) => getSideAxis(d.placement) === initialSideAxis ? d.overflows[0] > 0 : true)) {
459
- return {
460
- data: {
461
- index: nextIndex,
462
- overflows: overflowsData
463
- },
464
- reset: {
465
- placement: nextPlacement
466
- }
467
- };
468
- }
469
- }
470
- let resetPlacement = (_overflowsData$filter = overflowsData.filter((d) => d.overflows[0] <= 0).sort((a, b) => a.overflows[1] - b.overflows[1])[0]) == null ? void 0 : _overflowsData$filter.placement;
471
- if (!resetPlacement) {
472
- switch (fallbackStrategy) {
473
- case "bestFit": {
474
- var _overflowsData$filter2;
475
- const placement2 = (_overflowsData$filter2 = overflowsData.filter((d) => {
476
- if (hasFallbackAxisSideDirection) {
477
- const currentSideAxis = getSideAxis(d.placement);
478
- return currentSideAxis === initialSideAxis || // Create a bias to the `y` side axis due to horizontal
479
- // reading directions favoring greater width.
480
- currentSideAxis === "y";
481
- }
482
- return true;
483
- }).map((d) => [d.placement, d.overflows.filter((overflow2) => overflow2 > 0).reduce((acc, overflow2) => acc + overflow2, 0)]).sort((a, b) => a[1] - b[1])[0]) == null ? void 0 : _overflowsData$filter2[0];
484
- if (placement2) {
485
- resetPlacement = placement2;
486
- }
487
- break;
488
- }
489
- case "initialPlacement":
490
- resetPlacement = initialPlacement;
491
- break;
492
- }
493
- }
494
- if (placement !== resetPlacement) {
495
- return {
496
- reset: {
497
- placement: resetPlacement
498
- }
499
- };
500
- }
501
- }
502
- return {};
503
- }
504
- };
505
- };
506
- const shift$1 = function(options) {
507
- if (options === void 0) {
508
- options = {};
509
- }
510
- return {
511
- name: "shift",
512
- options,
513
- async fn(state) {
514
- const {
515
- x,
516
- y,
517
- placement
518
- } = state;
519
- const {
520
- mainAxis: checkMainAxis = true,
521
- crossAxis: checkCrossAxis = false,
522
- limiter = {
523
- fn: (_ref) => {
524
- let {
525
- x: x2,
526
- y: y2
527
- } = _ref;
528
- return {
529
- x: x2,
530
- y: y2
531
- };
532
- }
533
- },
534
- ...detectOverflowOptions
535
- } = evaluate(options, state);
536
- const coords = {
537
- x,
538
- y
539
- };
540
- const overflow = await detectOverflow(state, detectOverflowOptions);
541
- const crossAxis = getSideAxis(getSide(placement));
542
- const mainAxis = getOppositeAxis(crossAxis);
543
- let mainAxisCoord = coords[mainAxis];
544
- let crossAxisCoord = coords[crossAxis];
545
- if (checkMainAxis) {
546
- const minSide = mainAxis === "y" ? "top" : "left";
547
- const maxSide = mainAxis === "y" ? "bottom" : "right";
548
- const min2 = mainAxisCoord + overflow[minSide];
549
- const max2 = mainAxisCoord - overflow[maxSide];
550
- mainAxisCoord = clamp(min2, mainAxisCoord, max2);
551
- }
552
- if (checkCrossAxis) {
553
- const minSide = crossAxis === "y" ? "top" : "left";
554
- const maxSide = crossAxis === "y" ? "bottom" : "right";
555
- const min2 = crossAxisCoord + overflow[minSide];
556
- const max2 = crossAxisCoord - overflow[maxSide];
557
- crossAxisCoord = clamp(min2, crossAxisCoord, max2);
558
- }
559
- const limitedCoords = limiter.fn({
560
- ...state,
561
- [mainAxis]: mainAxisCoord,
562
- [crossAxis]: crossAxisCoord
563
- });
564
- return {
565
- ...limitedCoords,
566
- data: {
567
- x: limitedCoords.x - x,
568
- y: limitedCoords.y - y,
569
- enabled: {
570
- [mainAxis]: checkMainAxis,
571
- [crossAxis]: checkCrossAxis
572
- }
573
- }
574
- };
575
- }
576
- };
577
- };
578
- function hasWindow() {
579
- return typeof window !== "undefined";
580
- }
581
- function getNodeName(node) {
582
- if (isNode(node)) {
583
- return (node.nodeName || "").toLowerCase();
584
- }
585
- return "#document";
586
- }
587
- function getWindow(node) {
588
- var _node$ownerDocument;
589
- return (node == null || (_node$ownerDocument = node.ownerDocument) == null ? void 0 : _node$ownerDocument.defaultView) || window;
590
- }
591
- function getDocumentElement(node) {
592
- var _ref;
593
- return (_ref = (isNode(node) ? node.ownerDocument : node.document) || window.document) == null ? void 0 : _ref.documentElement;
594
- }
595
- function isNode(value) {
596
- if (!hasWindow()) {
597
- return false;
598
- }
599
- return value instanceof Node || value instanceof getWindow(value).Node;
600
- }
601
- function isElement(value) {
602
- if (!hasWindow()) {
603
- return false;
604
- }
605
- return value instanceof Element || value instanceof getWindow(value).Element;
606
- }
607
- function isHTMLElement(value) {
608
- if (!hasWindow()) {
609
- return false;
610
- }
611
- return value instanceof HTMLElement || value instanceof getWindow(value).HTMLElement;
612
- }
613
- function isShadowRoot(value) {
614
- if (!hasWindow() || typeof ShadowRoot === "undefined") {
615
- return false;
616
- }
617
- return value instanceof ShadowRoot || value instanceof getWindow(value).ShadowRoot;
618
- }
619
- const invalidOverflowDisplayValues = /* @__PURE__ */ new Set(["inline", "contents"]);
620
- function isOverflowElement(element) {
621
- const {
622
- overflow,
623
- overflowX,
624
- overflowY,
625
- display
626
- } = getComputedStyle$1(element);
627
- return /auto|scroll|overlay|hidden|clip/.test(overflow + overflowY + overflowX) && !invalidOverflowDisplayValues.has(display);
628
- }
629
- const tableElements = /* @__PURE__ */ new Set(["table", "td", "th"]);
630
- function isTableElement(element) {
631
- return tableElements.has(getNodeName(element));
632
- }
633
- const topLayerSelectors = [":popover-open", ":modal"];
634
- function isTopLayer(element) {
635
- return topLayerSelectors.some((selector) => {
636
- try {
637
- return element.matches(selector);
638
- } catch (_e) {
639
- return false;
640
- }
641
- });
642
- }
643
- const transformProperties = ["transform", "translate", "scale", "rotate", "perspective"];
644
- const willChangeValues = ["transform", "translate", "scale", "rotate", "perspective", "filter"];
645
- const containValues = ["paint", "layout", "strict", "content"];
646
- function isContainingBlock(elementOrCss) {
647
- const webkit = isWebKit();
648
- const css = isElement(elementOrCss) ? getComputedStyle$1(elementOrCss) : elementOrCss;
649
- return transformProperties.some((value) => css[value] ? css[value] !== "none" : false) || (css.containerType ? css.containerType !== "normal" : false) || !webkit && (css.backdropFilter ? css.backdropFilter !== "none" : false) || !webkit && (css.filter ? css.filter !== "none" : false) || willChangeValues.some((value) => (css.willChange || "").includes(value)) || containValues.some((value) => (css.contain || "").includes(value));
650
- }
651
- function getContainingBlock(element) {
652
- let currentNode = getParentNode(element);
653
- while (isHTMLElement(currentNode) && !isLastTraversableNode(currentNode)) {
654
- if (isContainingBlock(currentNode)) {
655
- return currentNode;
656
- } else if (isTopLayer(currentNode)) {
657
- return null;
658
- }
659
- currentNode = getParentNode(currentNode);
660
- }
661
- return null;
662
- }
663
- function isWebKit() {
664
- if (typeof CSS === "undefined" || !CSS.supports) return false;
665
- return CSS.supports("-webkit-backdrop-filter", "none");
666
- }
667
- const lastTraversableNodeNames = /* @__PURE__ */ new Set(["html", "body", "#document"]);
668
- function isLastTraversableNode(node) {
669
- return lastTraversableNodeNames.has(getNodeName(node));
670
- }
671
- function getComputedStyle$1(element) {
672
- return getWindow(element).getComputedStyle(element);
673
- }
674
- function getNodeScroll(element) {
675
- if (isElement(element)) {
676
- return {
677
- scrollLeft: element.scrollLeft,
678
- scrollTop: element.scrollTop
679
- };
680
- }
681
- return {
682
- scrollLeft: element.scrollX,
683
- scrollTop: element.scrollY
684
- };
685
- }
686
- function getParentNode(node) {
687
- if (getNodeName(node) === "html") {
688
- return node;
689
- }
690
- const result = (
691
- // Step into the shadow DOM of the parent of a slotted node.
692
- node.assignedSlot || // DOM Element detected.
693
- node.parentNode || // ShadowRoot detected.
694
- isShadowRoot(node) && node.host || // Fallback.
695
- getDocumentElement(node)
696
- );
697
- return isShadowRoot(result) ? result.host : result;
698
- }
699
- function getNearestOverflowAncestor(node) {
700
- const parentNode = getParentNode(node);
701
- if (isLastTraversableNode(parentNode)) {
702
- return node.ownerDocument ? node.ownerDocument.body : node.body;
703
- }
704
- if (isHTMLElement(parentNode) && isOverflowElement(parentNode)) {
705
- return parentNode;
706
- }
707
- return getNearestOverflowAncestor(parentNode);
708
- }
709
- function getOverflowAncestors(node, list, traverseIframes) {
710
- var _node$ownerDocument2;
711
- if (list === void 0) {
712
- list = [];
713
- }
714
- const scrollableAncestor = getNearestOverflowAncestor(node);
715
- const isBody = scrollableAncestor === ((_node$ownerDocument2 = node.ownerDocument) == null ? void 0 : _node$ownerDocument2.body);
716
- const win = getWindow(scrollableAncestor);
717
- if (isBody) {
718
- getFrameElement(win);
719
- return list.concat(win, win.visualViewport || [], isOverflowElement(scrollableAncestor) ? scrollableAncestor : [], []);
720
- }
721
- return list.concat(scrollableAncestor, getOverflowAncestors(scrollableAncestor, []));
722
- }
723
- function getFrameElement(win) {
724
- return win.parent && Object.getPrototypeOf(win.parent) ? win.frameElement : null;
725
- }
726
- function getCssDimensions(element) {
727
- const css = getComputedStyle$1(element);
728
- let width = parseFloat(css.width) || 0;
729
- let height = parseFloat(css.height) || 0;
730
- const hasOffset = isHTMLElement(element);
731
- const offsetWidth = hasOffset ? element.offsetWidth : width;
732
- const offsetHeight = hasOffset ? element.offsetHeight : height;
733
- const shouldFallback = round(width) !== offsetWidth || round(height) !== offsetHeight;
734
- if (shouldFallback) {
735
- width = offsetWidth;
736
- height = offsetHeight;
737
- }
738
- return {
739
- width,
740
- height,
741
- $: shouldFallback
742
- };
743
- }
744
- function unwrapElement(element) {
745
- return !isElement(element) ? element.contextElement : element;
746
- }
747
- function getScale(element) {
748
- const domElement = unwrapElement(element);
749
- if (!isHTMLElement(domElement)) {
750
- return createCoords(1);
751
- }
752
- const rect = domElement.getBoundingClientRect();
753
- const {
754
- width,
755
- height,
756
- $
757
- } = getCssDimensions(domElement);
758
- let x = ($ ? round(rect.width) : rect.width) / width;
759
- let y = ($ ? round(rect.height) : rect.height) / height;
760
- if (!x || !Number.isFinite(x)) {
761
- x = 1;
762
- }
763
- if (!y || !Number.isFinite(y)) {
764
- y = 1;
765
- }
766
- return {
767
- x,
768
- y
769
- };
770
- }
771
- const noOffsets = /* @__PURE__ */ createCoords(0);
772
- function getVisualOffsets(element) {
773
- const win = getWindow(element);
774
- if (!isWebKit() || !win.visualViewport) {
775
- return noOffsets;
776
- }
777
- return {
778
- x: win.visualViewport.offsetLeft,
779
- y: win.visualViewport.offsetTop
780
- };
781
- }
782
- function shouldAddVisualOffsets(element, isFixed, floatingOffsetParent) {
783
- if (isFixed === void 0) {
784
- isFixed = false;
785
- }
786
- if (!floatingOffsetParent || isFixed && floatingOffsetParent !== getWindow(element)) {
787
- return false;
788
- }
789
- return isFixed;
790
- }
791
- function getBoundingClientRect(element, includeScale, isFixedStrategy, offsetParent) {
792
- if (includeScale === void 0) {
793
- includeScale = false;
794
- }
795
- if (isFixedStrategy === void 0) {
796
- isFixedStrategy = false;
797
- }
798
- const clientRect = element.getBoundingClientRect();
799
- const domElement = unwrapElement(element);
800
- let scale = createCoords(1);
801
- if (includeScale) {
802
- if (offsetParent) {
803
- if (isElement(offsetParent)) {
804
- scale = getScale(offsetParent);
805
- }
806
- } else {
807
- scale = getScale(element);
808
- }
809
- }
810
- const visualOffsets = shouldAddVisualOffsets(domElement, isFixedStrategy, offsetParent) ? getVisualOffsets(domElement) : createCoords(0);
811
- let x = (clientRect.left + visualOffsets.x) / scale.x;
812
- let y = (clientRect.top + visualOffsets.y) / scale.y;
813
- let width = clientRect.width / scale.x;
814
- let height = clientRect.height / scale.y;
815
- if (domElement) {
816
- const win = getWindow(domElement);
817
- const offsetWin = offsetParent && isElement(offsetParent) ? getWindow(offsetParent) : offsetParent;
818
- let currentWin = win;
819
- let currentIFrame = getFrameElement(currentWin);
820
- while (currentIFrame && offsetParent && offsetWin !== currentWin) {
821
- const iframeScale = getScale(currentIFrame);
822
- const iframeRect = currentIFrame.getBoundingClientRect();
823
- const css = getComputedStyle$1(currentIFrame);
824
- const left = iframeRect.left + (currentIFrame.clientLeft + parseFloat(css.paddingLeft)) * iframeScale.x;
825
- const top = iframeRect.top + (currentIFrame.clientTop + parseFloat(css.paddingTop)) * iframeScale.y;
826
- x *= iframeScale.x;
827
- y *= iframeScale.y;
828
- width *= iframeScale.x;
829
- height *= iframeScale.y;
830
- x += left;
831
- y += top;
832
- currentWin = getWindow(currentIFrame);
833
- currentIFrame = getFrameElement(currentWin);
834
- }
835
- }
836
- return rectToClientRect({
837
- width,
838
- height,
839
- x,
840
- y
841
- });
842
- }
843
- function getWindowScrollBarX(element, rect) {
844
- const leftScroll = getNodeScroll(element).scrollLeft;
845
- if (!rect) {
846
- return getBoundingClientRect(getDocumentElement(element)).left + leftScroll;
847
- }
848
- return rect.left + leftScroll;
849
- }
850
- function getHTMLOffset(documentElement, scroll) {
851
- const htmlRect = documentElement.getBoundingClientRect();
852
- const x = htmlRect.left + scroll.scrollLeft - getWindowScrollBarX(documentElement, htmlRect);
853
- const y = htmlRect.top + scroll.scrollTop;
854
- return {
855
- x,
856
- y
857
- };
858
- }
859
- function convertOffsetParentRelativeRectToViewportRelativeRect(_ref) {
860
- let {
861
- elements,
862
- rect,
863
- offsetParent,
864
- strategy
865
- } = _ref;
866
- const isFixed = strategy === "fixed";
867
- const documentElement = getDocumentElement(offsetParent);
868
- const topLayer = elements ? isTopLayer(elements.floating) : false;
869
- if (offsetParent === documentElement || topLayer && isFixed) {
870
- return rect;
871
- }
872
- let scroll = {
873
- scrollLeft: 0,
874
- scrollTop: 0
875
- };
876
- let scale = createCoords(1);
877
- const offsets = createCoords(0);
878
- const isOffsetParentAnElement = isHTMLElement(offsetParent);
879
- if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
880
- if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
881
- scroll = getNodeScroll(offsetParent);
882
- }
883
- if (isHTMLElement(offsetParent)) {
884
- const offsetRect = getBoundingClientRect(offsetParent);
885
- scale = getScale(offsetParent);
886
- offsets.x = offsetRect.x + offsetParent.clientLeft;
887
- offsets.y = offsetRect.y + offsetParent.clientTop;
888
- }
889
- }
890
- const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
891
- return {
892
- width: rect.width * scale.x,
893
- height: rect.height * scale.y,
894
- x: rect.x * scale.x - scroll.scrollLeft * scale.x + offsets.x + htmlOffset.x,
895
- y: rect.y * scale.y - scroll.scrollTop * scale.y + offsets.y + htmlOffset.y
896
- };
897
- }
898
- function getClientRects(element) {
899
- return Array.from(element.getClientRects());
900
- }
901
- function getDocumentRect(element) {
902
- const html = getDocumentElement(element);
903
- const scroll = getNodeScroll(element);
904
- const body = element.ownerDocument.body;
905
- const width = max(html.scrollWidth, html.clientWidth, body.scrollWidth, body.clientWidth);
906
- const height = max(html.scrollHeight, html.clientHeight, body.scrollHeight, body.clientHeight);
907
- let x = -scroll.scrollLeft + getWindowScrollBarX(element);
908
- const y = -scroll.scrollTop;
909
- if (getComputedStyle$1(body).direction === "rtl") {
910
- x += max(html.clientWidth, body.clientWidth) - width;
911
- }
912
- return {
913
- width,
914
- height,
915
- x,
916
- y
917
- };
918
- }
919
- const SCROLLBAR_MAX = 25;
920
- function getViewportRect(element, strategy) {
921
- const win = getWindow(element);
922
- const html = getDocumentElement(element);
923
- const visualViewport = win.visualViewport;
924
- let width = html.clientWidth;
925
- let height = html.clientHeight;
926
- let x = 0;
927
- let y = 0;
928
- if (visualViewport) {
929
- width = visualViewport.width;
930
- height = visualViewport.height;
931
- const visualViewportBased = isWebKit();
932
- if (!visualViewportBased || visualViewportBased && strategy === "fixed") {
933
- x = visualViewport.offsetLeft;
934
- y = visualViewport.offsetTop;
935
- }
936
- }
937
- const windowScrollbarX = getWindowScrollBarX(html);
938
- if (windowScrollbarX <= 0) {
939
- const doc = html.ownerDocument;
940
- const body = doc.body;
941
- const bodyStyles = getComputedStyle(body);
942
- const bodyMarginInline = doc.compatMode === "CSS1Compat" ? parseFloat(bodyStyles.marginLeft) + parseFloat(bodyStyles.marginRight) || 0 : 0;
943
- const clippingStableScrollbarWidth = Math.abs(html.clientWidth - body.clientWidth - bodyMarginInline);
944
- if (clippingStableScrollbarWidth <= SCROLLBAR_MAX) {
945
- width -= clippingStableScrollbarWidth;
946
- }
947
- } else if (windowScrollbarX <= SCROLLBAR_MAX) {
948
- width += windowScrollbarX;
949
- }
950
- return {
951
- width,
952
- height,
953
- x,
954
- y
955
- };
956
- }
957
- const absoluteOrFixed = /* @__PURE__ */ new Set(["absolute", "fixed"]);
958
- function getInnerBoundingClientRect(element, strategy) {
959
- const clientRect = getBoundingClientRect(element, true, strategy === "fixed");
960
- const top = clientRect.top + element.clientTop;
961
- const left = clientRect.left + element.clientLeft;
962
- const scale = isHTMLElement(element) ? getScale(element) : createCoords(1);
963
- const width = element.clientWidth * scale.x;
964
- const height = element.clientHeight * scale.y;
965
- const x = left * scale.x;
966
- const y = top * scale.y;
967
- return {
968
- width,
969
- height,
970
- x,
971
- y
972
- };
973
- }
974
- function getClientRectFromClippingAncestor(element, clippingAncestor, strategy) {
975
- let rect;
976
- if (clippingAncestor === "viewport") {
977
- rect = getViewportRect(element, strategy);
978
- } else if (clippingAncestor === "document") {
979
- rect = getDocumentRect(getDocumentElement(element));
980
- } else if (isElement(clippingAncestor)) {
981
- rect = getInnerBoundingClientRect(clippingAncestor, strategy);
982
- } else {
983
- const visualOffsets = getVisualOffsets(element);
984
- rect = {
985
- x: clippingAncestor.x - visualOffsets.x,
986
- y: clippingAncestor.y - visualOffsets.y,
987
- width: clippingAncestor.width,
988
- height: clippingAncestor.height
989
- };
990
- }
991
- return rectToClientRect(rect);
992
- }
993
- function hasFixedPositionAncestor(element, stopNode) {
994
- const parentNode = getParentNode(element);
995
- if (parentNode === stopNode || !isElement(parentNode) || isLastTraversableNode(parentNode)) {
996
- return false;
997
- }
998
- return getComputedStyle$1(parentNode).position === "fixed" || hasFixedPositionAncestor(parentNode, stopNode);
999
- }
1000
- function getClippingElementAncestors(element, cache) {
1001
- const cachedResult = cache.get(element);
1002
- if (cachedResult) {
1003
- return cachedResult;
1004
- }
1005
- let result = getOverflowAncestors(element, []).filter((el) => isElement(el) && getNodeName(el) !== "body");
1006
- let currentContainingBlockComputedStyle = null;
1007
- const elementIsFixed = getComputedStyle$1(element).position === "fixed";
1008
- let currentNode = elementIsFixed ? getParentNode(element) : element;
1009
- while (isElement(currentNode) && !isLastTraversableNode(currentNode)) {
1010
- const computedStyle = getComputedStyle$1(currentNode);
1011
- const currentNodeIsContaining = isContainingBlock(currentNode);
1012
- if (!currentNodeIsContaining && computedStyle.position === "fixed") {
1013
- currentContainingBlockComputedStyle = null;
1014
- }
1015
- const shouldDropCurrentNode = elementIsFixed ? !currentNodeIsContaining && !currentContainingBlockComputedStyle : !currentNodeIsContaining && computedStyle.position === "static" && !!currentContainingBlockComputedStyle && absoluteOrFixed.has(currentContainingBlockComputedStyle.position) || isOverflowElement(currentNode) && !currentNodeIsContaining && hasFixedPositionAncestor(element, currentNode);
1016
- if (shouldDropCurrentNode) {
1017
- result = result.filter((ancestor) => ancestor !== currentNode);
1018
- } else {
1019
- currentContainingBlockComputedStyle = computedStyle;
1020
- }
1021
- currentNode = getParentNode(currentNode);
1022
- }
1023
- cache.set(element, result);
1024
- return result;
1025
- }
1026
- function getClippingRect(_ref) {
1027
- let {
1028
- element,
1029
- boundary,
1030
- rootBoundary,
1031
- strategy
1032
- } = _ref;
1033
- const elementClippingAncestors = boundary === "clippingAncestors" ? isTopLayer(element) ? [] : getClippingElementAncestors(element, this._c) : [].concat(boundary);
1034
- const clippingAncestors = [...elementClippingAncestors, rootBoundary];
1035
- const firstClippingAncestor = clippingAncestors[0];
1036
- const clippingRect = clippingAncestors.reduce((accRect, clippingAncestor) => {
1037
- const rect = getClientRectFromClippingAncestor(element, clippingAncestor, strategy);
1038
- accRect.top = max(rect.top, accRect.top);
1039
- accRect.right = min(rect.right, accRect.right);
1040
- accRect.bottom = min(rect.bottom, accRect.bottom);
1041
- accRect.left = max(rect.left, accRect.left);
1042
- return accRect;
1043
- }, getClientRectFromClippingAncestor(element, firstClippingAncestor, strategy));
1044
- return {
1045
- width: clippingRect.right - clippingRect.left,
1046
- height: clippingRect.bottom - clippingRect.top,
1047
- x: clippingRect.left,
1048
- y: clippingRect.top
1049
- };
1050
- }
1051
- function getDimensions(element) {
1052
- const {
1053
- width,
1054
- height
1055
- } = getCssDimensions(element);
1056
- return {
1057
- width,
1058
- height
1059
- };
1060
- }
1061
- function getRectRelativeToOffsetParent(element, offsetParent, strategy) {
1062
- const isOffsetParentAnElement = isHTMLElement(offsetParent);
1063
- const documentElement = getDocumentElement(offsetParent);
1064
- const isFixed = strategy === "fixed";
1065
- const rect = getBoundingClientRect(element, true, isFixed, offsetParent);
1066
- let scroll = {
1067
- scrollLeft: 0,
1068
- scrollTop: 0
1069
- };
1070
- const offsets = createCoords(0);
1071
- function setLeftRTLScrollbarOffset() {
1072
- offsets.x = getWindowScrollBarX(documentElement);
1073
- }
1074
- if (isOffsetParentAnElement || !isOffsetParentAnElement && !isFixed) {
1075
- if (getNodeName(offsetParent) !== "body" || isOverflowElement(documentElement)) {
1076
- scroll = getNodeScroll(offsetParent);
1077
- }
1078
- if (isOffsetParentAnElement) {
1079
- const offsetRect = getBoundingClientRect(offsetParent, true, isFixed, offsetParent);
1080
- offsets.x = offsetRect.x + offsetParent.clientLeft;
1081
- offsets.y = offsetRect.y + offsetParent.clientTop;
1082
- } else if (documentElement) {
1083
- setLeftRTLScrollbarOffset();
1084
- }
1085
- }
1086
- if (isFixed && !isOffsetParentAnElement && documentElement) {
1087
- setLeftRTLScrollbarOffset();
1088
- }
1089
- const htmlOffset = documentElement && !isOffsetParentAnElement && !isFixed ? getHTMLOffset(documentElement, scroll) : createCoords(0);
1090
- const x = rect.left + scroll.scrollLeft - offsets.x - htmlOffset.x;
1091
- const y = rect.top + scroll.scrollTop - offsets.y - htmlOffset.y;
1092
- return {
1093
- x,
1094
- y,
1095
- width: rect.width,
1096
- height: rect.height
1097
- };
1098
- }
1099
- function isStaticPositioned(element) {
1100
- return getComputedStyle$1(element).position === "static";
1101
- }
1102
- function getTrueOffsetParent(element, polyfill) {
1103
- if (!isHTMLElement(element) || getComputedStyle$1(element).position === "fixed") {
1104
- return null;
1105
- }
1106
- if (polyfill) {
1107
- return polyfill(element);
1108
- }
1109
- let rawOffsetParent = element.offsetParent;
1110
- if (getDocumentElement(element) === rawOffsetParent) {
1111
- rawOffsetParent = rawOffsetParent.ownerDocument.body;
1112
- }
1113
- return rawOffsetParent;
1114
- }
1115
- function getOffsetParent(element, polyfill) {
1116
- const win = getWindow(element);
1117
- if (isTopLayer(element)) {
1118
- return win;
1119
- }
1120
- if (!isHTMLElement(element)) {
1121
- let svgOffsetParent = getParentNode(element);
1122
- while (svgOffsetParent && !isLastTraversableNode(svgOffsetParent)) {
1123
- if (isElement(svgOffsetParent) && !isStaticPositioned(svgOffsetParent)) {
1124
- return svgOffsetParent;
1125
- }
1126
- svgOffsetParent = getParentNode(svgOffsetParent);
1127
- }
1128
- return win;
1129
- }
1130
- let offsetParent = getTrueOffsetParent(element, polyfill);
1131
- while (offsetParent && isTableElement(offsetParent) && isStaticPositioned(offsetParent)) {
1132
- offsetParent = getTrueOffsetParent(offsetParent, polyfill);
1133
- }
1134
- if (offsetParent && isLastTraversableNode(offsetParent) && isStaticPositioned(offsetParent) && !isContainingBlock(offsetParent)) {
1135
- return win;
1136
- }
1137
- return offsetParent || getContainingBlock(element) || win;
1138
- }
1139
- const getElementRects = async function(data) {
1140
- const getOffsetParentFn = this.getOffsetParent || getOffsetParent;
1141
- const getDimensionsFn = this.getDimensions;
1142
- const floatingDimensions = await getDimensionsFn(data.floating);
1143
- return {
1144
- reference: getRectRelativeToOffsetParent(data.reference, await getOffsetParentFn(data.floating), data.strategy),
1145
- floating: {
1146
- x: 0,
1147
- y: 0,
1148
- width: floatingDimensions.width,
1149
- height: floatingDimensions.height
1150
- }
1151
- };
1152
- };
1153
- function isRTL(element) {
1154
- return getComputedStyle$1(element).direction === "rtl";
1155
- }
1156
- const platform = {
1157
- convertOffsetParentRelativeRectToViewportRelativeRect,
1158
- getDocumentElement,
1159
- getClippingRect,
1160
- getOffsetParent,
1161
- getElementRects,
1162
- getClientRects,
1163
- getDimensions,
1164
- getScale,
1165
- isElement,
1166
- isRTL
1167
- };
1168
- const shift = shift$1;
1169
- const flip = flip$1;
1170
- const computePosition = (reference, floating, options) => {
1171
- const cache = /* @__PURE__ */ new Map();
1172
- const mergedOptions = {
1173
- platform,
1174
- ...options
1175
- };
1176
- const platformWithCache = {
1177
- ...mergedOptions.platform,
1178
- _c: cache
1179
- };
1180
- return computePosition$1(reference, floating, {
1181
- ...mergedOptions,
1182
- platform: platformWithCache
1183
- });
1184
- };
1185
77
  const chatTheme = {
1186
78
  base: "dark:text-white text-gray-500",
1187
79
  console: "flex w-full gap-4 h-full",
@@ -1425,6 +317,7 @@ const chatTheme = {
1425
317
  }
1426
318
  }
1427
319
  };
320
+ const POPUP_STYLE = { zIndex: 9999 };
1428
321
  const MentionList = forwardRef(
1429
322
  ({ items, command, triggerChar, config, query }, ref) => {
1430
323
  var _a;
@@ -1483,7 +376,7 @@ const MentionList = forwardRef(
1483
376
  List,
1484
377
  {
1485
378
  className: cn(popupTheme.base, popupTheme.content),
1486
- style: { zIndex: 9999 },
379
+ style: POPUP_STYLE,
1487
380
  role: "listbox",
1488
381
  id: popupId,
1489
382
  "aria-label": `${triggerChar === "@" ? "Mentions" : "Commands"} suggestions`,
@@ -1514,29 +407,28 @@ const MentionList = forwardRef(
1514
407
  );
1515
408
  }
1516
409
  );
1517
- function DefaultItemRenderer({
1518
- item,
1519
- isHighlighted,
1520
- popupTheme
1521
- }) {
1522
- const shortcut = "shortcut" in item ? item.shortcut : void 0;
1523
- return /* @__PURE__ */ jsx(
1524
- ListItem,
1525
- {
1526
- className: cn(
1527
- popupTheme.item,
1528
- isHighlighted && popupTheme.itemHighlighted
1529
- ),
1530
- dense: true,
1531
- start: item.icon ? /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemIcon), children: item.icon }) : void 0,
1532
- end: shortcut ? /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemShortcut), children: shortcut }) : void 0,
1533
- children: /* @__PURE__ */ jsxs("div", { className: cn(popupTheme.itemContent), children: [
1534
- /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemLabel), children: item.label }),
1535
- item.description && /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemDescription), children: item.description })
1536
- ] })
1537
- }
1538
- );
1539
- }
410
+ const DefaultItemRenderer = memo(
411
+ ({ item, isHighlighted, popupTheme }) => {
412
+ const shortcut = "shortcut" in item ? item.shortcut : void 0;
413
+ return /* @__PURE__ */ jsx(
414
+ ListItem,
415
+ {
416
+ className: cn(
417
+ popupTheme.item,
418
+ isHighlighted && popupTheme.itemHighlighted
419
+ ),
420
+ dense: true,
421
+ start: item.icon ? /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemIcon), children: item.icon }) : void 0,
422
+ end: shortcut ? /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemShortcut), children: shortcut }) : void 0,
423
+ children: /* @__PURE__ */ jsxs("div", { className: cn(popupTheme.itemContent), children: [
424
+ /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemLabel), children: item.label }),
425
+ item.description && /* @__PURE__ */ jsx("span", { className: cn(popupTheme.itemDescription), children: item.description })
426
+ ] })
427
+ }
428
+ );
429
+ }
430
+ );
431
+ DefaultItemRenderer.displayName = "DefaultItemRenderer";
1540
432
  MentionList.displayName = "MentionList";
1541
433
  function updatePopupPosition(editor, element) {
1542
434
  const virtualElement = {
@@ -1846,8 +738,14 @@ const ChatInput = forwardRef(
1846
738
  },
1847
739
  [fileUpload]
1848
740
  );
1849
- const mentionsConfig = mentions ? { ...mentions, trigger: mentions.trigger || "@" } : void 0;
1850
- const commandsConfig = commands ? { ...commands, trigger: commands.trigger || "/" } : void 0;
741
+ const mentionsConfig = useMemo(
742
+ () => mentions ? { ...mentions, trigger: mentions.trigger || "@" } : void 0,
743
+ [mentions]
744
+ );
745
+ const commandsConfig = useMemo(
746
+ () => commands ? { ...commands, trigger: commands.trigger || "/" } : void 0,
747
+ [commands]
748
+ );
1851
749
  return /* @__PURE__ */ jsx("div", { ref: containerRef, className: cn(theme.input.base), children: /* @__PURE__ */ jsxs("div", { className: cn("relative flex-1", theme.input.input), children: [
1852
750
  /* @__PURE__ */ jsx(
1853
751
  RichTextInput,
@@ -3017,7 +1915,7 @@ const TableDataCell = ({ children, ...props }) => /* @__PURE__ */ jsx("td", { ..
3017
1915
  const Markdown = ({
3018
1916
  children,
3019
1917
  remarkPlugins,
3020
- rehypePlugins = [rehypeKatex],
1918
+ rehypePlugins = [rehypeRaw, rehypeKatex],
3021
1919
  customComponents
3022
1920
  }) => {
3023
1921
  const { theme, markdownComponents } = useContext(ChatContext);
@@ -3059,7 +1957,15 @@ const Markdown = ({
3059
1957
  p: (props) => /* @__PURE__ */ jsx("p", { ...props, className: cn(theme.messages.message.markdown.p) }),
3060
1958
  li: (props) => /* @__PURE__ */ jsx("li", { ...props, className: cn(theme.messages.message.markdown.li) }),
3061
1959
  ul: (props) => /* @__PURE__ */ jsx("ul", { ...props, className: cn(theme.messages.message.markdown.ul) }),
3062
- ol: (props) => /* @__PURE__ */ jsx("ol", { ...props, className: cn(theme.messages.message.markdown.ol) })
1960
+ ol: (props) => /* @__PURE__ */ jsx("ol", { ...props, className: cn(theme.messages.message.markdown.ol) }),
1961
+ redact: (props) => /* @__PURE__ */ jsx(
1962
+ Redact,
1963
+ {
1964
+ value: props["data-redact-value"] || props.children,
1965
+ allowToggle: true,
1966
+ tooltipText: `${props["data-redact-name"] || "Sensitive"} information - Click to toggle`
1967
+ }
1968
+ )
3063
1969
  };
3064
1970
  return {
3065
1971
  ...defaultComponents,
@@ -3324,9 +2230,62 @@ const remarkChart = (options = {}) => {
3324
2230
  });
3325
2231
  };
3326
2232
  };
2233
+ function remarkRedact(matchers) {
2234
+ return () => (tree) => {
2235
+ if (!tree || !matchers || matchers.length === 0) {
2236
+ return;
2237
+ }
2238
+ const patterns = [];
2239
+ for (const { name, pattern, validate } of matchers) {
2240
+ patterns.push([
2241
+ pattern,
2242
+ (value) => {
2243
+ if (validate && !validate(value)) {
2244
+ return false;
2245
+ }
2246
+ return {
2247
+ type: "html",
2248
+ value: `<redact data-redact-name="${name}" data-redact-value="${value.replace(/"/g, "&quot;")}">${value}</redact>`
2249
+ };
2250
+ }
2251
+ ]);
2252
+ }
2253
+ if (patterns.length > 0) {
2254
+ try {
2255
+ findAndReplace(tree, patterns);
2256
+ } catch (err) {
2257
+ console.warn("Redact plugin error:", err);
2258
+ }
2259
+ }
2260
+ };
2261
+ }
2262
+ const ssnMatcher = {
2263
+ name: "SSN",
2264
+ pattern: /\b\d{3}-\d{2}-\d{4}\b/g
2265
+ };
2266
+ const creditCardMatcher = {
2267
+ name: "Credit Card",
2268
+ pattern: /\b(?:\d[ -]*?){13,19}\b/g,
2269
+ validate: (match) => {
2270
+ if (/(?:years?|year|yr|yrs|old|age|phone|tel|call)/.test(match)) {
2271
+ return false;
2272
+ }
2273
+ const cardNumber = match.replace(/[ -]/g, "");
2274
+ return cardNumber.length >= 13 && cardNumber.length <= 19;
2275
+ }
2276
+ };
2277
+ const bitcoinMatcher = {
2278
+ name: "Bitcoin",
2279
+ pattern: /\b[13][a-km-zA-HJ-NP-Z1-9]{25,34}\b/g
2280
+ };
2281
+ const commonRedactMatchers = [
2282
+ ssnMatcher,
2283
+ creditCardMatcher,
2284
+ bitcoinMatcher
2285
+ ];
3327
2286
  const SvgFile = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: 16, height: 16, viewBox: "0 0 16 16", fill: "currentColor", ...props }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", clipRule: "evenodd", d: "M2.7036 1.37034C3.04741 1.02653 3.51373 0.833374 3.99996 0.833374H9.33329H9.33331C9.47275 0.833374 9.59885 0.890449 9.68954 0.98251L13.6843 4.97722C13.7763 5.0679 13.8333 5.19398 13.8333 5.33337L13.8333 5.3379V13.3334C13.8333 13.8196 13.6401 14.2859 13.2963 14.6297C12.9525 14.9736 12.4862 15.1667 12 15.1667H3.99996C3.51373 15.1667 3.04741 14.9736 2.7036 14.6297C2.35978 14.2859 2.16663 13.8196 2.16663 13.3334V2.66671C2.16663 2.18048 2.35978 1.71416 2.7036 1.37034ZM3.99996 1.83337H8.83331V5.33337C8.83331 5.60952 9.05717 5.83337 9.33331 5.83337H12.8333V13.3334C12.8333 13.5544 12.7455 13.7663 12.5892 13.9226C12.4329 14.0789 12.221 14.1667 12 14.1667H3.99996C3.77895 14.1667 3.56698 14.0789 3.4107 13.9226C3.25442 13.7663 3.16663 13.5544 3.16663 13.3334V2.66671C3.16663 2.44569 3.25442 2.23373 3.4107 2.07745C3.56698 1.92117 3.77895 1.83337 3.99996 1.83337ZM9.83331 2.5405L12.1262 4.83337H9.83331V2.5405ZM5.33331 8.16663C5.05717 8.16663 4.83331 8.39048 4.83331 8.66663C4.83331 8.94277 5.05717 9.16663 5.33331 9.16663H10.6666C10.9428 9.16663 11.1666 8.94277 11.1666 8.66663C11.1666 8.39048 10.9428 8.16663 10.6666 8.16663H5.33331ZM4.83331 11.3334C4.83331 11.0572 5.05717 10.8334 5.33331 10.8334H10.6666C10.9428 10.8334 11.1666 11.0572 11.1666 11.3334C11.1666 11.6095 10.9428 11.8334 10.6666 11.8334H5.33331C5.05717 11.8334 4.83331 11.6095 4.83331 11.3334ZM5.33331 5.5C5.05717 5.5 4.83331 5.72386 4.83331 6C4.83331 6.27614 5.05717 6.5 5.33331 6.5H6.66665C6.94279 6.5 7.16665 6.27614 7.16665 6C7.16665 5.72386 6.94279 5.5 6.66665 5.5H5.33331Z" }));
3328
- const DefaultFileRenderer = lazy(() => import("./DefaultFileRenderer-Bi8LNDio.js"));
3329
- const CSVFileRenderer = lazy(() => import("./CSVFileRenderer-DXI8PDqR.js"));
2287
+ const DefaultFileRenderer = lazy(() => import("./DefaultFileRenderer-C2MsQ9wz.js"));
2288
+ const CSVFileRenderer = lazy(() => import("./CSVFileRenderer-BOdL4Jte.js"));
3330
2289
  const ImageFileRenderer = lazy(() => import("./ImageFileRenderer-C8tVW3I8.js"));
3331
2290
  const PDFFileRenderer = lazy(() => import("./PDFFileRenderer-DQdFS2l6.js"));
3332
2291
  const FILE_TYPE_RENDERER_MAP = {
@@ -3354,27 +2313,36 @@ const MessageFile = ({
3354
2313
  }
3355
2314
  );
3356
2315
  };
3357
- const MessageFiles = ({ files, children }) => {
2316
+ const MessageFiles = memo(({ files, children }) => {
3358
2317
  const { theme } = useContext(ChatContext);
3359
2318
  const Comp = children ? Slot : MessageFile;
3360
2319
  const [expanded, setExpanded] = useState(false);
2320
+ const { imageFiles, otherFiles } = useMemo(() => {
2321
+ if (!files || files.length === 0) {
2322
+ return {
2323
+ imageFiles: [],
2324
+ otherFiles: []
2325
+ };
2326
+ }
2327
+ return files.reduce(
2328
+ (acc, file) => {
2329
+ var _a;
2330
+ if ((_a = file.type) == null ? void 0 : _a.startsWith("image/")) {
2331
+ acc.imageFiles.push(file);
2332
+ } else {
2333
+ acc.otherFiles.push(file);
2334
+ }
2335
+ return acc;
2336
+ },
2337
+ {
2338
+ imageFiles: [],
2339
+ otherFiles: []
2340
+ }
2341
+ );
2342
+ }, [files]);
3361
2343
  if (!files || files.length === 0) {
3362
2344
  return null;
3363
2345
  }
3364
- const { imageFiles, otherFiles } = files.reduce(
3365
- (acc, file) => {
3366
- if (file.type.startsWith("image/")) {
3367
- acc.imageFiles.push(file);
3368
- } else {
3369
- acc.otherFiles.push(file);
3370
- }
3371
- return acc;
3372
- },
3373
- {
3374
- imageFiles: [],
3375
- otherFiles: []
3376
- }
3377
- );
3378
2346
  const maxImageLength = 3;
3379
2347
  const truncateImages = !expanded && imageFiles.length > maxImageLength;
3380
2348
  const renderImageFiles = (images) => {
@@ -3417,73 +2385,73 @@ const MessageFiles = ({ files, children }) => {
3417
2385
  children: [
3418
2386
  imageFiles.length > 0 && renderImageFiles(imageFiles),
3419
2387
  otherFiles.length > 0 && otherFiles.map((file, index) => /* @__PURE__ */ jsx(Comp, { ...file, children }, index))
3420
- ]
3421
- }
3422
- );
3423
- };
3424
- const MessageQuestion = ({
3425
- children,
3426
- ...props
3427
- }) => {
3428
- const { theme, remarkPlugins } = useContext(ChatContext);
3429
- const { question, files } = props;
3430
- const Comp = children ? Slot : "div";
3431
- const [expanded, setExpanded] = useState(false);
3432
- const isLong = question.length > 500;
3433
- return /* @__PURE__ */ jsx(
3434
- Comp,
3435
- {
3436
- className: cn(theme.messages.message.question, {
3437
- [theme.messages.message.overlay]: isLong && !expanded
3438
- }),
3439
- ...props,
3440
- children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
3441
- /* @__PURE__ */ jsx(MessageFiles, { files }),
3442
- /* @__PURE__ */ jsx(Markdown, { remarkPlugins, children: question }),
3443
- isLong && !expanded && /* @__PURE__ */ jsx(
3444
- Button,
3445
- {
3446
- variant: "link",
3447
- size: "small",
3448
- className: theme.messages.message.expand,
3449
- onClick: () => setExpanded(true),
3450
- children: "Show more"
3451
- }
3452
- )
3453
- ] })
3454
- }
3455
- );
3456
- };
3457
- const MessageResponse = ({
3458
- response,
3459
- isLoading,
3460
- children
3461
- }) => {
3462
- const { theme, isCompact, remarkPlugins } = useContext(ChatContext);
3463
- const Comp = children ? Slot : "div";
3464
- return /* @__PURE__ */ jsx(
3465
- Comp,
3466
- {
3467
- "data-compact": isCompact,
3468
- className: cn(theme.messages.message.response),
3469
- children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
3470
- /* @__PURE__ */ jsx(Markdown, { remarkPlugins, children: response }),
3471
- isLoading && /* @__PURE__ */ jsx(
3472
- motion.div,
3473
- {
3474
- className: cn(theme.messages.message.cursor),
3475
- animate: { opacity: [1, 0] },
3476
- transition: {
3477
- duration: 0.7,
3478
- repeat: Infinity,
3479
- repeatType: "reverse"
3480
- }
3481
- }
3482
- )
3483
- ] })
2388
+ ]
3484
2389
  }
3485
2390
  );
3486
- };
2391
+ });
2392
+ MessageFiles.displayName = "MessageFiles";
2393
+ const MessageQuestion = memo(
2394
+ ({ children, ...props }) => {
2395
+ const { theme, remarkPlugins } = useContext(ChatContext);
2396
+ const { question, files } = props;
2397
+ const Comp = children ? Slot : "div";
2398
+ const [expanded, setExpanded] = useState(false);
2399
+ const isLong = question.length > 500;
2400
+ return /* @__PURE__ */ jsx(
2401
+ Comp,
2402
+ {
2403
+ className: cn(theme.messages.message.question, {
2404
+ [theme.messages.message.overlay]: isLong && !expanded
2405
+ }),
2406
+ ...props,
2407
+ children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
2408
+ /* @__PURE__ */ jsx(MessageFiles, { files }),
2409
+ /* @__PURE__ */ jsx(Markdown, { remarkPlugins, children: question }),
2410
+ isLong && !expanded && /* @__PURE__ */ jsx(
2411
+ Button,
2412
+ {
2413
+ variant: "link",
2414
+ size: "small",
2415
+ className: theme.messages.message.expand,
2416
+ onClick: () => setExpanded(true),
2417
+ children: "Show more"
2418
+ }
2419
+ )
2420
+ ] })
2421
+ }
2422
+ );
2423
+ }
2424
+ );
2425
+ MessageQuestion.displayName = "MessageQuestion";
2426
+ const MessageResponse = memo(
2427
+ ({ response, isLoading, children }) => {
2428
+ const { theme, isCompact, remarkPlugins } = useContext(ChatContext);
2429
+ const Comp = children ? Slot : "div";
2430
+ return /* @__PURE__ */ jsx(
2431
+ Comp,
2432
+ {
2433
+ "data-compact": isCompact,
2434
+ className: cn(theme.messages.message.response),
2435
+ children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
2436
+ /* @__PURE__ */ jsx(Markdown, { remarkPlugins, children: response }),
2437
+ isLoading && /* @__PURE__ */ jsx(
2438
+ motion.div,
2439
+ {
2440
+ className: cn(theme.messages.message.cursor),
2441
+ animate: { opacity: [1, 0] },
2442
+ transition: {
2443
+ duration: 0.7,
2444
+ repeat: Infinity,
2445
+ repeatType: "reverse"
2446
+ }
2447
+ }
2448
+ )
2449
+ ] })
2450
+ }
2451
+ );
2452
+ }
2453
+ );
2454
+ MessageResponse.displayName = "MessageResponse";
3487
2455
  const MessageSource = ({ title, url, image, limit = 50 }) => {
3488
2456
  const { theme, isCompact } = useContext(ChatContext);
3489
2457
  return /* @__PURE__ */ jsxs(
@@ -3507,93 +2475,100 @@ const MessageSource = ({ title, url, image, limit = 50 }) => {
3507
2475
  }
3508
2476
  );
3509
2477
  };
3510
- const MessageSources = ({
3511
- sources,
3512
- children
3513
- }) => {
3514
- const { theme } = useContext(ChatContext);
3515
- const Comp = children ? Slot : MessageSource;
3516
- if (!sources || sources.length === 0) {
3517
- return null;
2478
+ const MessageSources = memo(
2479
+ ({ sources, children }) => {
2480
+ const { theme } = useContext(ChatContext);
2481
+ const Comp = children ? Slot : MessageSource;
2482
+ if (!sources || sources.length === 0) {
2483
+ return null;
2484
+ }
2485
+ return /* @__PURE__ */ jsx("div", { className: cn(theme.messages.message.sources.base), children: sources.map((source, index) => /* @__PURE__ */ jsx(Comp, { ...source, children }, index)) });
3518
2486
  }
3519
- return sources && sources.length > 0 && /* @__PURE__ */ jsx("div", { className: cn(theme.messages.message.sources.base), children: sources.map((source, index) => /* @__PURE__ */ jsx(Comp, { ...source, children }, index)) });
3520
- };
2487
+ );
2488
+ MessageSources.displayName = "MessageSources";
3521
2489
  const SvgThumbsDown = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1, strokeLinecap: "round", strokeLinejoin: "round", className: "lucide lucide-thumbs-down", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M17 14V2" }), /* @__PURE__ */ React.createElement("path", { d: "M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z" }));
3522
2490
  const SvgThumbsUp = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1, strokeLinecap: "round", strokeLinejoin: "round", className: "lucide lucide-thumbs-up", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M7 10v12" }), /* @__PURE__ */ React.createElement("path", { d: "M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z" }));
3523
2491
  const SvgRefresh = (props) => /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 1, strokeLinecap: "round", strokeLinejoin: "round", className: "lucide lucide-refresh-ccw", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" }), /* @__PURE__ */ React.createElement("path", { d: "M3 3v5h5" }), /* @__PURE__ */ React.createElement("path", { d: "M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16" }), /* @__PURE__ */ React.createElement("path", { d: "M16 16h5v5" }));
3524
- const MessageActions = ({
3525
- children,
3526
- ...props
3527
- }) => {
3528
- const { theme } = useContext(ChatContext);
3529
- const {
3530
- question,
3531
- response,
3532
- copyIcon = /* @__PURE__ */ jsx(SvgCopy, {}),
3533
- thumbsUpIcon = /* @__PURE__ */ jsx(SvgThumbsUp, {}),
3534
- thumbsDownIcon = /* @__PURE__ */ jsx(SvgThumbsDown, {}),
3535
- refreshIcon = /* @__PURE__ */ jsx(SvgRefresh, {}),
3536
- onCopy,
3537
- onUpvote,
3538
- onDownvote,
3539
- onRefresh
3540
- } = props;
3541
- const Comp = children ? Slot : "div";
3542
- const handleCopy = (text) => {
3543
- navigator.clipboard.writeText(text).then(() => {
3544
- console.log("Text copied to clipboard");
3545
- }).catch((err) => {
3546
- console.error("Could not copy text: ", err);
3547
- });
3548
- };
3549
- return (copyIcon || thumbsDownIcon || thumbsUpIcon || refreshIcon) && /* @__PURE__ */ jsx(Comp, { className: cn(theme.messages.message.footer.base), children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
3550
- copyIcon && /* @__PURE__ */ jsx(
3551
- IconButton,
3552
- {
3553
- variant: "text",
3554
- disablePadding: true,
3555
- title: "Copy question and response",
3556
- className: cn(theme.messages.message.footer.copy),
3557
- onClick: onCopy ? onCopy : () => handleCopy(`${question}
3558
- ${response}`),
3559
- children: copyIcon
3560
- }
3561
- ),
3562
- thumbsUpIcon && /* @__PURE__ */ jsx(
3563
- IconButton,
3564
- {
3565
- variant: "text",
3566
- disablePadding: true,
3567
- title: "Upvote",
3568
- className: cn(theme.messages.message.footer.upvote),
3569
- onClick: onUpvote,
3570
- children: thumbsUpIcon
3571
- }
3572
- ),
3573
- thumbsDownIcon && /* @__PURE__ */ jsx(
3574
- IconButton,
3575
- {
3576
- variant: "text",
3577
- disablePadding: true,
3578
- title: "Downvote",
3579
- className: cn(theme.messages.message.footer.downvote),
3580
- onClick: onDownvote,
3581
- children: thumbsDownIcon
3582
- }
3583
- ),
3584
- refreshIcon && /* @__PURE__ */ jsx(
3585
- IconButton,
3586
- {
3587
- variant: "text",
3588
- disablePadding: true,
3589
- title: "Refresh",
3590
- className: cn(theme.messages.message.footer.refresh),
3591
- onClick: onRefresh,
3592
- children: refreshIcon
2492
+ const MessageActions = memo(
2493
+ ({ children, ...props }) => {
2494
+ const { theme } = useContext(ChatContext);
2495
+ const {
2496
+ question,
2497
+ response,
2498
+ copyIcon = /* @__PURE__ */ jsx(SvgCopy, {}),
2499
+ thumbsUpIcon = /* @__PURE__ */ jsx(SvgThumbsUp, {}),
2500
+ thumbsDownIcon = /* @__PURE__ */ jsx(SvgThumbsDown, {}),
2501
+ refreshIcon = /* @__PURE__ */ jsx(SvgRefresh, {}),
2502
+ onCopy,
2503
+ onUpvote,
2504
+ onDownvote,
2505
+ onRefresh
2506
+ } = props;
2507
+ const Comp = children ? Slot : "div";
2508
+ const handleCopy = useCallback((text) => {
2509
+ navigator.clipboard.writeText(text).then(() => {
2510
+ console.log("Text copied to clipboard");
2511
+ }).catch((err) => {
2512
+ console.error("Could not copy text: ", err);
2513
+ });
2514
+ }, []);
2515
+ const handleCopyClick = useCallback(() => {
2516
+ if (onCopy) {
2517
+ onCopy();
2518
+ } else {
2519
+ handleCopy(`${question}${response ? `
2520
+ ${response}` : ""}`);
3593
2521
  }
3594
- )
3595
- ] }) });
3596
- };
2522
+ }, [onCopy, handleCopy, question, response]);
2523
+ return (copyIcon || thumbsDownIcon || thumbsUpIcon || refreshIcon) && /* @__PURE__ */ jsx(Comp, { className: cn(theme.messages.message.footer.base), children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
2524
+ copyIcon && /* @__PURE__ */ jsx(
2525
+ IconButton,
2526
+ {
2527
+ variant: "text",
2528
+ disablePadding: true,
2529
+ title: "Copy question and response",
2530
+ className: cn(theme.messages.message.footer.copy),
2531
+ onClick: handleCopyClick,
2532
+ children: copyIcon
2533
+ }
2534
+ ),
2535
+ thumbsUpIcon && /* @__PURE__ */ jsx(
2536
+ IconButton,
2537
+ {
2538
+ variant: "text",
2539
+ disablePadding: true,
2540
+ title: "Upvote",
2541
+ className: cn(theme.messages.message.footer.upvote),
2542
+ onClick: onUpvote,
2543
+ children: thumbsUpIcon
2544
+ }
2545
+ ),
2546
+ thumbsDownIcon && /* @__PURE__ */ jsx(
2547
+ IconButton,
2548
+ {
2549
+ variant: "text",
2550
+ disablePadding: true,
2551
+ title: "Downvote",
2552
+ className: cn(theme.messages.message.footer.downvote),
2553
+ onClick: onDownvote,
2554
+ children: thumbsDownIcon
2555
+ }
2556
+ ),
2557
+ refreshIcon && /* @__PURE__ */ jsx(
2558
+ IconButton,
2559
+ {
2560
+ variant: "text",
2561
+ disablePadding: true,
2562
+ title: "Refresh",
2563
+ className: cn(theme.messages.message.footer.refresh),
2564
+ onClick: onRefresh,
2565
+ children: refreshIcon
2566
+ }
2567
+ )
2568
+ ] }) });
2569
+ }
2570
+ );
2571
+ MessageActions.displayName = "MessageActions";
3597
2572
  const messageVariants = {
3598
2573
  hidden: {
3599
2574
  opacity: 0,
@@ -3607,37 +2582,36 @@ const messageVariants = {
3607
2582
  }
3608
2583
  }
3609
2584
  };
3610
- const SessionMessage = ({
3611
- conversation,
3612
- isLast,
3613
- children
3614
- }) => {
3615
- const { theme, isLoading } = useContext(ChatContext);
3616
- return /* @__PURE__ */ jsx(motion.div, { variants: messageVariants, children: /* @__PURE__ */ jsx(Card, { className: cn(theme.messages.message.base), children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
3617
- /* @__PURE__ */ jsx(
3618
- MessageQuestion,
3619
- {
3620
- question: conversation.question,
3621
- files: conversation.files
3622
- }
3623
- ),
3624
- /* @__PURE__ */ jsx(
3625
- MessageResponse,
3626
- {
3627
- response: conversation.response,
3628
- isLoading: isLast && isLoading
3629
- }
3630
- ),
3631
- /* @__PURE__ */ jsx(MessageSources, { sources: conversation.sources }),
3632
- /* @__PURE__ */ jsx(
3633
- MessageActions,
3634
- {
3635
- question: conversation.question,
3636
- response: conversation.response
3637
- }
3638
- )
3639
- ] }) }) }, conversation.id);
3640
- };
2585
+ const SessionMessage = memo(
2586
+ ({ conversation, isLast, children }) => {
2587
+ const { theme, isLoading } = useContext(ChatContext);
2588
+ return /* @__PURE__ */ jsx(motion.div, { variants: messageVariants, children: /* @__PURE__ */ jsx(Card, { className: cn(theme.messages.message.base), children: children || /* @__PURE__ */ jsxs(Fragment, { children: [
2589
+ /* @__PURE__ */ jsx(
2590
+ MessageQuestion,
2591
+ {
2592
+ question: conversation.question,
2593
+ files: conversation.files
2594
+ }
2595
+ ),
2596
+ /* @__PURE__ */ jsx(
2597
+ MessageResponse,
2598
+ {
2599
+ response: conversation.response,
2600
+ isLoading: isLast && isLoading
2601
+ }
2602
+ ),
2603
+ /* @__PURE__ */ jsx(MessageSources, { sources: conversation.sources }),
2604
+ /* @__PURE__ */ jsx(
2605
+ MessageActions,
2606
+ {
2607
+ question: conversation.question,
2608
+ response: conversation.response
2609
+ }
2610
+ )
2611
+ ] }) }) }, conversation.id);
2612
+ }
2613
+ );
2614
+ SessionMessage.displayName = "SessionMessage";
3641
2615
  const SvgArrowDown = (props) => /* @__PURE__ */ React.createElement("svg", { width: 20, height: 20, viewBox: "0 0 20 20", fill: "currentColor", xmlns: "http://www.w3.org/2000/svg", className: "shrink-0 mix-blend-luminosity", "aria-hidden": "true", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M10 3C10.2761 3.00006 10.5 3.2239 10.5 3.5V15.293L14.6465 11.1465C14.8418 10.9514 15.1583 10.9513 15.3536 11.1465C15.5487 11.3417 15.5486 11.6583 15.3536 11.8535L10.3535 16.8535C10.2598 16.9473 10.1326 17 10 17C9.90062 17 9.8042 16.9703 9.72268 16.916L9.64651 16.8535L4.6465 11.8535C4.45138 11.6582 4.45128 11.3417 4.6465 11.1465C4.84172 10.9513 5.15827 10.9514 5.35353 11.1465L9.50003 15.293V3.5C9.50003 3.22386 9.72389 3 10 3Z" }));
3642
2616
  const containerVariants = {
3643
2617
  hidden: {},
@@ -3743,7 +2717,7 @@ const SessionMessages = ({
3743
2717
  SessionMessage,
3744
2718
  {
3745
2719
  conversation,
3746
- isLast: index === conversation.length - 1
2720
+ isLast: index === convosToRender.length - 1
3747
2721
  },
3748
2722
  conversation.id
3749
2723
  ))
@@ -3777,23 +2751,35 @@ const SessionMessages = ({
3777
2751
  const useDimensions = () => {
3778
2752
  const [ref, setRef] = useState(null);
3779
2753
  const [width, setWidth] = useState(void 0);
2754
+ const rafId = useRef(null);
3780
2755
  const observe = useCallback((element) => {
3781
2756
  if (element) setRef(element);
3782
2757
  }, []);
3783
2758
  useEffect(() => {
3784
2759
  if (!ref) return;
3785
2760
  const resizeObserver = new ResizeObserver((entries) => {
3786
- for (let entry of entries) {
3787
- setWidth(entry.contentRect.width);
2761
+ if (rafId.current !== null) {
2762
+ cancelAnimationFrame(rafId.current);
3788
2763
  }
2764
+ rafId.current = requestAnimationFrame(() => {
2765
+ for (const entry of entries) {
2766
+ setWidth(entry.contentRect.width);
2767
+ }
2768
+ rafId.current = null;
2769
+ });
3789
2770
  });
3790
2771
  resizeObserver.observe(ref);
3791
2772
  return () => {
2773
+ if (rafId.current !== null) {
2774
+ cancelAnimationFrame(rafId.current);
2775
+ rafId.current = null;
2776
+ }
3792
2777
  resizeObserver.disconnect();
3793
2778
  };
3794
2779
  }, [ref]);
3795
2780
  return { width, observe };
3796
2781
  };
2782
+ const defaultRemarkPlugins = [remarkGfm, remarkYoutube, remarkMath];
3797
2783
  const Chat = ({
3798
2784
  children,
3799
2785
  viewType = "console",
@@ -3807,7 +2793,7 @@ const Chat = ({
3807
2793
  activeSessionId,
3808
2794
  theme: customTheme = chatTheme,
3809
2795
  onNewSession,
3810
- remarkPlugins = [remarkGfm, remarkYoutube, remarkMath],
2796
+ remarkPlugins = defaultRemarkPlugins,
3811
2797
  markdownComponents,
3812
2798
  disabled,
3813
2799
  style,
@@ -3906,44 +2892,54 @@ const Chat = ({
3906
2892
  };
3907
2893
  const SvgTrash = (props) => /* @__PURE__ */ React.createElement("svg", { width: 14, height: 14, viewBox: "0 0 14 14", fill: "none", xmlns: "http://www.w3.org/2000/svg", ...props }, /* @__PURE__ */ React.createElement("g", { id: "Delete" }, /* @__PURE__ */ React.createElement("path", { id: "Vector", d: "M5.97905 1.16666C5.90859 1.16576 5.83895 1.18189 5.77605 1.21368C5.71316 1.24547 5.65888 1.29199 5.61783 1.34926C5.57677 1.40654 5.55016 1.47288 5.54025 1.54265C5.53034 1.61242 5.53743 1.68355 5.56092 1.75H4.27007C3.7342 1.75 3.2324 2.01817 2.93535 2.46435L2.24492 3.5H2.18738C2.12941 3.49918 2.07185 3.50989 2.01805 3.5315C1.96425 3.55312 1.91529 3.58522 1.874 3.62593C1.83271 3.66663 1.79993 3.71514 1.77755 3.76863C1.75518 3.82211 1.74365 3.87952 1.74365 3.9375C1.74365 3.99548 1.75518 4.05288 1.77755 4.10636C1.79993 4.15985 1.83271 4.20836 1.874 4.24907C1.91529 4.28977 1.96425 4.32187 2.01805 4.34349C2.07185 4.3651 2.12941 4.37582 2.18738 4.375H2.41012C2.44765 4.38067 2.48576 4.38143 2.52348 4.37727L3.24468 11.1084C3.33169 11.9199 4.02367 12.5417 4.83973 12.5417H9.15947C9.97553 12.5417 10.6675 11.9199 10.7545 11.1084L11.4763 4.37727C11.5133 4.38124 11.5506 4.38047 11.5874 4.375H11.8124C11.8704 4.37582 11.9279 4.3651 11.9817 4.34349C12.0355 4.32187 12.0845 4.28977 12.1258 4.24907C12.1671 4.20836 12.1998 4.15985 12.2222 4.10636C12.2446 4.05288 12.2561 3.99548 12.2561 3.9375C12.2561 3.87952 12.2446 3.82211 12.2222 3.76863C12.1998 3.71514 12.1671 3.66663 12.1258 3.62593C12.0845 3.58522 12.0355 3.55312 11.9817 3.5315C11.9279 3.50989 11.8704 3.49918 11.8124 3.5H11.7548L11.0644 2.46435C10.7671 2.01841 10.2654 1.75 9.7297 1.75H8.43885C8.46234 1.68355 8.46943 1.61242 8.45952 1.54265C8.44961 1.47288 8.423 1.40654 8.38194 1.34926C8.34089 1.29199 8.2866 1.24547 8.22371 1.21368C8.16082 1.18189 8.09118 1.16576 8.02072 1.16666H5.97905ZM4.27007 2.625H9.7297C9.97394 2.625 10.2009 2.74639 10.3364 2.9497L10.7033 3.5H3.29651L3.66338 2.9497L3.66395 2.94913C3.79913 2.74608 4.02543 2.625 4.27007 2.625ZM3.40361 4.375H10.5962L9.88465 11.015C9.8445 11.3894 9.53575 11.6667 9.15947 11.6667H4.83973C4.46345 11.6667 4.15527 11.3894 4.11512 11.015L3.40361 4.375Z", fill: "currentColor" })));
3908
2894
  const SvgChat = (props) => /* @__PURE__ */ React.createElement("svg", { width: 16, height: 17, viewBox: "0 0 16 17", fill: "none", xmlns: "http://www.w3.org/2000/svg", ...props }, /* @__PURE__ */ React.createElement("path", { d: "M8 3C4.55375 3 1.75 5.23753 1.75 7.98828C1.75 9.70653 2.83659 11.2762 4.62109 12.188C4.11184 13.0465 3.62587 13.7378 3.62012 13.7461C3.50687 13.9071 3.49862 14.1196 3.59912 14.2891C3.69012 14.4418 3.8543 14.5342 4.0293 14.5342C4.0483 14.5342 4.06743 14.533 4.08643 14.5308C4.15168 14.5233 5.66214 14.3364 7.50439 12.9604C7.67239 12.9712 7.8385 12.9766 8 12.9766C11.4462 12.9766 14.25 10.739 14.25 7.98828C14.25 5.23753 11.4462 3 8 3ZM8 4C10.8948 4 13.25 5.78903 13.25 7.98828C13.25 10.1875 10.8948 11.9766 8 11.9766C7.8055 11.9766 7.60225 11.968 7.396 11.9497C7.271 11.9382 7.1454 11.9752 7.0459 12.0527C6.3589 12.5855 5.72033 12.9308 5.20508 13.1528C5.38383 12.8648 5.57691 12.5418 5.76416 12.2061C5.83416 12.0813 5.84705 11.9324 5.7998 11.7974C5.75255 11.6624 5.64983 11.5542 5.51758 11.5C3.81033 10.7993 2.75 9.45328 2.75 7.98828C2.75 5.78903 5.10525 4 8 4ZM5.5 7.25C5.08575 7.25 4.75 7.58575 4.75 8C4.75 8.41425 5.08575 8.75 5.5 8.75C5.91425 8.75 6.25 8.41425 6.25 8C6.25 7.58575 5.91425 7.25 5.5 7.25ZM8 7.25C7.58575 7.25 7.25 7.58575 7.25 8C7.25 8.41425 7.58575 8.75 8 8.75C8.41425 8.75 8.75 8.41425 8.75 8C8.75 7.58575 8.41425 7.25 8 7.25ZM10.5 7.25C10.0857 7.25 9.75 7.58575 9.75 8C9.75 8.41425 10.0857 8.75 10.5 8.75C10.9143 8.75 11.25 8.41425 11.25 8C11.25 7.58575 10.9143 7.25 10.5 7.25Z", fill: "currentColor" }));
3909
- const SessionListItem = ({
3910
- children,
3911
- session,
3912
- deletable = true,
3913
- limit = 100,
3914
- deleteIcon = /* @__PURE__ */ jsx(SvgTrash, {}),
3915
- chatIcon = /* @__PURE__ */ jsx(SvgChat, { className: "mr-2" })
3916
- }) => {
3917
- const { activeSessionId, selectSession, deleteSession, theme } = useContext(ChatContext);
3918
- const Comp = children ? Slot : ListItem;
3919
- return /* @__PURE__ */ jsx(
3920
- Comp,
3921
- {
3922
- dense: true,
3923
- disableGutters: true,
3924
- active: session.id === activeSessionId,
3925
- className: cn(theme.sessions.session.base, {
3926
- [theme.sessions.session.active]: session.id === activeSessionId
3927
- }),
3928
- onClick: () => selectSession == null ? void 0 : selectSession(session.id),
3929
- start: chatIcon,
3930
- end: /* @__PURE__ */ jsx(Fragment, { children: deletable && /* @__PURE__ */ jsx(
3931
- IconButton,
3932
- {
3933
- size: "small",
3934
- variant: "text",
3935
- onClick: (e) => {
3936
- e.stopPropagation();
3937
- deleteSession(session.id);
3938
- },
3939
- className: cn(theme.sessions.session.delete),
3940
- children: deleteIcon
3941
- }
3942
- ) }),
3943
- children: children || /* @__PURE__ */ jsx(Ellipsis, { value: session.title, limit })
3944
- }
3945
- );
3946
- };
2895
+ const SessionListItem = memo(
2896
+ ({
2897
+ children,
2898
+ session,
2899
+ deletable = true,
2900
+ limit = 100,
2901
+ deleteIcon = /* @__PURE__ */ jsx(SvgTrash, {}),
2902
+ chatIcon = /* @__PURE__ */ jsx(SvgChat, { className: "mr-2" })
2903
+ }) => {
2904
+ const { activeSessionId, selectSession, deleteSession, theme } = useContext(ChatContext);
2905
+ const Comp = children ? Slot : ListItem;
2906
+ const handleSelect = useCallback(() => {
2907
+ selectSession == null ? void 0 : selectSession(session.id);
2908
+ }, [selectSession, session.id]);
2909
+ const handleDelete = useCallback(
2910
+ (e) => {
2911
+ e.stopPropagation();
2912
+ deleteSession(session.id);
2913
+ },
2914
+ [deleteSession, session.id]
2915
+ );
2916
+ return /* @__PURE__ */ jsx(
2917
+ Comp,
2918
+ {
2919
+ dense: true,
2920
+ disableGutters: true,
2921
+ active: session.id === activeSessionId,
2922
+ className: cn(theme.sessions.session.base, {
2923
+ [theme.sessions.session.active]: session.id === activeSessionId
2924
+ }),
2925
+ onClick: handleSelect,
2926
+ start: chatIcon,
2927
+ end: /* @__PURE__ */ jsx(Fragment, { children: deletable && /* @__PURE__ */ jsx(
2928
+ IconButton,
2929
+ {
2930
+ size: "small",
2931
+ variant: "text",
2932
+ onClick: handleDelete,
2933
+ className: cn(theme.sessions.session.delete),
2934
+ children: deleteIcon
2935
+ }
2936
+ ) }),
2937
+ children: children || /* @__PURE__ */ jsx(Ellipsis, { value: session.title, limit })
2938
+ }
2939
+ );
2940
+ }
2941
+ );
2942
+ SessionListItem.displayName = "SessionListItem";
3947
2943
  const SessionsList = ({
3948
2944
  children,
3949
2945
  templates
@@ -4026,49 +3022,43 @@ const sortOrder = [
4026
3022
  "December",
4027
3023
  "Last Year"
4028
3024
  ];
3025
+ const sortOrderMap = new Map(sortOrder.map((v, i) => [v, i]));
4029
3026
  function groupSessionsByDate(sessions) {
4030
3027
  const grouped = {};
3028
+ const now = /* @__PURE__ */ new Date();
4031
3029
  sessions.forEach((session) => {
4032
- const createdAt = new Date(session.createdAt);
4033
- const now = /* @__PURE__ */ new Date();
4034
- if (isToday(createdAt)) {
4035
- if (!grouped["Today"]) grouped["Today"] = [];
4036
- grouped["Today"].push(session);
3030
+ const createdAt = session.createdAt ? new Date(session.createdAt) : null;
3031
+ let group;
3032
+ if (!createdAt || isNaN(createdAt.getTime())) {
3033
+ group = "Last Year";
3034
+ } else if (isToday(createdAt)) {
3035
+ group = "Today";
4037
3036
  } else if (isYesterday(createdAt)) {
4038
- if (!grouped["Yesterday"]) grouped["Yesterday"] = [];
4039
- grouped["Yesterday"].push(session);
3037
+ group = "Yesterday";
4040
3038
  } else if (isThisWeek(createdAt)) {
4041
- if (!grouped["Last Week"]) grouped["Last Week"] = [];
4042
- grouped["Last Week"].push(session);
3039
+ group = "Last Week";
4043
3040
  } else if (differenceInYears(now, createdAt) === 0) {
4044
3041
  const monthDiff = now.getMonth() - createdAt.getMonth();
4045
3042
  const yearDiff = now.getFullYear() - createdAt.getFullYear();
4046
3043
  const adjustedMonthDiff = yearDiff > 0 ? monthDiff + 12 : monthDiff;
4047
3044
  if (adjustedMonthDiff === 1 || adjustedMonthDiff === 0 && now.getDate() > createdAt.getDate()) {
4048
- if (!grouped["Last Month"]) grouped["Last Month"] = [];
4049
- grouped["Last Month"].push(session);
3045
+ group = "Last Month";
4050
3046
  } else {
4051
- const monthName = format(createdAt, "MMMM");
4052
- if (!grouped[monthName]) grouped[monthName] = [];
4053
- grouped[monthName].push(session);
3047
+ group = format(createdAt, "MMMM");
4054
3048
  }
4055
3049
  } else {
4056
- if (!grouped["Last Year"]) grouped["Last Year"] = [];
4057
- grouped["Last Year"].push(session);
4058
- }
4059
- });
4060
- Object.keys(grouped).forEach((key) => {
4061
- if (grouped[key].length === 0) {
4062
- delete grouped[key];
3050
+ group = "Last Year";
4063
3051
  }
3052
+ if (!grouped[group]) grouped[group] = [];
3053
+ grouped[group].push(session);
4064
3054
  });
4065
3055
  const sortedGroups = Object.keys(grouped).sort(
4066
- (a, b) => sortOrder.indexOf(a) - sortOrder.indexOf(b)
3056
+ (a, b) => (sortOrderMap.get(a) ?? 999) - (sortOrderMap.get(b) ?? 999)
4067
3057
  );
4068
3058
  return sortedGroups.map((heading) => ({
4069
3059
  heading,
4070
3060
  sessions: grouped[heading].sort(
4071
- (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
3061
+ (a, b) => (b.createdAt ? new Date(b.createdAt).getTime() : 0) - (a.createdAt ? new Date(a.createdAt).getTime() : 0)
4072
3062
  )
4073
3063
  }));
4074
3064
  }
@@ -4102,16 +3092,21 @@ const AppBar = ({
4102
3092
  const theme = useComponentTheme("chat", customTheme);
4103
3093
  return /* @__PURE__ */ jsx("div", { className: cn(theme.appbar), children: content });
4104
3094
  };
3095
+ const DEFAULT_MODIFIERS = [offset({ mainAxis: 0, crossAxis: -40 })];
4105
3096
  const ChatBubble = memo(
4106
3097
  ({
4107
3098
  children,
4108
3099
  bubbleContent,
4109
3100
  position = "right-end",
4110
- modifiers = [offset({ mainAxis: 0, crossAxis: -40 })],
3101
+ modifiers = DEFAULT_MODIFIERS,
4111
3102
  className
4112
3103
  }) => {
4113
3104
  const [isOpen, setIsOpen] = useState(false);
4114
3105
  const ref = useRef(null);
3106
+ const handleOpen = useCallback(() => setIsOpen(true), []);
3107
+ const handleClose = useCallback(() => setIsOpen(false), []);
3108
+ const handleToggle = useCallback(() => setIsOpen((prev) => !prev), []);
3109
+ const renderContent = useCallback(() => /* @__PURE__ */ jsx(Fragment, { children }), [children]);
4115
3110
  return /* @__PURE__ */ jsxs(Fragment, { children: [
4116
3111
  /* @__PURE__ */ jsx(
4117
3112
  ConnectedOverlay,
@@ -4120,20 +3115,12 @@ const ChatBubble = memo(
4120
3115
  modifiers,
4121
3116
  reference: ref.current,
4122
3117
  open: isOpen,
4123
- onOpen: () => setIsOpen(true),
4124
- onClose: () => setIsOpen(false),
4125
- content: () => /* @__PURE__ */ jsx(Fragment, { children })
3118
+ onOpen: handleOpen,
3119
+ onClose: handleClose,
3120
+ content: renderContent
4126
3121
  }
4127
3122
  ),
4128
- /* @__PURE__ */ jsx(
4129
- "div",
4130
- {
4131
- ref,
4132
- className,
4133
- onClick: () => setIsOpen((prev) => !prev),
4134
- children: bubbleContent
4135
- }
4136
- )
3123
+ /* @__PURE__ */ jsx("div", { ref, className, onClick: handleToggle, children: bubbleContent })
4137
3124
  ] });
4138
3125
  }
4139
3126
  );
@@ -4314,56 +3301,394 @@ const MessageStatus = ({
4314
3301
  }
4315
3302
  ) });
4316
3303
  };
3304
+ var AgUiEventType = /* @__PURE__ */ ((AgUiEventType2) => {
3305
+ AgUiEventType2["RUN_STARTED"] = "RUN_STARTED";
3306
+ AgUiEventType2["RUN_FINISHED"] = "RUN_FINISHED";
3307
+ AgUiEventType2["RUN_ERROR"] = "RUN_ERROR";
3308
+ AgUiEventType2["STEP_STARTED"] = "STEP_STARTED";
3309
+ AgUiEventType2["STEP_FINISHED"] = "STEP_FINISHED";
3310
+ AgUiEventType2["TEXT_MESSAGE_START"] = "TEXT_MESSAGE_START";
3311
+ AgUiEventType2["TEXT_MESSAGE_CONTENT"] = "TEXT_MESSAGE_CONTENT";
3312
+ AgUiEventType2["TEXT_MESSAGE_END"] = "TEXT_MESSAGE_END";
3313
+ AgUiEventType2["TEXT_MESSAGE_CHUNK"] = "TEXT_MESSAGE_CHUNK";
3314
+ AgUiEventType2["TOOL_CALL_START"] = "TOOL_CALL_START";
3315
+ AgUiEventType2["TOOL_CALL_ARGS"] = "TOOL_CALL_ARGS";
3316
+ AgUiEventType2["TOOL_CALL_END"] = "TOOL_CALL_END";
3317
+ AgUiEventType2["TOOL_CALL_RESULT"] = "TOOL_CALL_RESULT";
3318
+ AgUiEventType2["TOOL_CALL_CHUNK"] = "TOOL_CALL_CHUNK";
3319
+ AgUiEventType2["STATE_SNAPSHOT"] = "STATE_SNAPSHOT";
3320
+ AgUiEventType2["STATE_DELTA"] = "STATE_DELTA";
3321
+ AgUiEventType2["MESSAGES_SNAPSHOT"] = "MESSAGES_SNAPSHOT";
3322
+ AgUiEventType2["RAW"] = "RAW";
3323
+ AgUiEventType2["CUSTOM"] = "CUSTOM";
3324
+ return AgUiEventType2;
3325
+ })(AgUiEventType || {});
3326
+ function generateId() {
3327
+ return Math.random().toString(36).substring(2, 11);
3328
+ }
3329
+ function addConversationToSession(sessions, sessionId, conversation) {
3330
+ return sessions.map((s) => {
3331
+ if (s.id !== sessionId) return s;
3332
+ return {
3333
+ ...s,
3334
+ updatedAt: conversation.createdAt,
3335
+ conversations: [...s.conversations, conversation]
3336
+ };
3337
+ });
3338
+ }
3339
+ function updateConversationInSession(sessions, sessionId, conversationId, response) {
3340
+ return sessions.map((s) => {
3341
+ if (s.id !== sessionId) return s;
3342
+ return {
3343
+ ...s,
3344
+ updatedAt: /* @__PURE__ */ new Date(),
3345
+ conversations: s.conversations.map((c) => {
3346
+ if (c.id !== conversationId) return c;
3347
+ return { ...c, response, updatedAt: /* @__PURE__ */ new Date() };
3348
+ })
3349
+ };
3350
+ });
3351
+ }
3352
+ function sessionsToAgUiMessages(session) {
3353
+ const messages = [];
3354
+ for (const conv of session.conversations) {
3355
+ messages.push({
3356
+ id: `${conv.id}-q`,
3357
+ role: "user",
3358
+ content: conv.question
3359
+ });
3360
+ if (conv.response) {
3361
+ messages.push({
3362
+ id: `${conv.id}-r`,
3363
+ role: "assistant",
3364
+ content: conv.response
3365
+ });
3366
+ }
3367
+ }
3368
+ return messages;
3369
+ }
3370
+ function parseSSELine(line) {
3371
+ const trimmed = line.trim();
3372
+ if (!trimmed || trimmed.startsWith(":")) return null;
3373
+ if (trimmed.startsWith("data:")) {
3374
+ const data = trimmed.slice(5).trim();
3375
+ if (data === "[DONE]") return null;
3376
+ try {
3377
+ return JSON.parse(data);
3378
+ } catch (err) {
3379
+ return new Error(
3380
+ `Failed to parse AG-UI event: ${err instanceof Error ? err.message : err}`
3381
+ );
3382
+ }
3383
+ }
3384
+ return null;
3385
+ }
3386
+ async function* parseSSE(response, signal) {
3387
+ var _a;
3388
+ const reader = (_a = response.body) == null ? void 0 : _a.getReader();
3389
+ if (!reader) {
3390
+ throw new Error("Response body is not readable");
3391
+ }
3392
+ const decoder = new TextDecoder();
3393
+ let buffer = "";
3394
+ try {
3395
+ while (!signal.aborted) {
3396
+ const { done, value } = await reader.read();
3397
+ if (done) break;
3398
+ buffer += decoder.decode(value, { stream: true });
3399
+ const lines = buffer.split("\n");
3400
+ buffer = lines.pop() || "";
3401
+ for (const line of lines) {
3402
+ const result = parseSSELine(line);
3403
+ if (result !== null) yield result;
3404
+ }
3405
+ }
3406
+ if (buffer.trim()) {
3407
+ const result = parseSSELine(buffer);
3408
+ if (result !== null) yield result;
3409
+ }
3410
+ } finally {
3411
+ reader.releaseLock();
3412
+ }
3413
+ }
3414
+ function useAgUi({
3415
+ agent,
3416
+ initialSessions = [],
3417
+ initialActiveSessionId,
3418
+ tools = [],
3419
+ context = [],
3420
+ forwardedProps = {},
3421
+ headers = {},
3422
+ onToolCall,
3423
+ onError,
3424
+ onEvent
3425
+ }) {
3426
+ const [sessions, setSessions] = useState(initialSessions);
3427
+ const [activeSessionId, setActiveSessionId] = useState(
3428
+ initialActiveSessionId
3429
+ );
3430
+ const [isLoading, setIsLoading] = useState(false);
3431
+ const abortRef = useRef(null);
3432
+ const onToolCallRef = useRef(onToolCall);
3433
+ onToolCallRef.current = onToolCall;
3434
+ const onErrorRef = useRef(onError);
3435
+ onErrorRef.current = onError;
3436
+ const onEventRef = useRef(onEvent);
3437
+ onEventRef.current = onEvent;
3438
+ useEffect(() => {
3439
+ return () => {
3440
+ var _a;
3441
+ (_a = abortRef.current) == null ? void 0 : _a.abort();
3442
+ };
3443
+ }, []);
3444
+ const selectSession = useCallback((sessionId) => {
3445
+ setActiveSessionId(sessionId);
3446
+ }, []);
3447
+ const deleteSession = useCallback(
3448
+ (sessionId) => {
3449
+ setSessions((prev) => prev.filter((s) => s.id !== sessionId));
3450
+ if (activeSessionId === sessionId) {
3451
+ setActiveSessionId(void 0);
3452
+ }
3453
+ },
3454
+ [activeSessionId]
3455
+ );
3456
+ const createSession = useCallback(() => {
3457
+ const id = generateId();
3458
+ const newSession = {
3459
+ id,
3460
+ title: "New Session",
3461
+ createdAt: /* @__PURE__ */ new Date(),
3462
+ updatedAt: /* @__PURE__ */ new Date(),
3463
+ conversations: []
3464
+ };
3465
+ setSessions((prev) => [newSession, ...prev]);
3466
+ setActiveSessionId(id);
3467
+ }, []);
3468
+ const stopMessage = useCallback(() => {
3469
+ var _a;
3470
+ (_a = abortRef.current) == null ? void 0 : _a.abort();
3471
+ abortRef.current = null;
3472
+ setIsLoading(false);
3473
+ }, []);
3474
+ const sendMessage = useCallback(
3475
+ async (message) => {
3476
+ var _a, _b, _c, _d, _e, _f;
3477
+ (_a = abortRef.current) == null ? void 0 : _a.abort();
3478
+ const abortController = new AbortController();
3479
+ abortRef.current = abortController;
3480
+ let sessionId = activeSessionId;
3481
+ if (!sessionId) {
3482
+ sessionId = generateId();
3483
+ const newSession = {
3484
+ id: sessionId,
3485
+ title: message.slice(0, 50),
3486
+ createdAt: /* @__PURE__ */ new Date(),
3487
+ updatedAt: /* @__PURE__ */ new Date(),
3488
+ conversations: []
3489
+ };
3490
+ setSessions((prev) => [newSession, ...prev]);
3491
+ setActiveSessionId(sessionId);
3492
+ }
3493
+ const conversationId = generateId();
3494
+ const now = /* @__PURE__ */ new Date();
3495
+ setSessions(
3496
+ (prev) => addConversationToSession(prev, sessionId, {
3497
+ id: conversationId,
3498
+ question: message,
3499
+ createdAt: now
3500
+ })
3501
+ );
3502
+ setIsLoading(true);
3503
+ const currentSession = [
3504
+ ...((_b = sessions.find((s) => s.id === sessionId)) == null ? void 0 : _b.conversations) ?? []
3505
+ ];
3506
+ const historyMessages = sessionsToAgUiMessages({
3507
+ conversations: currentSession
3508
+ });
3509
+ historyMessages.push({
3510
+ id: `${conversationId}-q`,
3511
+ role: "user",
3512
+ content: message
3513
+ });
3514
+ const runId = generateId();
3515
+ const input = {
3516
+ threadId: sessionId,
3517
+ runId,
3518
+ messages: historyMessages,
3519
+ tools,
3520
+ context,
3521
+ state: null,
3522
+ forwardedProps
3523
+ };
3524
+ try {
3525
+ const response = await fetch(agent, {
3526
+ method: "POST",
3527
+ headers: {
3528
+ "Content-Type": "application/json",
3529
+ Accept: "text/event-stream",
3530
+ ...headers
3531
+ },
3532
+ body: JSON.stringify(input),
3533
+ signal: abortController.signal
3534
+ });
3535
+ if (!response.ok) {
3536
+ throw new Error(
3537
+ `Agent returned ${response.status}: ${response.statusText}`
3538
+ );
3539
+ }
3540
+ let responseText = "";
3541
+ const toolCalls = /* @__PURE__ */ new Map();
3542
+ const updateResponse = (text) => {
3543
+ setSessions(
3544
+ (prev) => updateConversationInSession(prev, sessionId, conversationId, text)
3545
+ );
3546
+ };
3547
+ for await (const eventOrError of parseSSE(
3548
+ response,
3549
+ abortController.signal
3550
+ )) {
3551
+ if (eventOrError instanceof Error) {
3552
+ (_c = onErrorRef.current) == null ? void 0 : _c.call(onErrorRef, eventOrError);
3553
+ continue;
3554
+ }
3555
+ const event = eventOrError;
3556
+ (_d = onEventRef.current) == null ? void 0 : _d.call(onEventRef, event);
3557
+ switch (event.type) {
3558
+ case AgUiEventType.TEXT_MESSAGE_CONTENT: {
3559
+ responseText += event.delta;
3560
+ updateResponse(responseText);
3561
+ break;
3562
+ }
3563
+ case AgUiEventType.TEXT_MESSAGE_CHUNK: {
3564
+ if (event.delta) {
3565
+ responseText += event.delta;
3566
+ updateResponse(responseText);
3567
+ }
3568
+ break;
3569
+ }
3570
+ case AgUiEventType.TOOL_CALL_START: {
3571
+ toolCalls.set(event.toolCallId, {
3572
+ name: event.toolCallName,
3573
+ args: ""
3574
+ });
3575
+ break;
3576
+ }
3577
+ case AgUiEventType.TOOL_CALL_ARGS: {
3578
+ const tc = toolCalls.get(event.toolCallId);
3579
+ if (tc) {
3580
+ tc.args += event.delta;
3581
+ }
3582
+ break;
3583
+ }
3584
+ case AgUiEventType.TOOL_CALL_END: {
3585
+ const tc = toolCalls.get(event.toolCallId);
3586
+ if (tc && onToolCallRef.current) {
3587
+ try {
3588
+ await onToolCallRef.current({
3589
+ toolCallId: event.toolCallId,
3590
+ toolCallName: tc.name,
3591
+ args: tc.args
3592
+ });
3593
+ } catch {
3594
+ }
3595
+ }
3596
+ toolCalls.delete(event.toolCallId);
3597
+ break;
3598
+ }
3599
+ case AgUiEventType.RUN_ERROR: {
3600
+ const err = new Error(event.message);
3601
+ (_e = onErrorRef.current) == null ? void 0 : _e.call(onErrorRef, err);
3602
+ break;
3603
+ }
3604
+ case AgUiEventType.RUN_FINISHED: {
3605
+ break;
3606
+ }
3607
+ }
3608
+ }
3609
+ } catch (err) {
3610
+ if (err instanceof DOMException && err.name === "AbortError") {
3611
+ return;
3612
+ }
3613
+ const error = err instanceof Error ? err : new Error(String(err));
3614
+ (_f = onErrorRef.current) == null ? void 0 : _f.call(onErrorRef, error);
3615
+ } finally {
3616
+ if (abortRef.current === abortController) {
3617
+ abortRef.current = null;
3618
+ }
3619
+ setIsLoading(false);
3620
+ }
3621
+ },
3622
+ [activeSessionId, agent, context, forwardedProps, headers, sessions, tools]
3623
+ );
3624
+ return {
3625
+ sessions,
3626
+ activeSessionId,
3627
+ isLoading,
3628
+ selectSession,
3629
+ deleteSession,
3630
+ createSession,
3631
+ sendMessage,
3632
+ stopMessage
3633
+ };
3634
+ }
4317
3635
  export {
4318
- ChartError as A,
4319
- validateChartData as B,
4320
- ChatInput as C,
4321
- parseChartConfig as D,
4322
- isChartClassName as E,
3636
+ remarkRedact as $,
3637
+ AgUiEventType as A,
3638
+ SessionMessages as B,
3639
+ ChartError as C,
3640
+ SessionMessagesHeader as D,
3641
+ SessionsGroup as E,
4323
3642
  FileInput as F,
4324
- getChildText as G,
4325
- remarkCve as H,
4326
- remarkChart as I,
4327
- dark as J,
4328
- light as K,
4329
- ChatContext as L,
4330
- MentionList as M,
3643
+ SessionsList as G,
3644
+ StatusIcon as H,
3645
+ TableDataCell as I,
3646
+ TableHeaderCell as J,
3647
+ bitcoinMatcher as K,
3648
+ chartComponents as L,
3649
+ Markdown as M,
4331
3650
  NewSessionButton as N,
4332
- AppBar as O,
4333
- ChatBubble as P,
4334
- ChatSuggestions as Q,
3651
+ chatTheme as O,
3652
+ commonRedactMatchers as P,
3653
+ creditCardMatcher as Q,
4335
3654
  RichTextInput as R,
4336
3655
  SvgFile as S,
4337
3656
  TableComponent as T,
4338
- ChatSuggestion as U,
4339
- MessageStatus as V,
4340
- MessageStatusItem as W,
4341
- StatusIcon as X,
3657
+ dark as U,
3658
+ getChildText as V,
3659
+ isChartClassName as W,
3660
+ light as X,
3661
+ parseChartConfig as Y,
3662
+ remarkChart as Z,
3663
+ remarkCve as _,
4342
3664
  SvgCopy as a,
4343
- SessionEmpty as b,
4344
- SessionMessagesHeader as c,
4345
- SessionMessagePanel as d,
4346
- SessionMessage as e,
4347
- MessageSource as f,
4348
- MessageActions as g,
4349
- MessageFile as h,
4350
- MessageFiles as i,
4351
- MessageQuestion as j,
4352
- MessageResponse as k,
4353
- MessageSources as l,
4354
- SessionMessages as m,
4355
- Chat as n,
4356
- SessionsList as o,
4357
- SessionListItem as p,
4358
- SessionGroups as q,
4359
- SessionsGroup as r,
4360
- chatTheme as s,
4361
- Markdown as t,
4362
- TableHeaderCell as u,
4363
- TableDataCell as v,
4364
- CodeHighlighter as w,
4365
- chartComponents as x,
4366
- ChartRenderer as y,
4367
- ChartPre as z
3665
+ ssnMatcher as a0,
3666
+ useAgUi as a1,
3667
+ validateChartData as a2,
3668
+ AppBar as b,
3669
+ ChartPre as c,
3670
+ ChartRenderer as d,
3671
+ Chat as e,
3672
+ ChatBubble as f,
3673
+ ChatContext as g,
3674
+ ChatInput as h,
3675
+ ChatSuggestion as i,
3676
+ ChatSuggestions as j,
3677
+ CodeHighlighter as k,
3678
+ MentionList as l,
3679
+ MessageActions as m,
3680
+ MessageFile as n,
3681
+ MessageFiles as o,
3682
+ MessageQuestion as p,
3683
+ MessageResponse as q,
3684
+ MessageSource as r,
3685
+ MessageSources as s,
3686
+ MessageStatus as t,
3687
+ MessageStatusItem as u,
3688
+ SessionEmpty as v,
3689
+ SessionGroups as w,
3690
+ SessionListItem as x,
3691
+ SessionMessage as y,
3692
+ SessionMessagePanel as z
4368
3693
  };
4369
- //# sourceMappingURL=index-CBHNcMyR.js.map
3694
+ //# sourceMappingURL=index-DdRyk11n.js.map