@langchain/macaw-components 1.7.10 → 1.7.12

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.
@@ -10,8 +10,21 @@ export interface ChatConversationProps {
10
10
  label?: string;
11
11
  className?: string;
12
12
  /**
13
- * The scrolling element. Older messages inserted above the viewport are not
14
- * anchored; hosts that load history upward can adjust `scrollTop` here.
13
+ * `bottom` (default) keeps the newest content in view while the reader is at
14
+ * the bottom. `none` never scrolls on its own; Jump to latest still appears.
15
+ */
16
+ follow?: 'bottom' | 'none';
17
+ /**
18
+ * ID of a message to bring to the top, usually the one just sent. Each new ID
19
+ * scrolls it up once and reserves space below for the reply. Following
20
+ * resumes at the bottom or on Jump to latest. Matches `data-chat-message-id`,
21
+ * which `ChatMessage` sets.
22
+ */
23
+ pinnedMessageId?: string;
24
+ /**
25
+ * The scrolling element, for hosts that track or restore the reading
26
+ * position. Content inserted above the first visible message, such as older
27
+ * messages, keeps that message in place.
15
28
  */
16
29
  viewportRef?: Ref<HTMLDivElement>;
17
30
  }
@@ -23,4 +36,4 @@ export interface ChatConversationProps {
23
36
  * text would be read out word by word. Announce completed replies from a
24
37
  * polite `role="status"` region in the host.
25
38
  */
26
- export declare function ChatConversation({ children, header, footer, label, className, viewportRef: externalViewportRef, }: ChatConversationProps): import("react").JSX.Element;
39
+ export declare function ChatConversation({ children, header, footer, label, className, follow, pinnedMessageId, viewportRef: externalViewportRef, }: ChatConversationProps): import("react").JSX.Element;
@@ -7,8 +7,14 @@ import { jsx, jsxs } from "react/jsx-runtime";
7
7
  //#region packages/components/src/components/ChatConversation/ChatConversation.tsx
8
8
  /** Distance from the bottom, in px, that still counts as reading the latest output. */
9
9
  var FOLLOW_THRESHOLD = 48;
10
+ var MESSAGE_ID_ATTRIBUTE = "data-chat-message-id";
11
+ var MESSAGE_SELECTOR = `[${MESSAGE_ID_ATTRIBUTE}]`;
10
12
  var COLUMN_CLASS_NAME = "mx-auto w-full min-w-0 max-w-3xl px-space-4";
11
- var VIEWPORT_MASK_STYLE = { "--scroll-mask-fade-from-t": "calc(100% - 2rem)" };
13
+ var TOP_FADE = "2rem";
14
+ var VIEWPORT_STYLE = {
15
+ "--scroll-mask-fade-from-t": `calc(100% - ${TOP_FADE})`,
16
+ scrollPaddingTop: TOP_FADE
17
+ };
12
18
  /**
13
19
  * Bounded-height chat layout that follows new output while the reader is at
14
20
  * the bottom. Remount with a conversation `key` when switching threads.
@@ -17,48 +23,34 @@ var VIEWPORT_MASK_STYLE = { "--scroll-mask-fade-from-t": "calc(100% - 2rem)" };
17
23
  * text would be read out word by word. Announce completed replies from a
18
24
  * polite `role="status"` region in the host.
19
25
  */
20
- function ChatConversation({ children, header, footer, label = "Conversation", className, viewportRef: externalViewportRef }) {
26
+ function ChatConversation({ children, header, footer, label = "Conversation", className, follow = "bottom", pinnedMessageId, viewportRef: externalViewportRef }) {
21
27
  const viewportRef = useRef(null);
22
28
  const contentRef = useRef(null);
23
- const followingRef = useRef(true);
24
- const [isNearBottom, setIsNearBottom] = useState(true);
29
+ const spacerRef = useRef(null);
30
+ const scrollRef = useRef(null);
31
+ const [showJump, setShowJump] = useState(false);
25
32
  const mergedViewportRef = useMemo(() => mergeRefs([viewportRef, externalViewportRef]), [externalViewportRef]);
26
33
  useLayoutEffect(() => {
27
34
  const viewport = viewportRef.current;
28
35
  const content = contentRef.current;
29
- if (!viewport || !content) return;
30
- const followContent = () => {
31
- if (!followingRef.current) return;
32
- viewport.scrollTop = viewport.scrollHeight;
33
- };
34
- let lastScrollTop = viewport.scrollTop;
35
- const handleScroll = () => {
36
- const { scrollTop, scrollHeight, clientHeight } = viewport;
37
- const nearBottom = scrollHeight - clientHeight - scrollTop <= FOLLOW_THRESHOLD;
38
- followingRef.current = nearBottom || followingRef.current && scrollTop >= lastScrollTop;
39
- lastScrollTop = scrollTop;
40
- setIsNearBottom(followingRef.current);
41
- };
42
- followContent();
43
- const observer = new ResizeObserver(() => {
44
- followContent();
45
- handleScroll();
46
- });
47
- observer.observe(viewport);
48
- observer.observe(content);
49
- viewport.addEventListener("scroll", handleScroll, { passive: true });
36
+ const spacer = spacerRef.current;
37
+ if (!viewport || !content || !spacer) return;
38
+ const scroll = connectConversationScroll(viewport, content, spacer, setShowJump);
39
+ scrollRef.current = scroll;
50
40
  return () => {
51
- observer.disconnect();
52
- viewport.removeEventListener("scroll", handleScroll);
41
+ scroll.disconnect();
42
+ scrollRef.current = null;
53
43
  };
54
44
  }, []);
55
- function scrollToLatest() {
56
- const viewport = viewportRef.current;
57
- if (!viewport) return;
58
- followingRef.current = true;
59
- viewport.scrollTop = viewport.scrollHeight;
60
- setIsNearBottom(true);
61
- viewport.focus({ preventScroll: true });
45
+ useLayoutEffect(() => {
46
+ scrollRef.current?.setFollow(follow);
47
+ }, [follow]);
48
+ useLayoutEffect(() => {
49
+ if (pinnedMessageId !== void 0) scrollRef.current?.pin(pinnedMessageId);
50
+ }, [pinnedMessageId]);
51
+ function jumpToLatest() {
52
+ scrollRef.current?.jumpToLatest();
53
+ viewportRef.current?.focus({ preventScroll: true });
62
54
  }
63
55
  return /* @__PURE__ */ jsxs("section", {
64
56
  "aria-label": label,
@@ -71,32 +63,35 @@ function ChatConversation({ children, header, footer, label = "Conversation", cl
71
63
  /* @__PURE__ */ jsxs("div", {
72
64
  className: "relative flex min-h-0 flex-1 flex-col",
73
65
  children: [
74
- /* @__PURE__ */ jsx("div", {
66
+ /* @__PURE__ */ jsxs("div", {
75
67
  ref: mergedViewportRef,
76
68
  role: "log",
77
69
  "aria-label": `${label} messages`,
78
70
  "aria-live": "off",
79
71
  tabIndex: 0,
80
- style: VIEWPORT_MASK_STYLE,
81
- className: "peer scroll-mask-t min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain outline-hidden [scrollbar-gutter:stable_both-edges]",
82
- children: /* @__PURE__ */ jsx("div", {
72
+ style: VIEWPORT_STYLE,
73
+ className: "peer scroll-mask-t min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain outline-hidden [overflow-anchor:none] [scrollbar-gutter:stable_both-edges]",
74
+ children: [/* @__PURE__ */ jsx("div", {
83
75
  ref: contentRef,
84
76
  className: cn(COLUMN_CLASS_NAME, "flex min-h-full flex-col gap-space-6 py-space-5 pb-space-9"),
85
77
  children
86
- })
78
+ }), /* @__PURE__ */ jsx("div", {
79
+ ref: spacerRef,
80
+ "aria-hidden": "true"
81
+ })]
87
82
  }),
88
83
  /* @__PURE__ */ jsx("div", {
89
84
  "aria-hidden": true,
90
85
  className: "pointer-events-none absolute inset-0 ring-inset ring-focus peer-focus-visible:ring-2"
91
86
  }),
92
- !isNearBottom && /* @__PURE__ */ jsx("div", {
87
+ showJump && /* @__PURE__ */ jsx("div", {
93
88
  className: "pointer-events-none absolute inset-x-0 bottom-0 flex justify-center pb-space-3",
94
89
  children: /* @__PURE__ */ jsx(Button, {
95
90
  color: "secondary",
96
91
  size: "md",
97
92
  leftDecorator: CaretDownIcon,
98
93
  className: "pointer-events-auto shadow-md hover:bg-elevated pointer-coarse:h-11",
99
- onClick: scrollToLatest,
94
+ onClick: jumpToLatest,
100
95
  children: "Jump to latest"
101
96
  })
102
97
  })
@@ -109,6 +104,179 @@ function ChatConversation({ children, header, footer, label = "Conversation", cl
109
104
  ]
110
105
  });
111
106
  }
107
+ /**
108
+ * Owns the log's scroll position: following the bottom, holding a pinned
109
+ * message at the top, and keeping the reader's place when content above it
110
+ * changes size. Every scroll it makes is instant.
111
+ */
112
+ function connectConversationScroll(viewport, content, spacer, onShowJumpChange) {
113
+ let follow;
114
+ /** Scroll to the bottom whenever the content or viewport resizes. */
115
+ let following = false;
116
+ let lastScrollTop = viewport.scrollTop;
117
+ let spacerHeight = 0;
118
+ /** A pin whose message hasn't rendered yet. */
119
+ let pendingPinId;
120
+ let pinnedId;
121
+ let pinned = null;
122
+ /** Keeps the pinned message at the top until the reader scrolls. */
123
+ let holdingPin = false;
124
+ /** The first visible message and its offset within the scrolled content. */
125
+ let anchor = null;
126
+ /** Keeps a pinned message clear of the top fade. */
127
+ const pinInset = parseFloat(getComputedStyle(viewport).scrollPaddingTop) || 0;
128
+ function offsetTop(element) {
129
+ return element.getBoundingClientRect().top - viewport.getBoundingClientRect().top + viewport.scrollTop;
130
+ }
131
+ /** Distance from the viewport's bottom edge to the end of the content, not counting the spacer. */
132
+ function distanceToEnd() {
133
+ return viewport.scrollHeight - spacerHeight - viewport.clientHeight - viewport.scrollTop;
134
+ }
135
+ function findMessage(id) {
136
+ return content.querySelector(`[${MESSAGE_ID_ATTRIBUTE}="${CSS.escape(id)}"]`);
137
+ }
138
+ function isVisible(element, viewportTop) {
139
+ const rect = element.getBoundingClientRect();
140
+ return rect.height > 0 && rect.bottom > viewportTop;
141
+ }
142
+ function firstVisible(viewportTop) {
143
+ const messages = content.querySelectorAll(MESSAGE_SELECTOR);
144
+ for (const element of messages.length > 0 ? messages : content.children) if (isVisible(element, viewportTop)) return element;
145
+ return null;
146
+ }
147
+ function setSpacer(height) {
148
+ if (height === spacerHeight) return;
149
+ spacerHeight = height;
150
+ spacer.style.height = height > 0 ? `${height}px` : "";
151
+ }
152
+ function tryPendingPin() {
153
+ if (pendingPinId === void 0) return;
154
+ const element = findMessage(pendingPinId);
155
+ if (!element) return;
156
+ pinnedId = pendingPinId;
157
+ pinned = element;
158
+ pendingPinId = void 0;
159
+ holdingPin = true;
160
+ following = false;
161
+ pendingPinObserver.disconnect();
162
+ }
163
+ function unpin() {
164
+ pinnedId = void 0;
165
+ pinned = null;
166
+ holdingPin = false;
167
+ setSpacer(0);
168
+ }
169
+ /**
170
+ * Sizes the spacer so the pinned message can reach the top of the viewport,
171
+ * and holds it there until the reader scrolls. The spacer shrinks as the
172
+ * reply grows and is gone once the reply fills the viewport.
173
+ */
174
+ function layoutPin() {
175
+ if (pinnedId === void 0) return;
176
+ if (!pinned?.isConnected || pinned.getAttribute(MESSAGE_ID_ATTRIBUTE) !== pinnedId) pinned = findMessage(pinnedId);
177
+ if (!pinned) {
178
+ unpin();
179
+ following = follow === "bottom" && distanceToEnd() <= FOLLOW_THRESHOLD;
180
+ return;
181
+ }
182
+ const target = Math.max(0, offsetTop(pinned) - pinInset);
183
+ const contentHeight = viewport.scrollHeight - spacerHeight;
184
+ setSpacer(Math.max(0, Math.ceil(target + viewport.clientHeight - contentHeight)));
185
+ if (holdingPin) viewport.scrollTop = target;
186
+ }
187
+ /** Moves with content that changed size above the first visible message. */
188
+ function restoreAnchor() {
189
+ if (!anchor?.element.isConnected) return;
190
+ const shift = offsetTop(anchor.element) - anchor.top;
191
+ if (Math.abs(shift) >= 1) viewport.scrollTop += shift;
192
+ }
193
+ function snapshotAnchor(rescan) {
194
+ if (following) {
195
+ anchor = null;
196
+ return;
197
+ }
198
+ const viewportTop = viewport.getBoundingClientRect().top;
199
+ let element = rescan ? null : anchor?.element;
200
+ if (!element?.isConnected || !isVisible(element, viewportTop)) element = firstVisible(viewportTop);
201
+ anchor = element ? {
202
+ element,
203
+ top: offsetTop(element)
204
+ } : null;
205
+ }
206
+ /**
207
+ * Records where the reader is after a scroll event, a resize, or a
208
+ * reposition the component made itself. Only a scroll event can be the
209
+ * reader's own movement: `lastScrollTop` is synced after every scroll the
210
+ * component makes, so the events those scrolls fire read as no movement.
211
+ */
212
+ function update(source) {
213
+ const { scrollTop } = viewport;
214
+ const atEnd = distanceToEnd() <= FOLLOW_THRESHOLD;
215
+ const clamped = scrollTop < lastScrollTop && viewport.scrollHeight - viewport.clientHeight - scrollTop <= 1;
216
+ if (pinnedId !== void 0) {
217
+ if (source === "scroll" && scrollTop !== lastScrollTop && !clamped) {
218
+ holdingPin = false;
219
+ if (scrollTop > lastScrollTop && atEnd && spacerHeight === 0) {
220
+ unpin();
221
+ following = follow === "bottom";
222
+ }
223
+ }
224
+ } else if (follow === "bottom") following = atEnd || following && scrollTop >= lastScrollTop;
225
+ lastScrollTop = scrollTop;
226
+ onShowJumpChange(!following && !atEnd);
227
+ snapshotAnchor(source !== "resize");
228
+ }
229
+ const handleScroll = () => update("scroll");
230
+ function relayout() {
231
+ tryPendingPin();
232
+ layoutPin();
233
+ if (following) viewport.scrollTop = viewport.scrollHeight;
234
+ else if (!holdingPin) restoreAnchor();
235
+ update("resize");
236
+ }
237
+ const observer = new ResizeObserver(relayout);
238
+ const pendingPinObserver = new MutationObserver(() => {
239
+ if (pendingPinId !== void 0 && findMessage(pendingPinId)) relayout();
240
+ });
241
+ observer.observe(viewport);
242
+ observer.observe(content);
243
+ viewport.addEventListener("scroll", handleScroll, { passive: true });
244
+ return {
245
+ setFollow(nextFollow) {
246
+ const isFirst = follow === void 0;
247
+ follow = nextFollow;
248
+ if (pinnedId === void 0) {
249
+ following = nextFollow === "bottom" && (isFirst || distanceToEnd() <= FOLLOW_THRESHOLD);
250
+ if (following) viewport.scrollTop = viewport.scrollHeight;
251
+ }
252
+ update("reposition");
253
+ },
254
+ pin(id) {
255
+ pendingPinId = id;
256
+ tryPendingPin();
257
+ if (pendingPinId !== void 0) pendingPinObserver.observe(content, {
258
+ childList: true,
259
+ subtree: true
260
+ });
261
+ layoutPin();
262
+ update("reposition");
263
+ },
264
+ jumpToLatest() {
265
+ pendingPinId = void 0;
266
+ pendingPinObserver.disconnect();
267
+ unpin();
268
+ following = follow === "bottom";
269
+ viewport.scrollTop = viewport.scrollHeight;
270
+ update("reposition");
271
+ },
272
+ disconnect() {
273
+ observer.disconnect();
274
+ pendingPinObserver.disconnect();
275
+ viewport.removeEventListener("scroll", handleScroll);
276
+ setSpacer(0);
277
+ }
278
+ };
279
+ }
112
280
  //#endregion
113
281
  export { ChatConversation };
114
282
 
@@ -1 +1 @@
1
- {"version":3,"file":"ChatConversation.js","names":[],"sources":["../../../src/components/ChatConversation/ChatConversation.tsx"],"sourcesContent":["import {\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n type Ref,\n} from 'react';\n\nimport { CaretDownIcon } from '@phosphor-icons/react/dist/ssr/CaretDown';\n\nimport { cn } from '../../utils/cn';\nimport { mergeRefs } from '../../utils/merge-refs';\nimport { Button } from '../Button';\n\n/** Distance from the bottom, in px, that still counts as reading the latest output. */\nconst FOLLOW_THRESHOLD = 48;\n\nconst COLUMN_CLASS_NAME = 'mx-auto w-full min-w-0 max-w-3xl px-space-4';\n\n// Caps the top fade at 32px. Inline because the unlayered `.scroll-mask-t`\n// rule in base.css overrides utility classes.\nconst VIEWPORT_MASK_STYLE = {\n '--scroll-mask-fade-from-t': 'calc(100% - 2rem)',\n} as CSSProperties;\n\nexport interface ChatConversationProps {\n /** Messages, or a host-provided empty or loading state. */\n children: ReactNode;\n /** Fixed content above the scrolling messages; the host supplies its styling. */\n header?: ReactNode;\n /** Fixed content below the messages, such as a composer. Shares the message column. */\n footer?: ReactNode;\n /** Accessible name for the region; the message log is named \"{label} messages\". */\n label?: string;\n className?: string;\n /**\n * The scrolling element. Older messages inserted above the viewport are not\n * anchored; hosts that load history upward can adjust `scrollTop` here.\n */\n viewportRef?: Ref<HTMLDivElement>;\n}\n\n/**\n * Bounded-height chat layout that follows new output while the reader is at\n * the bottom. Remount with a conversation `key` when switching threads.\n *\n * The message log doesn't announce changes (`aria-live=\"off\"`), since streamed\n * text would be read out word by word. Announce completed replies from a\n * polite `role=\"status\"` region in the host.\n */\nexport function ChatConversation({\n children,\n header,\n footer,\n label = 'Conversation',\n className,\n viewportRef: externalViewportRef,\n}: ChatConversationProps) {\n const viewportRef = useRef<HTMLDivElement>(null);\n const contentRef = useRef<HTMLDivElement>(null);\n const followingRef = useRef(true);\n const [isNearBottom, setIsNearBottom] = useState(true);\n const mergedViewportRef = useMemo(\n () => mergeRefs([viewportRef, externalViewportRef]),\n [externalViewportRef]\n );\n\n useLayoutEffect(() => {\n const viewport = viewportRef.current;\n const content = contentRef.current;\n if (!viewport || !content) return;\n\n const followContent = () => {\n if (!followingRef.current) return;\n viewport.scrollTop = viewport.scrollHeight;\n };\n\n let lastScrollTop = viewport.scrollTop;\n const handleScroll = () => {\n const { scrollTop, scrollHeight, clientHeight } = viewport;\n const nearBottom =\n scrollHeight - clientHeight - scrollTop <= FOLLOW_THRESHOLD;\n // Only scrolling up stops following. The scroll event from our own pin\n // can land after more content arrives, leaving a gap the reader didn't make.\n followingRef.current =\n nearBottom || (followingRef.current && scrollTop >= lastScrollTop);\n lastScrollTop = scrollTop;\n setIsNearBottom(followingRef.current);\n };\n\n followContent();\n const observer = new ResizeObserver(() => {\n followContent();\n handleScroll();\n });\n observer.observe(viewport);\n observer.observe(content);\n viewport.addEventListener('scroll', handleScroll, { passive: true });\n return () => {\n observer.disconnect();\n viewport.removeEventListener('scroll', handleScroll);\n };\n }, []);\n\n function scrollToLatest() {\n const viewport = viewportRef.current;\n if (!viewport) return;\n followingRef.current = true;\n viewport.scrollTop = viewport.scrollHeight;\n setIsNearBottom(true);\n // The jump button disappears; keep keyboard focus in the reading region.\n viewport.focus({ preventScroll: true });\n }\n\n return (\n <section\n aria-label={label}\n className={cn(\n 'flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-surface-level-1 text-primary',\n className\n )}\n >\n {header != null && <div className=\"min-w-0 shrink-0\">{header}</div>}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n <div\n ref={mergedViewportRef}\n role=\"log\"\n aria-label={`${label} messages`}\n aria-live=\"off\"\n tabIndex={0}\n style={VIEWPORT_MASK_STYLE}\n className=\"peer scroll-mask-t min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain outline-hidden [scrollbar-gutter:stable_both-edges]\"\n >\n <div\n ref={contentRef}\n className={cn(\n COLUMN_CLASS_NAME,\n 'flex min-h-full flex-col gap-space-6 py-space-5 pb-space-9'\n )}\n >\n {children}\n </div>\n </div>\n {/* The focus ring sits on an overlay so the viewport's scroll mask can't fade it. */}\n <div\n aria-hidden\n className=\"pointer-events-none absolute inset-0 ring-inset ring-focus peer-focus-visible:ring-2\"\n />\n {!isNearBottom && (\n <div className=\"pointer-events-none absolute inset-x-0 bottom-0 flex justify-center pb-space-3\">\n <Button\n color=\"secondary\"\n size=\"md\"\n leftDecorator={CaretDownIcon}\n className=\"pointer-events-auto shadow-md hover:bg-elevated pointer-coarse:h-11\"\n onClick={scrollToLatest}\n >\n Jump to latest\n </Button>\n </div>\n )}\n </div>\n {footer != null && (\n <div className={cn(COLUMN_CLASS_NAME, 'shrink-0 py-space-3')}>\n {footer}\n </div>\n )}\n </section>\n );\n}\n"],"mappings":";;;;;;;;AAiBA,IAAM,mBAAmB;AAEzB,IAAM,oBAAoB;AAI1B,IAAM,sBAAsB,EAC1B,6BAA6B,oBAC/B;;;;;;;;;AA2BA,SAAgB,iBAAiB,EAC/B,UACA,QACA,QACA,QAAQ,gBACR,WACA,aAAa,uBACW;CACxB,MAAM,cAAc,OAAuB,IAAI;CAC/C,MAAM,aAAa,OAAuB,IAAI;CAC9C,MAAM,eAAe,OAAO,IAAI;CAChC,MAAM,CAAC,cAAc,mBAAmB,SAAS,IAAI;CACrD,MAAM,oBAAoB,cAClB,UAAU,CAAC,aAAa,mBAAmB,CAAC,GAClD,CAAC,mBAAmB,CACtB;CAEA,sBAAsB;EACpB,MAAM,WAAW,YAAY;EAC7B,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,YAAY,CAAC,SAAS;EAE3B,MAAM,sBAAsB;GAC1B,IAAI,CAAC,aAAa,SAAS;GAC3B,SAAS,YAAY,SAAS;EAChC;EAEA,IAAI,gBAAgB,SAAS;EAC7B,MAAM,qBAAqB;GACzB,MAAM,EAAE,WAAW,cAAc,iBAAiB;GAClD,MAAM,aACJ,eAAe,eAAe,aAAa;GAG7C,aAAa,UACX,cAAe,aAAa,WAAW,aAAa;GACtD,gBAAgB;GAChB,gBAAgB,aAAa,OAAO;EACtC;EAEA,cAAc;EACd,MAAM,WAAW,IAAI,qBAAqB;GACxC,cAAc;GACd,aAAa;EACf,CAAC;EACD,SAAS,QAAQ,QAAQ;EACzB,SAAS,QAAQ,OAAO;EACxB,SAAS,iBAAiB,UAAU,cAAc,EAAE,SAAS,KAAK,CAAC;EACnE,aAAa;GACX,SAAS,WAAW;GACpB,SAAS,oBAAoB,UAAU,YAAY;EACrD;CACF,GAAG,CAAC,CAAC;CAEL,SAAS,iBAAiB;EACxB,MAAM,WAAW,YAAY;EAC7B,IAAI,CAAC,UAAU;EACf,aAAa,UAAU;EACvB,SAAS,YAAY,SAAS;EAC9B,gBAAgB,IAAI;EAEpB,SAAS,MAAM,EAAE,eAAe,KAAK,CAAC;CACxC;CAEA,OACE,qBAAC,WAAD;EACE,cAAY;EACZ,WAAW,GACT,wFACA,SACF;EALF,UAAA;GAOG,UAAU,QAAQ,oBAAC,OAAD;IAAK,WAAU;IAAoB,UAAA;GAAY,CAAA;GAClE,qBAAC,OAAD;IAAK,WAAU;IAAf,UAAA;KACE,oBAAC,OAAD;MACE,KAAK;MACL,MAAK;MACL,cAAY,GAAG,MAAM;MACrB,aAAU;MACV,UAAU;MACV,OAAO;MACP,WAAU;MAEV,UAAA,oBAAC,OAAD;OACE,KAAK;OACL,WAAW,GACT,mBACA,4DACF;OAEC;MACE,CAAA;KACF,CAAA;KAEL,oBAAC,OAAD;MACE,eAAA;MACA,WAAU;KACX,CAAA;KACA,CAAC,gBACA,oBAAC,OAAD;MAAK,WAAU;MACb,UAAA,oBAAC,QAAD;OACE,OAAM;OACN,MAAK;OACL,eAAe;OACf,WAAU;OACV,SAAS;OACV,UAAA;MAEO,CAAA;KACL,CAAA;IAEJ;;GACJ,UAAU,QACT,oBAAC,OAAD;IAAK,WAAW,GAAG,mBAAmB,qBAAqB;IACxD,UAAA;GACE,CAAA;EAEA;;AAEb"}
1
+ {"version":3,"file":"ChatConversation.js","names":[],"sources":["../../../src/components/ChatConversation/ChatConversation.tsx"],"sourcesContent":["import {\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n type Ref,\n} from 'react';\n\nimport { CaretDownIcon } from '@phosphor-icons/react/dist/ssr/CaretDown';\n\nimport { cn } from '../../utils/cn';\nimport { mergeRefs } from '../../utils/merge-refs';\nimport { Button } from '../Button';\n\n/** Distance from the bottom, in px, that still counts as reading the latest output. */\nconst FOLLOW_THRESHOLD = 48;\n\nconst MESSAGE_ID_ATTRIBUTE = 'data-chat-message-id';\nconst MESSAGE_SELECTOR = `[${MESSAGE_ID_ATTRIBUTE}]`;\n\nconst COLUMN_CLASS_NAME = 'mx-auto w-full min-w-0 max-w-3xl px-space-4';\n\n// Caps the top fade at 32px. Inline because the unlayered `.scroll-mask-t`\n// rule in base.css overrides utility classes. The matching scroll padding\n// keeps a pinned message, or anything scrolled into view, clear of the fade.\nconst TOP_FADE = '2rem';\nconst VIEWPORT_STYLE = {\n '--scroll-mask-fade-from-t': `calc(100% - ${TOP_FADE})`,\n scrollPaddingTop: TOP_FADE,\n} as CSSProperties;\n\nexport interface ChatConversationProps {\n /** Messages, or a host-provided empty or loading state. */\n children: ReactNode;\n /** Fixed content above the scrolling messages; the host supplies its styling. */\n header?: ReactNode;\n /** Fixed content below the messages, such as a composer. Shares the message column. */\n footer?: ReactNode;\n /** Accessible name for the region; the message log is named \"{label} messages\". */\n label?: string;\n className?: string;\n /**\n * `bottom` (default) keeps the newest content in view while the reader is at\n * the bottom. `none` never scrolls on its own; Jump to latest still appears.\n */\n follow?: 'bottom' | 'none';\n /**\n * ID of a message to bring to the top, usually the one just sent. Each new ID\n * scrolls it up once and reserves space below for the reply. Following\n * resumes at the bottom or on Jump to latest. Matches `data-chat-message-id`,\n * which `ChatMessage` sets.\n */\n pinnedMessageId?: string;\n /**\n * The scrolling element, for hosts that track or restore the reading\n * position. Content inserted above the first visible message, such as older\n * messages, keeps that message in place.\n */\n viewportRef?: Ref<HTMLDivElement>;\n}\n\ntype Follow = NonNullable<ChatConversationProps['follow']>;\n\n/**\n * Bounded-height chat layout that follows new output while the reader is at\n * the bottom. Remount with a conversation `key` when switching threads.\n *\n * The message log doesn't announce changes (`aria-live=\"off\"`), since streamed\n * text would be read out word by word. Announce completed replies from a\n * polite `role=\"status\"` region in the host.\n */\nexport function ChatConversation({\n children,\n header,\n footer,\n label = 'Conversation',\n className,\n follow = 'bottom',\n pinnedMessageId,\n viewportRef: externalViewportRef,\n}: ChatConversationProps) {\n const viewportRef = useRef<HTMLDivElement>(null);\n const contentRef = useRef<HTMLDivElement>(null);\n const spacerRef = useRef<HTMLDivElement>(null);\n const scrollRef = useRef<ConversationScroll | null>(null);\n const [showJump, setShowJump] = useState(false);\n const mergedViewportRef = useMemo(\n () => mergeRefs([viewportRef, externalViewportRef]),\n [externalViewportRef]\n );\n\n // Declared before the follow and pin effects so they find it on mount.\n useLayoutEffect(() => {\n const viewport = viewportRef.current;\n const content = contentRef.current;\n const spacer = spacerRef.current;\n if (!viewport || !content || !spacer) return;\n\n const scroll = connectConversationScroll(\n viewport,\n content,\n spacer,\n setShowJump\n );\n scrollRef.current = scroll;\n return () => {\n scroll.disconnect();\n scrollRef.current = null;\n };\n }, []);\n\n useLayoutEffect(() => {\n scrollRef.current?.setFollow(follow);\n }, [follow]);\n\n useLayoutEffect(() => {\n if (pinnedMessageId !== undefined) scrollRef.current?.pin(pinnedMessageId);\n }, [pinnedMessageId]);\n\n function jumpToLatest() {\n scrollRef.current?.jumpToLatest();\n // The jump button disappears; keep keyboard focus in the reading region.\n viewportRef.current?.focus({ preventScroll: true });\n }\n\n return (\n <section\n aria-label={label}\n className={cn(\n 'flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-surface-level-1 text-primary',\n className\n )}\n >\n {header != null && <div className=\"min-w-0 shrink-0\">{header}</div>}\n <div className=\"relative flex min-h-0 flex-1 flex-col\">\n <div\n ref={mergedViewportRef}\n role=\"log\"\n aria-label={`${label} messages`}\n aria-live=\"off\"\n tabIndex={0}\n style={VIEWPORT_STYLE}\n // Native scroll anchoring would repeat the adjustment the component\n // makes for content inserted above, so it is turned off here.\n className=\"peer scroll-mask-t min-h-0 flex-1 overflow-y-auto overflow-x-hidden overscroll-contain outline-hidden [overflow-anchor:none] [scrollbar-gutter:stable_both-edges]\"\n >\n <div\n ref={contentRef}\n className={cn(\n COLUMN_CLASS_NAME,\n 'flex min-h-full flex-col gap-space-6 py-space-5 pb-space-9'\n )}\n >\n {children}\n </div>\n {/* Room for a pinned message to reach the top while its reply is short. */}\n <div ref={spacerRef} aria-hidden=\"true\" />\n </div>\n {/* The focus ring sits on an overlay so the viewport's scroll mask can't fade it. */}\n <div\n aria-hidden\n className=\"pointer-events-none absolute inset-0 ring-inset ring-focus peer-focus-visible:ring-2\"\n />\n {showJump && (\n <div className=\"pointer-events-none absolute inset-x-0 bottom-0 flex justify-center pb-space-3\">\n <Button\n color=\"secondary\"\n size=\"md\"\n leftDecorator={CaretDownIcon}\n className=\"pointer-events-auto shadow-md hover:bg-elevated pointer-coarse:h-11\"\n onClick={jumpToLatest}\n >\n Jump to latest\n </Button>\n </div>\n )}\n </div>\n {footer != null && (\n <div className={cn(COLUMN_CLASS_NAME, 'shrink-0 py-space-3')}>\n {footer}\n </div>\n )}\n </section>\n );\n}\n\ninterface ConversationScroll {\n /** Applies the follow mode; the first call also sets the starting position. */\n setFollow: (follow: Follow) => void;\n pin: (id: string) => void;\n jumpToLatest: () => void;\n disconnect: () => void;\n}\n\n/**\n * Owns the log's scroll position: following the bottom, holding a pinned\n * message at the top, and keeping the reader's place when content above it\n * changes size. Every scroll it makes is instant.\n */\nfunction connectConversationScroll(\n viewport: HTMLElement,\n content: HTMLElement,\n spacer: HTMLElement,\n onShowJumpChange: (showJump: boolean) => void\n): ConversationScroll {\n let follow: Follow | undefined;\n /** Scroll to the bottom whenever the content or viewport resizes. */\n let following = false;\n let lastScrollTop = viewport.scrollTop;\n let spacerHeight = 0;\n /** A pin whose message hasn't rendered yet. */\n let pendingPinId: string | undefined;\n let pinnedId: string | undefined;\n let pinned: Element | null = null;\n /** Keeps the pinned message at the top until the reader scrolls. */\n let holdingPin = false;\n /** The first visible message and its offset within the scrolled content. */\n let anchor: { element: Element; top: number } | null = null;\n /** Keeps a pinned message clear of the top fade. */\n const pinInset = parseFloat(getComputedStyle(viewport).scrollPaddingTop) || 0;\n\n function offsetTop(element: Element) {\n return (\n element.getBoundingClientRect().top -\n viewport.getBoundingClientRect().top +\n viewport.scrollTop\n );\n }\n\n /** Distance from the viewport's bottom edge to the end of the content, not counting the spacer. */\n function distanceToEnd() {\n return (\n viewport.scrollHeight -\n spacerHeight -\n viewport.clientHeight -\n viewport.scrollTop\n );\n }\n\n function findMessage(id: string) {\n return content.querySelector(\n `[${MESSAGE_ID_ATTRIBUTE}=\"${CSS.escape(id)}\"]`\n );\n }\n\n function isVisible(element: Element, viewportTop: number) {\n const rect = element.getBoundingClientRect();\n return rect.height > 0 && rect.bottom > viewportTop;\n }\n\n function firstVisible(viewportTop: number) {\n const messages = content.querySelectorAll(MESSAGE_SELECTOR);\n for (const element of messages.length > 0 ? messages : content.children) {\n if (isVisible(element, viewportTop)) return element;\n }\n return null;\n }\n\n function setSpacer(height: number) {\n if (height === spacerHeight) return;\n spacerHeight = height;\n spacer.style.height = height > 0 ? `${height}px` : '';\n }\n\n function tryPendingPin() {\n if (pendingPinId === undefined) return;\n const element = findMessage(pendingPinId);\n if (!element) return;\n pinnedId = pendingPinId;\n pinned = element;\n pendingPinId = undefined;\n holdingPin = true;\n following = false;\n pendingPinObserver.disconnect();\n }\n\n function unpin() {\n pinnedId = undefined;\n pinned = null;\n holdingPin = false;\n setSpacer(0);\n }\n\n /**\n * Sizes the spacer so the pinned message can reach the top of the viewport,\n * and holds it there until the reader scrolls. The spacer shrinks as the\n * reply grows and is gone once the reply fills the viewport.\n */\n function layoutPin() {\n if (pinnedId === undefined) return;\n if (\n !pinned?.isConnected ||\n pinned.getAttribute(MESSAGE_ID_ATTRIBUTE) !== pinnedId\n ) {\n pinned = findMessage(pinnedId);\n }\n if (!pinned) {\n // The message was removed, so there is nothing left to hold in place.\n unpin();\n following = follow === 'bottom' && distanceToEnd() <= FOLLOW_THRESHOLD;\n return;\n }\n const target = Math.max(0, offsetTop(pinned) - pinInset);\n const contentHeight = viewport.scrollHeight - spacerHeight;\n setSpacer(\n Math.max(0, Math.ceil(target + viewport.clientHeight - contentHeight))\n );\n if (holdingPin) viewport.scrollTop = target;\n }\n\n /** Moves with content that changed size above the first visible message. */\n function restoreAnchor() {\n if (!anchor?.element.isConnected) return;\n const shift = offsetTop(anchor.element) - anchor.top;\n if (Math.abs(shift) >= 1) viewport.scrollTop += shift;\n }\n\n function snapshotAnchor(rescan: boolean) {\n if (following) {\n anchor = null;\n return;\n }\n const viewportTop = viewport.getBoundingClientRect().top;\n let element = rescan ? null : anchor?.element;\n if (!element?.isConnected || !isVisible(element, viewportTop)) {\n element = firstVisible(viewportTop);\n }\n anchor = element ? { element, top: offsetTop(element) } : null;\n }\n\n /**\n * Records where the reader is after a scroll event, a resize, or a\n * reposition the component made itself. Only a scroll event can be the\n * reader's own movement: `lastScrollTop` is synced after every scroll the\n * component makes, so the events those scrolls fire read as no movement.\n */\n function update(source: 'scroll' | 'resize' | 'reposition') {\n const { scrollTop } = viewport;\n const atEnd = distanceToEnd() <= FOLLOW_THRESHOLD;\n // When content below shrinks, the browser pulls scrollTop back to the new\n // end before the spacer can grow; that isn't the reader scrolling.\n const clamped =\n scrollTop < lastScrollTop &&\n viewport.scrollHeight - viewport.clientHeight - scrollTop <= 1;\n if (pinnedId !== undefined) {\n if (source === 'scroll' && scrollTop !== lastScrollTop && !clamped) {\n holdingPin = false;\n // Scrolling down to the end of a reply that outgrew the viewport\n // hands back to bottom-following.\n if (scrollTop > lastScrollTop && atEnd && spacerHeight === 0) {\n unpin();\n following = follow === 'bottom';\n }\n }\n } else if (follow === 'bottom') {\n // Only scrolling up stops following. The scroll event from our own\n // scroll to the bottom can land after more content arrives, leaving a\n // gap the reader didn't make.\n following = atEnd || (following && scrollTop >= lastScrollTop);\n }\n lastScrollTop = scrollTop;\n onShowJumpChange(!following && !atEnd);\n snapshotAnchor(source !== 'resize');\n }\n\n const handleScroll = () => update('scroll');\n\n function relayout() {\n tryPendingPin();\n layoutPin();\n if (following) viewport.scrollTop = viewport.scrollHeight;\n else if (!holdingPin) restoreAnchor();\n update('resize');\n }\n\n const observer = new ResizeObserver(relayout);\n // While the content is shorter than the viewport, `min-h-full` keeps its\n // size fixed, so a newly rendered message doesn't trigger a resize.\n const pendingPinObserver = new MutationObserver(() => {\n if (pendingPinId !== undefined && findMessage(pendingPinId)) relayout();\n });\n observer.observe(viewport);\n observer.observe(content);\n viewport.addEventListener('scroll', handleScroll, { passive: true });\n\n return {\n setFollow(nextFollow) {\n const isFirst = follow === undefined;\n follow = nextFollow;\n if (pinnedId === undefined) {\n following =\n nextFollow === 'bottom' &&\n (isFirst || distanceToEnd() <= FOLLOW_THRESHOLD);\n if (following) viewport.scrollTop = viewport.scrollHeight;\n }\n update('reposition');\n },\n pin(id) {\n pendingPinId = id;\n tryPendingPin();\n if (pendingPinId !== undefined) {\n pendingPinObserver.observe(content, { childList: true, subtree: true });\n }\n layoutPin();\n update('reposition');\n },\n jumpToLatest() {\n pendingPinId = undefined;\n pendingPinObserver.disconnect();\n unpin();\n following = follow === 'bottom';\n viewport.scrollTop = viewport.scrollHeight;\n update('reposition');\n },\n disconnect() {\n observer.disconnect();\n pendingPinObserver.disconnect();\n viewport.removeEventListener('scroll', handleScroll);\n setSpacer(0);\n },\n };\n}\n"],"mappings":";;;;;;;;AAiBA,IAAM,mBAAmB;AAEzB,IAAM,uBAAuB;AAC7B,IAAM,mBAAmB,IAAI,qBAAqB;AAElD,IAAM,oBAAoB;AAK1B,IAAM,WAAW;AACjB,IAAM,iBAAiB;CACrB,6BAA6B,eAAe,SAAS;CACrD,kBAAkB;AACpB;;;;;;;;;AA0CA,SAAgB,iBAAiB,EAC/B,UACA,QACA,QACA,QAAQ,gBACR,WACA,SAAS,UACT,iBACA,aAAa,uBACW;CACxB,MAAM,cAAc,OAAuB,IAAI;CAC/C,MAAM,aAAa,OAAuB,IAAI;CAC9C,MAAM,YAAY,OAAuB,IAAI;CAC7C,MAAM,YAAY,OAAkC,IAAI;CACxD,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AS;GAC9B,OAAO,YAAY;EACrB;EACA,aAAa;GACX,SAAS,WAAW;GACpB,mBAAmB,WAAW;GAC9B,SAAS,oBAAoB,UAAU,YAAY;GACnD,UAAU,CAAC;EACb;CACF;AACF"}
@@ -27,7 +27,9 @@ export interface ChatMessageProps extends ComponentPropsWithRef<'div'> {
27
27
  /**
28
28
  * One message in a conversation. Renders a header and the message's content
29
29
  * blocks, or `children` in their place for custom layouts. The footer is
30
- * hidden, but keeps its space, while the message streams.
30
+ * hidden, but keeps its space, while the message streams. The root carries
31
+ * `data-chat-message-id`, which `ChatConversation` uses to pin a message and
32
+ * to hold the reader's place when earlier messages load.
31
33
  */
32
34
  export declare function ChatMessage({ message, footer, avatar, name, align, isLatest, animateParagraphs, className, contentClassName, children, ...props }: ChatMessageProps): import("react").JSX.Element;
33
35
  export interface ChatMessageHeaderProps extends ComponentPropsWithRef<'div'> {
@@ -43,7 +43,9 @@ var settledStatuses = /* @__PURE__ */ new Set([
43
43
  /**
44
44
  * One message in a conversation. Renders a header and the message's content
45
45
  * blocks, or `children` in their place for custom layouts. The footer is
46
- * hidden, but keeps its space, while the message streams.
46
+ * hidden, but keeps its space, while the message streams. The root carries
47
+ * `data-chat-message-id`, which `ChatConversation` uses to pin a message and
48
+ * to hold the reader's place when earlier messages load.
47
49
  */
48
50
  function ChatMessage({ message, footer, avatar, name, align, isLatest = false, animateParagraphs = false, className, contentClassName, children, ...props }) {
49
51
  const alignment = align ?? (message.role === "user" ? "end" : "start");
@@ -55,6 +57,7 @@ function ChatMessage({ message, footer, avatar, name, align, isLatest = false, a
55
57
  role: "article",
56
58
  "aria-label": `${typeof name === "string" ? name : avatar?.label || roleLabels[message.role]} message`,
57
59
  "aria-busy": isStreaming || message.status === "submitting",
60
+ "data-chat-message-id": message.id,
58
61
  className: cn("group/chat-message flex w-full min-w-0 text-primary", alignment === "end" && "justify-end", className),
59
62
  ...props,
60
63
  children: /* @__PURE__ */ jsxs("div", {
@@ -1 +1 @@
1
- {"version":3,"file":"ChatMessage.js","names":[],"sources":["../../../src/components/ChatMessage/ChatMessage.tsx"],"sourcesContent":["import {\n createContext,\n Fragment,\n useContext,\n useState,\n type ComponentPropsWithRef,\n type ReactNode,\n} from 'react';\n\nimport { ArrowClockwiseIcon } from '@phosphor-icons/react/dist/ssr/ArrowClockwise';\nimport { CopySimpleIcon } from '@phosphor-icons/react/dist/ssr/CopySimple';\nimport { PencilSimpleIcon } from '@phosphor-icons/react/dist/ssr/PencilSimple';\nimport { WarningCircleIcon } from '@phosphor-icons/react/dist/ssr/WarningCircle';\nimport { XIcon } from '@phosphor-icons/react/dist/ssr/X';\n\nimport { cn } from '../../utils/cn';\nimport type { IconComponent } from '../../utils/icon-types';\nimport { Avatar, type AvatarProps } from '../Avatar';\nimport { Divider } from '../Divider';\nimport { Icon } from '../Icon';\nimport { IconButton } from '../IconButton';\nimport { Text } from '../Text';\nimport { ThinkingState } from '../ThinkingState';\nimport type {\n ChatMessageActionCapabilities,\n ChatMessageContentBlock,\n ChatMessageModel,\n ChatMessageRole,\n ChatMessageStatus,\n} from './ChatMessage.types';\n\n/**\n * The message's alignment, so a host-supplied `ChatMessageBody` lines up its\n * blocks the same way the default body does.\n */\nconst ChatMessageAlignmentContext = createContext<'start' | 'end'>('start');\n\nconst roleLabels: Record<ChatMessageRole, string> = {\n user: 'User',\n assistant: 'Assistant',\n system: 'System',\n tool: 'Tool',\n};\n\nconst statusLabels: Record<ChatMessageStatus, string | null> = {\n idle: null,\n queued: 'Queued',\n submitting: 'Sending',\n streaming: 'Responding',\n interrupted: 'Interrupted',\n failed: 'Failed',\n stopped: 'Stopped',\n completed: null,\n};\n\nconst settledStatuses = new Set<ChatMessageStatus>([\n 'completed',\n 'failed',\n 'stopped',\n 'interrupted',\n]);\n\nexport interface ChatMessageProps extends ComponentPropsWithRef<'div'> {\n message: ChatMessageModel;\n /** Metadata and actions share the message's footer layout and visibility. */\n footer?: ReactNode;\n /** `Avatar` shown before the name in the default header, sized to match it. */\n avatar?: Omit<AvatarProps, 'size'>;\n /**\n * Name shown after the avatar in the default header. A string name also\n * labels the message for screen readers; otherwise the avatar's label or\n * the role label does.\n */\n name?: ReactNode;\n /** Defaults to end for user messages and start for other roles. */\n align?: 'start' | 'end';\n /** Keeps the footer visible; earlier messages reveal it on hover or focus. */\n isLatest?: boolean;\n /**\n * Fade in complete text blocks as they mount; keep their IDs stable. A\n * message that mounts already settled, such as history, doesn't fade in.\n */\n animateParagraphs?: boolean;\n contentClassName?: string;\n}\n\n/**\n * One message in a conversation. Renders a header and the message's content\n * blocks, or `children` in their place for custom layouts. The footer is\n * hidden, but keeps its space, while the message streams.\n */\nexport function ChatMessage({\n message,\n footer,\n avatar,\n name,\n align,\n isLatest = false,\n animateParagraphs = false,\n className,\n contentClassName,\n children,\n ...props\n}: ChatMessageProps) {\n const alignment = align ?? (message.role === 'user' ? 'end' : 'start');\n const isStreaming = message.status === 'streaming';\n const isSettled = settledStatuses.has(message.status);\n const [isHistory, setIsHistory] = useState(isSettled);\n if (isHistory && !isSettled) setIsHistory(false);\n\n return (\n <div\n role=\"article\"\n aria-label={`${typeof name === 'string' ? name : avatar?.label || roleLabels[message.role]} message`}\n aria-busy={isStreaming || message.status === 'submitting'}\n className={cn(\n 'group/chat-message flex w-full min-w-0 text-primary',\n alignment === 'end' && 'justify-end',\n className\n )}\n {...props}\n >\n <div\n className={cn(\n 'flex min-w-0 max-w-full flex-col gap-space-2',\n alignment === 'end' ? 'w-fit max-w-[85%] items-end' : 'w-full',\n contentClassName\n )}\n >\n <ChatMessageAlignmentContext.Provider value={alignment}>\n {children ?? (\n <>\n <ChatMessageHeader\n avatar={avatar}\n name={name}\n status={message.status}\n />\n <ChatMessageBody\n blocks={message.content}\n animateParagraphs={animateParagraphs && !isHistory}\n />\n </>\n )}\n </ChatMessageAlignmentContext.Provider>\n {footer != null && (\n <div\n // Reserve the footer's space while streaming so it doesn't pop in.\n inert={isStreaming}\n className={cn(\n 'flex min-w-0 max-w-full flex-wrap items-center gap-space-2 [overflow-wrap:anywhere]',\n isStreaming && 'invisible',\n // Earlier messages hide their footer until hovered or focused,\n // except on touch screens, which have no hover to reveal it.\n // Keyboard focus reveals it without a fade.\n !isLatest &&\n 'transition-opacity duration-fast focus-within:transition-none motion-reduce:transition-none pointer-fine:opacity-0 pointer-fine:focus-within:opacity-100 pointer-fine:group-hover/chat-message:opacity-100 pointer-fine:has-[[data-state=open]]:opacity-100'\n )}\n >\n {footer}\n </div>\n )}\n </div>\n </div>\n );\n}\n\nexport interface ChatMessageHeaderProps extends ComponentPropsWithRef<'div'> {\n avatar?: Omit<AvatarProps, 'size'>;\n name?: ReactNode;\n status?: ChatMessageStatus;\n}\n\n/**\n * Avatar, name, and status line. Renders nothing without any of them or\n * children, unless it has shown a streaming status.\n */\nexport function ChatMessageHeader({\n avatar,\n name,\n status = 'completed',\n children,\n className,\n ...props\n}: ChatMessageHeaderProps) {\n const [hasStreamed, setHasStreamed] = useState(status === 'streaming');\n if (status === 'streaming' && !hasStreamed) setHasStreamed(true);\n\n const statusLabel = statusLabels[status];\n const isEmpty =\n avatar == null && name == null && !statusLabel && children == null;\n\n if (isEmpty && !hasStreamed) return null;\n\n return (\n <div\n className={cn(\n 'flex min-w-0 max-w-full flex-wrap items-center gap-space-2 [overflow-wrap:anywhere]',\n // Keep the line the streaming status used so the text below doesn't\n // jump up when it ends.\n isEmpty && 'min-h-lh text-xxs leading-snug',\n className\n )}\n {...props}\n >\n {avatar && (\n // The name and the message label already identify the speaker; this\n // keeps the avatar's initial from being read out before the name.\n <span aria-hidden=\"true\" className=\"inline-flex shrink-0\">\n <Avatar size=\"xs\" {...avatar} />\n </span>\n )}\n {name != null && (\n <Text as=\"span\" variant=\"xs\" weight=\"medium\" className=\"leading-snug\">\n {name}\n </Text>\n )}\n {status === 'streaming' ? (\n <ThinkingState size=\"xs\" label={statusLabel} motion=\"subtle\" />\n ) : statusLabel ? (\n <Text\n as=\"span\"\n variant=\"xs\"\n color={status === 'failed' ? 'error' : 'secondary'}\n className=\"flex items-center gap-space-2 leading-snug\"\n >\n {status === 'failed' && (\n <Icon\n icon={WarningCircleIcon}\n size=\"sm\"\n weight=\"fill\"\n className=\"text-icon-error\"\n aria-hidden=\"true\"\n />\n )}\n {statusLabel}\n </Text>\n ) : null}\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageBodyProps extends Omit<\n ComponentPropsWithRef<'div'>,\n 'children'\n> {\n blocks: readonly ChatMessageContentBlock[];\n /** Supply one complete paragraph per text block; existing blocks do not replay. */\n animateParagraphs?: boolean;\n}\n\n/** Content blocks in order. Text blocks render as escaped plain text. */\nexport function ChatMessageBody({\n blocks,\n animateParagraphs = false,\n className,\n ...props\n}: ChatMessageBodyProps) {\n const alignment = useContext(ChatMessageAlignmentContext);\n if (blocks.length === 0) return null;\n\n return (\n <div\n className={cn(\n 'flex w-full min-w-0 max-w-full flex-col gap-space-3 [overflow-wrap:anywhere]',\n alignment === 'end' && 'items-end',\n // Keep wide host content from stretching the message. Tables that\n // already sit in a scrolling region, such as MarkdownDisplay's, keep\n // table layout so they can fill the message width.\n '[&_img]:max-w-full [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table:not([role=region]>table)]:block [&_table:not([role=region]>table)]:max-w-full [&_table:not([role=region]>table)]:overflow-x-auto',\n className\n )}\n {...props}\n >\n {blocks.map((block) => {\n const content =\n block.type === 'text' ? (\n <Text\n as=\"p\"\n variant=\"sm\"\n weight=\"normal\"\n className={cn(\n 'min-w-0 whitespace-pre-wrap leading-normal tracking-normal text-inherit',\n animateParagraphs &&\n 'animate-in fade-in duration-normal ease-out motion-reduce:animate-none'\n )}\n >\n {block.text}\n </Text>\n ) : (\n block.content\n );\n\n return block.appearance === 'bubble' ? (\n <div\n key={block.id}\n className=\"w-fit min-w-0 max-w-full rounded-lg bg-surface-level-2 px-space-3 py-space-2\"\n >\n {content}\n </div>\n ) : (\n <Fragment key={block.id}>{content}</Fragment>\n );\n })}\n </div>\n );\n}\n\nconst actionDefinitions: {\n name: keyof ChatMessageActionCapabilities;\n label: string;\n icon: IconComponent;\n}[] = [\n { name: 'copy', label: 'Copy message', icon: CopySimpleIcon },\n { name: 'edit', label: 'Edit message', icon: PencilSimpleIcon },\n { name: 'retry', label: 'Retry message', icon: ArrowClockwiseIcon },\n { name: 'cancel', label: 'Cancel queued message', icon: XIcon },\n];\n\nfunction canChangeMessage(status: ChatMessageStatus, readOnly: boolean) {\n return (\n !readOnly &&\n status !== 'queued' &&\n status !== 'submitting' &&\n status !== 'streaming'\n );\n}\n\nfunction isActionAvailable(\n name: keyof ChatMessageActionCapabilities,\n status: ChatMessageStatus,\n readOnly: boolean\n) {\n if (name === 'copy') return true;\n if (name === 'cancel') return !readOnly && status === 'queued';\n return canChangeMessage(status, readOnly);\n}\n\nexport interface ChatMessageActionsProps extends ComponentPropsWithRef<'div'> {\n actions?: ChatMessageActionCapabilities;\n status?: ChatMessageStatus;\n readOnly?: boolean;\n}\n\n/**\n * Copy, edit, retry, and cancel buttons, plus any host actions in `children`.\n * Edit and retry are hidden while the message is pending or read-only; cancel\n * appears only on a queued message; copy stays available. Renders nothing\n * when no actions remain.\n */\nexport function ChatMessageActions({\n actions,\n status = 'completed',\n readOnly = false,\n children,\n className,\n ...props\n}: ChatMessageActionsProps) {\n const visibleActions = actionDefinitions.flatMap((definition) => {\n const action = actions?.[definition.name];\n return action && isActionAvailable(definition.name, status, readOnly)\n ? [{ ...definition, action }]\n : [];\n });\n if (visibleActions.length === 0 && children == null) return null;\n\n return (\n <div\n role=\"group\"\n aria-label=\"Message actions\"\n className={cn(\n 'flex min-w-0 max-w-full flex-wrap items-center gap-space-1',\n className\n )}\n {...props}\n >\n {visibleActions.map(({ name, label, icon, action }) => (\n <IconButton\n key={name}\n icon={icon}\n iconWeight=\"regular\"\n label={action.label ?? label}\n color=\"secondary\"\n variant=\"plain\"\n size=\"xs\"\n onClick={action.onClick}\n />\n ))}\n {children}\n </div>\n );\n}\n\nexport interface ChatTurnDividerProps extends Omit<\n ComponentPropsWithRef<'div'>,\n 'children'\n> {\n label: string;\n}\n\nexport function ChatTurnDivider({\n label,\n className,\n ...props\n}: ChatTurnDividerProps) {\n return (\n <div\n role=\"separator\"\n aria-label={label}\n aria-orientation=\"horizontal\"\n className={cn(\n 'flex w-full min-w-0 items-center gap-space-3 py-space-3',\n className\n )}\n {...props}\n >\n <Divider className=\"min-w-space-4 flex-1\" />\n <Text\n variant=\"xs\"\n color=\"tertiary\"\n className=\"min-w-0 text-center [overflow-wrap:anywhere]\"\n >\n {label}\n </Text>\n <Divider className=\"min-w-space-4 flex-1\" />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,IAAM,8BAA8B,cAA+B,OAAO;AAE1E,IAAM,aAA8C;CAClD,MAAM;CACN,WAAW;CACX,QAAQ;CACR,MAAM;AACR;AAEA,IAAM,eAAyD;CAC7D,MAAM;CACN,QAAQ;CACR,YAAY;CACZ,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,WAAW;AACb;AAEA,IAAM,kCAAkB,IAAI,IAAuB;CACjD;CACA;CACA;CACA;AACF,CAAC;;;;;;AA+BD,SAAgB,YAAY,EAC1B,SACA,QACA,QACA,MACA,OACA,WAAW,OACX,oBAAoB,OACpB,WACA,kBACA,UACA,GAAG,SACgB;CACnB,MAAM,YAAY,UAAU,QAAQ,SAAS,SAAS,QAAQ;CAC9D,MAAM,cAAc,QAAQ,WAAW;CACvC,MAAM,YAAY,gBAAgB,IAAI,QAAQ,MAAM;CACpD,MAAM,CAAC,WAAW,gBAAgB,SAAS,SAAS;CACpD,IAAI,aAAa,CAAC,WAAW,aAAa,KAAK;CAE/C,OACE,oBAAC,OAAD;EACE,MAAK;EACL,cAAY,GAAG,OAAO,SAAS,WAAW,OAAO,QAAQ,SAAS,WAAW,QAAQ,MAAM;EAC3F,aAAW,eAAe,QAAQ,WAAW;EAC7C,WAAW,GACT,uDACA,cAAc,SAAS,eACvB,SACF;EACA,GAAI;EA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,QAAQ,QAAQ;AAC1C;;;;;;;AAcA,SAAgB,mBAAmB,EACjC,SACA,SAAS,aACT,WAAW,OACX,UACA,WACA,GAAG,SACuB;CAC1B,MAAM,iBAAiB,kBAAkB,SAAS,eAAe;EAC/D,MAAM,SAAS,UAAU,WAAW;EACpC,OAAO,UAAU,kBAAkB,WAAW,MAAM,QAAQ,QAAQ,IAChE,CAAC;GAAE,GAAG;GAAY;EAAO,CAAC,IAC1B,CAAC;CACP,CAAC;CACD,IAAI,eAAe,WAAW,KAAK,YAAY,MAAM,OAAO;CAE5D,OACE,qBAAC,OAAD;EACE,MAAK;EACL,cAAW;EACX,WAAW,GACT,8DACA,SACF;EACA,GAAI;EAPN,UAAA,CASG,eAAe,KAAK,EAAE,MAAM,OAAO,MAAM,aACxC,oBAAC,YAAD;GAEQ;GACN,YAAW;GACX,OAAO,OAAO,SAAS;GACvB,OAAM;GACN,SAAQ;GACR,MAAK;GACL,SAAS,OAAO;EACjB,GARM,IAQN,CACF,GACA,QACE;;AAET;AASA,SAAgB,gBAAgB,EAC9B,OACA,WACA,GAAG,SACoB;CACvB,OACE,qBAAC,OAAD;EACE,MAAK;EACL,cAAY;EACZ,oBAAiB;EACjB,WAAW,GACT,2DACA,SACF;EACA,GAAI;EARN,UAAA;GAUE,oBAAC,SAAD,EAAS,WAAU,uBAAwB,CAAA;GAC3C,oBAAC,MAAD;IACE,SAAQ;IACR,OAAM;IACN,WAAU;IAET,UAAA;GACG,CAAA;GACN,oBAAC,SAAD,EAAS,WAAU,uBAAwB,CAAA;EACxC;;AAET"}
1
+ {"version":3,"file":"ChatMessage.js","names":[],"sources":["../../../src/components/ChatMessage/ChatMessage.tsx"],"sourcesContent":["import {\n createContext,\n Fragment,\n useContext,\n useState,\n type ComponentPropsWithRef,\n type ReactNode,\n} from 'react';\n\nimport { ArrowClockwiseIcon } from '@phosphor-icons/react/dist/ssr/ArrowClockwise';\nimport { CopySimpleIcon } from '@phosphor-icons/react/dist/ssr/CopySimple';\nimport { PencilSimpleIcon } from '@phosphor-icons/react/dist/ssr/PencilSimple';\nimport { WarningCircleIcon } from '@phosphor-icons/react/dist/ssr/WarningCircle';\nimport { XIcon } from '@phosphor-icons/react/dist/ssr/X';\n\nimport { cn } from '../../utils/cn';\nimport type { IconComponent } from '../../utils/icon-types';\nimport { Avatar, type AvatarProps } from '../Avatar';\nimport { Divider } from '../Divider';\nimport { Icon } from '../Icon';\nimport { IconButton } from '../IconButton';\nimport { Text } from '../Text';\nimport { ThinkingState } from '../ThinkingState';\nimport type {\n ChatMessageActionCapabilities,\n ChatMessageContentBlock,\n ChatMessageModel,\n ChatMessageRole,\n ChatMessageStatus,\n} from './ChatMessage.types';\n\n/**\n * The message's alignment, so a host-supplied `ChatMessageBody` lines up its\n * blocks the same way the default body does.\n */\nconst ChatMessageAlignmentContext = createContext<'start' | 'end'>('start');\n\nconst roleLabels: Record<ChatMessageRole, string> = {\n user: 'User',\n assistant: 'Assistant',\n system: 'System',\n tool: 'Tool',\n};\n\nconst statusLabels: Record<ChatMessageStatus, string | null> = {\n idle: null,\n queued: 'Queued',\n submitting: 'Sending',\n streaming: 'Responding',\n interrupted: 'Interrupted',\n failed: 'Failed',\n stopped: 'Stopped',\n completed: null,\n};\n\nconst settledStatuses = new Set<ChatMessageStatus>([\n 'completed',\n 'failed',\n 'stopped',\n 'interrupted',\n]);\n\nexport interface ChatMessageProps extends ComponentPropsWithRef<'div'> {\n message: ChatMessageModel;\n /** Metadata and actions share the message's footer layout and visibility. */\n footer?: ReactNode;\n /** `Avatar` shown before the name in the default header, sized to match it. */\n avatar?: Omit<AvatarProps, 'size'>;\n /**\n * Name shown after the avatar in the default header. A string name also\n * labels the message for screen readers; otherwise the avatar's label or\n * the role label does.\n */\n name?: ReactNode;\n /** Defaults to end for user messages and start for other roles. */\n align?: 'start' | 'end';\n /** Keeps the footer visible; earlier messages reveal it on hover or focus. */\n isLatest?: boolean;\n /**\n * Fade in complete text blocks as they mount; keep their IDs stable. A\n * message that mounts already settled, such as history, doesn't fade in.\n */\n animateParagraphs?: boolean;\n contentClassName?: string;\n}\n\n/**\n * One message in a conversation. Renders a header and the message's content\n * blocks, or `children` in their place for custom layouts. The footer is\n * hidden, but keeps its space, while the message streams. The root carries\n * `data-chat-message-id`, which `ChatConversation` uses to pin a message and\n * to hold the reader's place when earlier messages load.\n */\nexport function ChatMessage({\n message,\n footer,\n avatar,\n name,\n align,\n isLatest = false,\n animateParagraphs = false,\n className,\n contentClassName,\n children,\n ...props\n}: ChatMessageProps) {\n const alignment = align ?? (message.role === 'user' ? 'end' : 'start');\n const isStreaming = message.status === 'streaming';\n const isSettled = settledStatuses.has(message.status);\n const [isHistory, setIsHistory] = useState(isSettled);\n if (isHistory && !isSettled) setIsHistory(false);\n\n return (\n <div\n role=\"article\"\n aria-label={`${typeof name === 'string' ? name : avatar?.label || roleLabels[message.role]} message`}\n aria-busy={isStreaming || message.status === 'submitting'}\n data-chat-message-id={message.id}\n className={cn(\n 'group/chat-message flex w-full min-w-0 text-primary',\n alignment === 'end' && 'justify-end',\n className\n )}\n {...props}\n >\n <div\n className={cn(\n 'flex min-w-0 max-w-full flex-col gap-space-2',\n alignment === 'end' ? 'w-fit max-w-[85%] items-end' : 'w-full',\n contentClassName\n )}\n >\n <ChatMessageAlignmentContext.Provider value={alignment}>\n {children ?? (\n <>\n <ChatMessageHeader\n avatar={avatar}\n name={name}\n status={message.status}\n />\n <ChatMessageBody\n blocks={message.content}\n animateParagraphs={animateParagraphs && !isHistory}\n />\n </>\n )}\n </ChatMessageAlignmentContext.Provider>\n {footer != null && (\n <div\n // Reserve the footer's space while streaming so it doesn't pop in.\n inert={isStreaming}\n className={cn(\n 'flex min-w-0 max-w-full flex-wrap items-center gap-space-2 [overflow-wrap:anywhere]',\n isStreaming && 'invisible',\n // Earlier messages hide their footer until hovered or focused,\n // except on touch screens, which have no hover to reveal it.\n // Keyboard focus reveals it without a fade.\n !isLatest &&\n 'transition-opacity duration-fast focus-within:transition-none motion-reduce:transition-none pointer-fine:opacity-0 pointer-fine:focus-within:opacity-100 pointer-fine:group-hover/chat-message:opacity-100 pointer-fine:has-[[data-state=open]]:opacity-100'\n )}\n >\n {footer}\n </div>\n )}\n </div>\n </div>\n );\n}\n\nexport interface ChatMessageHeaderProps extends ComponentPropsWithRef<'div'> {\n avatar?: Omit<AvatarProps, 'size'>;\n name?: ReactNode;\n status?: ChatMessageStatus;\n}\n\n/**\n * Avatar, name, and status line. Renders nothing without any of them or\n * children, unless it has shown a streaming status.\n */\nexport function ChatMessageHeader({\n avatar,\n name,\n status = 'completed',\n children,\n className,\n ...props\n}: ChatMessageHeaderProps) {\n const [hasStreamed, setHasStreamed] = useState(status === 'streaming');\n if (status === 'streaming' && !hasStreamed) setHasStreamed(true);\n\n const statusLabel = statusLabels[status];\n const isEmpty =\n avatar == null && name == null && !statusLabel && children == null;\n\n if (isEmpty && !hasStreamed) return null;\n\n return (\n <div\n className={cn(\n 'flex min-w-0 max-w-full flex-wrap items-center gap-space-2 [overflow-wrap:anywhere]',\n // Keep the line the streaming status used so the text below doesn't\n // jump up when it ends.\n isEmpty && 'min-h-lh text-xxs leading-snug',\n className\n )}\n {...props}\n >\n {avatar && (\n // The name and the message label already identify the speaker; this\n // keeps the avatar's initial from being read out before the name.\n <span aria-hidden=\"true\" className=\"inline-flex shrink-0\">\n <Avatar size=\"xs\" {...avatar} />\n </span>\n )}\n {name != null && (\n <Text as=\"span\" variant=\"xs\" weight=\"medium\" className=\"leading-snug\">\n {name}\n </Text>\n )}\n {status === 'streaming' ? (\n <ThinkingState size=\"xs\" label={statusLabel} motion=\"subtle\" />\n ) : statusLabel ? (\n <Text\n as=\"span\"\n variant=\"xs\"\n color={status === 'failed' ? 'error' : 'secondary'}\n className=\"flex items-center gap-space-2 leading-snug\"\n >\n {status === 'failed' && (\n <Icon\n icon={WarningCircleIcon}\n size=\"sm\"\n weight=\"fill\"\n className=\"text-icon-error\"\n aria-hidden=\"true\"\n />\n )}\n {statusLabel}\n </Text>\n ) : null}\n {children}\n </div>\n );\n}\n\nexport interface ChatMessageBodyProps extends Omit<\n ComponentPropsWithRef<'div'>,\n 'children'\n> {\n blocks: readonly ChatMessageContentBlock[];\n /** Supply one complete paragraph per text block; existing blocks do not replay. */\n animateParagraphs?: boolean;\n}\n\n/** Content blocks in order. Text blocks render as escaped plain text. */\nexport function ChatMessageBody({\n blocks,\n animateParagraphs = false,\n className,\n ...props\n}: ChatMessageBodyProps) {\n const alignment = useContext(ChatMessageAlignmentContext);\n if (blocks.length === 0) return null;\n\n return (\n <div\n className={cn(\n 'flex w-full min-w-0 max-w-full flex-col gap-space-3 [overflow-wrap:anywhere]',\n alignment === 'end' && 'items-end',\n // Keep wide host content from stretching the message. Tables that\n // already sit in a scrolling region, such as MarkdownDisplay's, keep\n // table layout so they can fill the message width.\n '[&_img]:max-w-full [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table:not([role=region]>table)]:block [&_table:not([role=region]>table)]:max-w-full [&_table:not([role=region]>table)]:overflow-x-auto',\n className\n )}\n {...props}\n >\n {blocks.map((block) => {\n const content =\n block.type === 'text' ? (\n <Text\n as=\"p\"\n variant=\"sm\"\n weight=\"normal\"\n className={cn(\n 'min-w-0 whitespace-pre-wrap leading-normal tracking-normal text-inherit',\n animateParagraphs &&\n 'animate-in fade-in duration-normal ease-out motion-reduce:animate-none'\n )}\n >\n {block.text}\n </Text>\n ) : (\n block.content\n );\n\n return block.appearance === 'bubble' ? (\n <div\n key={block.id}\n className=\"w-fit min-w-0 max-w-full rounded-lg bg-surface-level-2 px-space-3 py-space-2\"\n >\n {content}\n </div>\n ) : (\n <Fragment key={block.id}>{content}</Fragment>\n );\n })}\n </div>\n );\n}\n\nconst actionDefinitions: {\n name: keyof ChatMessageActionCapabilities;\n label: string;\n icon: IconComponent;\n}[] = [\n { name: 'copy', label: 'Copy message', icon: CopySimpleIcon },\n { name: 'edit', label: 'Edit message', icon: PencilSimpleIcon },\n { name: 'retry', label: 'Retry message', icon: ArrowClockwiseIcon },\n { name: 'cancel', label: 'Cancel queued message', icon: XIcon },\n];\n\nfunction canChangeMessage(status: ChatMessageStatus, readOnly: boolean) {\n return (\n !readOnly &&\n status !== 'queued' &&\n status !== 'submitting' &&\n status !== 'streaming'\n );\n}\n\nfunction isActionAvailable(\n name: keyof ChatMessageActionCapabilities,\n status: ChatMessageStatus,\n readOnly: boolean\n) {\n if (name === 'copy') return true;\n if (name === 'cancel') return !readOnly && status === 'queued';\n return canChangeMessage(status, readOnly);\n}\n\nexport interface ChatMessageActionsProps extends ComponentPropsWithRef<'div'> {\n actions?: ChatMessageActionCapabilities;\n status?: ChatMessageStatus;\n readOnly?: boolean;\n}\n\n/**\n * Copy, edit, retry, and cancel buttons, plus any host actions in `children`.\n * Edit and retry are hidden while the message is pending or read-only; cancel\n * appears only on a queued message; copy stays available. Renders nothing\n * when no actions remain.\n */\nexport function ChatMessageActions({\n actions,\n status = 'completed',\n readOnly = false,\n children,\n className,\n ...props\n}: ChatMessageActionsProps) {\n const visibleActions = actionDefinitions.flatMap((definition) => {\n const action = actions?.[definition.name];\n return action && isActionAvailable(definition.name, status, readOnly)\n ? [{ ...definition, action }]\n : [];\n });\n if (visibleActions.length === 0 && children == null) return null;\n\n return (\n <div\n role=\"group\"\n aria-label=\"Message actions\"\n className={cn(\n 'flex min-w-0 max-w-full flex-wrap items-center gap-space-1',\n className\n )}\n {...props}\n >\n {visibleActions.map(({ name, label, icon, action }) => (\n <IconButton\n key={name}\n icon={icon}\n iconWeight=\"regular\"\n label={action.label ?? label}\n color=\"secondary\"\n variant=\"plain\"\n size=\"xs\"\n onClick={action.onClick}\n />\n ))}\n {children}\n </div>\n );\n}\n\nexport interface ChatTurnDividerProps extends Omit<\n ComponentPropsWithRef<'div'>,\n 'children'\n> {\n label: string;\n}\n\nexport function ChatTurnDivider({\n label,\n className,\n ...props\n}: ChatTurnDividerProps) {\n return (\n <div\n role=\"separator\"\n aria-label={label}\n aria-orientation=\"horizontal\"\n className={cn(\n 'flex w-full min-w-0 items-center gap-space-3 py-space-3',\n className\n )}\n {...props}\n >\n <Divider className=\"min-w-space-4 flex-1\" />\n <Text\n variant=\"xs\"\n color=\"tertiary\"\n className=\"min-w-0 text-center [overflow-wrap:anywhere]\"\n >\n {label}\n </Text>\n <Divider className=\"min-w-space-4 flex-1\" />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,IAAM,8BAA8B,cAA+B,OAAO;AAE1E,IAAM,aAA8C;CAClD,MAAM;CACN,WAAW;CACX,QAAQ;CACR,MAAM;AACR;AAEA,IAAM,eAAyD;CAC7D,MAAM;CACN,QAAQ;CACR,YAAY;CACZ,WAAW;CACX,aAAa;CACb,QAAQ;CACR,SAAS;CACT,WAAW;AACb;AAEA,IAAM,kCAAkB,IAAI,IAAuB;CACjD;CACA;CACA;CACA;AACF,CAAC;;;;;;;;AAiCD,SAAgB,YAAY,EAC1B,SACA,QACA,QACA,MACA,OACA,WAAW,OACX,oBAAoB,OACpB,WACA,kBACA,UACA,GAAG,SACgB;CACnB,MAAM,YAAY,UAAU,QAAQ,SAAS,SAAS,QAAQ;CAC9D,MAAM,cAAc,QAAQ,WAAW;CACvC,MAAM,YAAY,gBAAgB,IAAI,QAAQ,MAAM;CACpD,MAAM,CAAC,WAAW,gBAAgB,SAAS,SAAS;CACpD,IAAI,aAAa,CAAC,WAAW,aAAa,KAAK;CAE/C,OACE,oBAAC,OAAD;EACE,MAAK;EACL,cAAY,GAAG,OAAO,SAAS,WAAW,OAAO,QAAQ,SAAS,WAAW,QAAQ,MAAM;EAC3F,aAAW,eAAe,QAAQ,WAAW;EAC7C,wBAAsB,QAAQ;EAC9B,WAAW,GACT,uDACA,cAAc,SAAS,eACvB,SACF;EACA,GAAI;EAEJ,UAAA,qBAAC,OAAD;GACE,WAAW,GACT,gDACA,cAAc,QAAQ,gCAAgC,UACtD,gBACF;GALF,UAAA,CAOE,oBAAC,4BAA4B,UAA7B;IAAsC,OAAO;IAC1C,UAAA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Ae;EAC/D,MAAM,SAAS,UAAU,WAAW;EACpC,OAAO,UAAU,kBAAkB,WAAW,MAAM,QAAQ,QAAQ,IAChE,CAAC;GAAE,GAAG;GAAY;EAAO,CAAC,IAC1B,CAAC;CACP,CAAC;CACD,IAAI,eAAe,WAAW,KAAK,YAAY,MAAM,OAAO;CAE5D,OACE,qBAAC,OAAD;EACE,MAAK;EACL,cAAW;EACX,WAAW,GACT,8DACA,SACF;EACA,GAAI;EAPN,UAAA,CASG,eAAe,KAAK,EAAE,MAAM,OAAO,MAAM,aACxC,oBAAC,YAAD;GAEQ;GACN,YAAW;GACX,OAAO,OAAO,SAAS;GACvB,OAAM;GACN,SAAQ;GACR,MAAK;GACL,SAAS,OAAO;EACjB,GARM,IAQN,CACF,GACA,QACE;;AAET;AASA,SAAgB,gBAAgB,EAC9B,OACA,WACA,GAAG,SACoB;CACvB,OACE,qBAAC,OAAD;EACE,MAAK;EACL,cAAY;EACZ,oBAAiB;EACjB,WAAW,GACT,2DACA,SACF;EACA,GAAI;EARN,UAAA;GAUE,oBAAC,SAAD,EAAS,WAAU,uBAAwB,CAAA;GAC3C,oBAAC,MAAD;IACE,SAAQ;IACR,OAAM;IACN,WAAU;IAET,UAAA;GACG,CAAA;GACN,oBAAC,SAAD,EAAS,WAAU,uBAAwB,CAAA;EACxC;;AAET"}
@@ -7,7 +7,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
7
7
  import * as TooltipPrimitive from "@radix-ui/react-tooltip";
8
8
  //#region packages/components/src/components/Tooltip/Tooltip.tsx
9
9
  function Tooltip({ title, description, children, tooltipClassName, side = "top", sideOffset = 10, align = "center", alignOffset = 0, invert = false, delayDuration = 300, disabled = false, blockTriggerEvents = false, open, onOpenChange, disableHoverableContent = true }) {
10
- const zIndex = useZIndex(zIndices.tooltip);
10
+ const zIndex = useZIndex(zIndices.tooltipOverlay);
11
11
  if (!title && !description || disabled) return children;
12
12
  return /* @__PURE__ */ jsxs(TooltipPrimitive.Root, {
13
13
  delayDuration,
@@ -1 +1 @@
1
- {"version":3,"file":"Tooltip.js","names":[],"sources":["../../../src/components/Tooltip/Tooltip.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport * as TooltipPrimitive from '@radix-ui/react-tooltip';\n\nimport { cn } from '../../utils/cn';\nimport { useZIndex } from '../../utils/useZIndex';\nimport { ZIndexProvider } from '../../utils/ZIndexContext';\nimport zIndices from '../../utils/zIndices';\nimport { Text } from '../Text';\n\nexport type TooltipProps = {\n title?: string | ReactNode;\n description?: ReactNode;\n children: ReactNode;\n tooltipClassName?: string;\n side?: 'top' | 'bottom' | 'left' | 'right';\n sideOffset?: number;\n align?: 'start' | 'center' | 'end';\n alignOffset?: number;\n invert?: boolean;\n delayDuration?: number;\n disabled?: boolean;\n blockTriggerEvents?: boolean;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n disableHoverableContent?: boolean;\n};\n\n// Tooltip sets two opinionated defaults — override with caution:\n// - delayDuration=300: prevents tooltips from blocking clicks\n// - disableHoverableContent=true: dismisses the tooltip when hovering off the trigger\nexport function Tooltip({\n title,\n description,\n children,\n tooltipClassName,\n side = 'top',\n sideOffset = 10,\n align = 'center',\n alignOffset = 0,\n invert = false,\n delayDuration = 300,\n disabled = false,\n blockTriggerEvents = false,\n open,\n onOpenChange,\n disableHoverableContent = true,\n}: TooltipProps) {\n // Tooltips have no fixed z-index floor — they always render one level above\n // their parent caller so they naturally stack above whichever layer triggered them.\n const zIndex = useZIndex(zIndices.tooltip);\n\n if ((!title && !description) || disabled) {\n return children;\n }\n\n return (\n <TooltipPrimitive.Root\n delayDuration={delayDuration}\n open={open}\n onOpenChange={onOpenChange}\n disableHoverableContent={disableHoverableContent}\n >\n <TooltipPrimitive.Trigger\n asChild\n onPointerDown={(e) => {\n if (blockTriggerEvents) {\n e.preventDefault();\n e.stopPropagation();\n }\n }}\n >\n {children}\n </TooltipPrimitive.Trigger>\n <TooltipPrimitive.Portal>\n <TooltipPrimitive.Content\n sideOffset={sideOffset}\n side={side}\n align={align}\n alignOffset={alignOffset}\n collisionPadding={8}\n className={cn(\n 'max-w-[320px] overflow-hidden rounded-md border border-subtle bg-popover p-space-2 text-sm shadow-md',\n 'animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',\n tooltipClassName,\n invert && 'invert'\n )}\n style={{ zIndex }}\n >\n <ZIndexProvider value={zIndex}>\n <div className=\"flex flex-col gap-space-2 text-xxs\">\n {typeof title === 'string' ? (\n <Text\n variant=\"sm\"\n data-target=\"title\"\n className={!tooltipClassName ? 'text-primary' : ''}\n >\n {title}\n </Text>\n ) : (\n title\n )}\n {description && (\n <Text\n variant=\"sm\"\n className={!tooltipClassName ? 'text-secondary' : ''}\n data-target=\"description\"\n >\n {description}\n </Text>\n )}\n </div>\n </ZIndexProvider>\n </TooltipPrimitive.Content>\n </TooltipPrimitive.Portal>\n </TooltipPrimitive.Root>\n );\n}\n"],"mappings":";;;;;;;;AA+BA,SAAgB,QAAQ,EACtB,OACA,aACA,UACA,kBACA,OAAO,OACP,aAAa,IACb,QAAQ,UACR,cAAc,GACd,SAAS,OACT,gBAAgB,KAChB,WAAW,OACX,qBAAqB,OACrB,MACA,cACA,0BAA0B,QACX;CAGf,MAAM,SAAS,UAAU,SAAS,OAAO;CAEzC,IAAK,CAAC,SAAS,CAAC,eAAgB,UAC9B,OAAO;CAGT,OACE,qBAAC,iBAAiB,MAAlB;EACiB;EACT;EACQ;EACW;EAJ3B,UAAA,CAME,oBAAC,iBAAiB,SAAlB;GACE,SAAA;GACA,gBAAgB,MAAM;IACpB,IAAI,oBAAoB;KACtB,EAAE,eAAe;KACjB,EAAE,gBAAgB;IACpB;GACF;GAEC;EACuB,CAAA,GAC1B,oBAAC,iBAAiB,QAAlB,EAAA,UACE,oBAAC,iBAAiB,SAAlB;GACc;GACN;GACC;GACM;GACb,kBAAkB;GAClB,WAAW,GACT,wGACA,8RACA,kBACA,UAAU,QACZ;GACA,OAAO,EAAE,OAAO;GAEhB,UAAA,oBAAC,gBAAD;IAAgB,OAAO;IACrB,UAAA,qBAAC,OAAD;KAAK,WAAU;KAAf,UAAA,CACG,OAAO,UAAU,WAChB,oBAAC,MAAD;MACE,SAAQ;MACR,eAAY;MACZ,WAAW,CAAC,mBAAmB,iBAAiB;MAE/C,UAAA;KACG,CAAA,IAEN,OAED,eACC,oBAAC,MAAD;MACE,SAAQ;MACR,WAAW,CAAC,mBAAmB,mBAAmB;MAClD,eAAY;MAEX,UAAA;KACG,CAAA,CAEL;;GACS,CAAA;EACQ,CAAA,EACH,CAAA,CACJ;;AAE3B"}
1
+ {"version":3,"file":"Tooltip.js","names":[],"sources":["../../../src/components/Tooltip/Tooltip.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport * as TooltipPrimitive from '@radix-ui/react-tooltip';\n\nimport { cn } from '../../utils/cn';\nimport { useZIndex } from '../../utils/useZIndex';\nimport { ZIndexProvider } from '../../utils/ZIndexContext';\nimport zIndices from '../../utils/zIndices';\nimport { Text } from '../Text';\n\nexport type TooltipProps = {\n title?: string | ReactNode;\n description?: ReactNode;\n children: ReactNode;\n tooltipClassName?: string;\n side?: 'top' | 'bottom' | 'left' | 'right';\n sideOffset?: number;\n align?: 'start' | 'center' | 'end';\n alignOffset?: number;\n invert?: boolean;\n delayDuration?: number;\n disabled?: boolean;\n blockTriggerEvents?: boolean;\n open?: boolean;\n onOpenChange?: (open: boolean) => void;\n disableHoverableContent?: boolean;\n};\n\n// Tooltip sets two opinionated defaults — override with caution:\n// - delayDuration=300: prevents tooltips from blocking clicks\n// - disableHoverableContent=true: dismisses the tooltip when hovering off the trigger\nexport function Tooltip({\n title,\n description,\n children,\n tooltipClassName,\n side = 'top',\n sideOffset = 10,\n align = 'center',\n alignOffset = 0,\n invert = false,\n delayDuration = 300,\n disabled = false,\n blockTriggerEvents = false,\n open,\n onOpenChange,\n disableHoverableContent = true,\n}: TooltipProps) {\n const zIndex = useZIndex(zIndices.tooltipOverlay);\n\n if ((!title && !description) || disabled) {\n return children;\n }\n\n return (\n <TooltipPrimitive.Root\n delayDuration={delayDuration}\n open={open}\n onOpenChange={onOpenChange}\n disableHoverableContent={disableHoverableContent}\n >\n <TooltipPrimitive.Trigger\n asChild\n onPointerDown={(e) => {\n if (blockTriggerEvents) {\n e.preventDefault();\n e.stopPropagation();\n }\n }}\n >\n {children}\n </TooltipPrimitive.Trigger>\n <TooltipPrimitive.Portal>\n <TooltipPrimitive.Content\n sideOffset={sideOffset}\n side={side}\n align={align}\n alignOffset={alignOffset}\n collisionPadding={8}\n className={cn(\n 'max-w-[320px] overflow-hidden rounded-md border border-subtle bg-popover p-space-2 text-sm shadow-md',\n 'animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',\n tooltipClassName,\n invert && 'invert'\n )}\n style={{ zIndex }}\n >\n <ZIndexProvider value={zIndex}>\n <div className=\"flex flex-col gap-space-2 text-xxs\">\n {typeof title === 'string' ? (\n <Text\n variant=\"sm\"\n data-target=\"title\"\n className={!tooltipClassName ? 'text-primary' : ''}\n >\n {title}\n </Text>\n ) : (\n title\n )}\n {description && (\n <Text\n variant=\"sm\"\n className={!tooltipClassName ? 'text-secondary' : ''}\n data-target=\"description\"\n >\n {description}\n </Text>\n )}\n </div>\n </ZIndexProvider>\n </TooltipPrimitive.Content>\n </TooltipPrimitive.Portal>\n </TooltipPrimitive.Root>\n );\n}\n"],"mappings":";;;;;;;;AA+BA,SAAgB,QAAQ,EACtB,OACA,aACA,UACA,kBACA,OAAO,OACP,aAAa,IACb,QAAQ,UACR,cAAc,GACd,SAAS,OACT,gBAAgB,KAChB,WAAW,OACX,qBAAqB,OACrB,MACA,cACA,0BAA0B,QACX;CACf,MAAM,SAAS,UAAU,SAAS,cAAc;CAEhD,IAAK,CAAC,SAAS,CAAC,eAAgB,UAC9B,OAAO;CAGT,OACE,qBAAC,iBAAiB,MAAlB;EACiB;EACT;EACQ;EACW;EAJ3B,UAAA,CAME,oBAAC,iBAAiB,SAAlB;GACE,SAAA;GACA,gBAAgB,MAAM;IACpB,IAAI,oBAAoB;KACtB,EAAE,eAAe;KACjB,EAAE,gBAAgB;IACpB;GACF;GAEC;EACuB,CAAA,GAC1B,oBAAC,iBAAiB,QAAlB,EAAA,UACE,oBAAC,iBAAiB,SAAlB;GACc;GACN;GACC;GACM;GACb,kBAAkB;GAClB,WAAW,GACT,wGACA,8RACA,kBACA,UAAU,QACZ;GACA,OAAO,EAAE,OAAO;GAEhB,UAAA,oBAAC,gBAAD;IAAgB,OAAO;IACrB,UAAA,qBAAC,OAAD;KAAK,WAAU;KAAf,UAAA,CACG,OAAO,UAAU,WAChB,oBAAC,MAAD;MACE,SAAQ;MACR,eAAY;MACZ,WAAW,CAAC,mBAAmB,iBAAiB;MAE/C,UAAA;KACG,CAAA,IAEN,OAED,eACC,oBAAC,MAAD;MACE,SAAQ;MACR,WAAW,CAAC,mBAAmB,mBAAmB;MAClD,eAAY;MAEX,UAAA;KACG,CAAA,CAEL;;GACS,CAAA;EACQ,CAAA,EACH,CAAA,CACJ;;AAE3B"}