@langchain/macaw-components 1.7.9 → 1.7.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/catalog.json +772 -757
- package/dist/components/ChatComposer/ChatComposer.d.ts +10 -1
- package/dist/components/ChatComposer/ChatComposer.js +16 -9
- package/dist/components/ChatComposer/ChatComposer.js.map +1 -1
- package/dist/components/ChatComposer/ChatComposerContext.d.ts +1 -1
- package/dist/components/ChatComposer/ChatComposerContext.js.map +1 -1
- package/dist/components/ChatComposer/ChatComposerRichInput.js +13 -2
- package/dist/components/ChatComposer/ChatComposerRichInput.js.map +1 -1
- package/dist/components/ChatConversation/ChatConversation.d.ts +16 -3
- package/dist/components/ChatConversation/ChatConversation.js +209 -41
- package/dist/components/ChatConversation/ChatConversation.js.map +1 -1
- package/dist/components/ChatMessage/ChatMessage.d.ts +7 -4
- package/dist/components/ChatMessage/ChatMessage.js +21 -7
- package/dist/components/ChatMessage/ChatMessage.js.map +1 -1
- package/dist/components/ChatMessage/ChatMessage.types.d.ts +2 -0
- package/dist/components/ChatPlan/ChatPlan.d.ts +27 -0
- package/dist/components/ChatPlan/ChatPlan.js +156 -0
- package/dist/components/ChatPlan/ChatPlan.js.map +1 -0
- package/dist/components/ChatPlan/index.d.ts +2 -0
- package/dist/components/ChatPlan/index.js +2 -0
- package/dist/components/ChatRichContent/ChatRichContent.js +79 -28
- package/dist/components/ChatRichContent/ChatRichContent.js.map +1 -1
- package/dist/components/ChatRichContent/ChatRichContent.types.d.ts +18 -0
- package/dist/components/ChatRichContent/index.d.ts +1 -1
- package/dist/components/ChatState/ChatState.d.ts +12 -1
- package/dist/components/ChatState/ChatState.js +5 -4
- package/dist/components/ChatState/ChatState.js.map +1 -1
- package/dist/components/ChatState/ChatStateTimer.d.ts +3 -1
- package/dist/components/ChatState/ChatStateTimer.js +24 -11
- package/dist/components/ChatState/ChatStateTimer.js.map +1 -1
- package/dist/components/ChatState/formatChatDuration.d.ts +16 -0
- package/dist/components/ChatState/formatChatDuration.js +19 -0
- package/dist/components/ChatState/formatChatDuration.js.map +1 -0
- package/dist/components/ChatState/index.d.ts +2 -0
- package/dist/components/ChatState/index.js +2 -1
- package/dist/components/ChatToolCall/ChatToolCall.d.ts +7 -1
- package/dist/components/ChatToolCall/ChatToolCall.js +3 -1
- package/dist/components/ChatToolCall/ChatToolCall.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallAccordion.d.ts +3 -1
- package/dist/components/ChatToolCall/ChatToolCallAccordion.js +33 -26
- package/dist/components/ChatToolCall/ChatToolCallAccordion.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallGroup.d.ts +20 -2
- package/dist/components/ChatToolCall/ChatToolCallGroup.js +8 -5
- package/dist/components/ChatToolCall/ChatToolCallGroup.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallReasoning.d.ts +10 -2
- package/dist/components/ChatToolCall/ChatToolCallReasoning.js +13 -5
- package/dist/components/ChatToolCall/ChatToolCallReasoning.js.map +1 -1
- package/dist/components/ChatToolCall/ChatToolCallStatusRow.d.ts +3 -1
- package/dist/components/ChatToolCall/ChatToolCallStatusRow.js +29 -18
- package/dist/components/ChatToolCall/ChatToolCallStatusRow.js.map +1 -1
- package/dist/utilities.css +1 -1
- package/docs/CHAT.md +50 -0
- package/docs/DESIGN.md +10 -6
- package/package.json +6 -2
|
@@ -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,MAAM,CAAC,UAAU,eAAe,SAAS,KAAK;CAC9C,MAAM,oBAAoB,cAClB,UAAU,CAAC,aAAa,mBAAmB,CAAC,GAClD,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U,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'> {
|
|
@@ -53,9 +55,10 @@ export interface ChatMessageActionsProps extends ComponentPropsWithRef<'div'> {
|
|
|
53
55
|
readOnly?: boolean;
|
|
54
56
|
}
|
|
55
57
|
/**
|
|
56
|
-
* Copy, edit, and
|
|
57
|
-
* and retry are hidden while the message is pending or read-only;
|
|
58
|
-
*
|
|
58
|
+
* Copy, edit, retry, and cancel buttons, plus any host actions in `children`.
|
|
59
|
+
* Edit and retry are hidden while the message is pending or read-only; cancel
|
|
60
|
+
* appears only on a queued message; copy stays available. Renders nothing
|
|
61
|
+
* when no actions remain.
|
|
59
62
|
*/
|
|
60
63
|
export declare function ChatMessageActions({ actions, status, readOnly, children, className, ...props }: ChatMessageActionsProps): import("react").JSX.Element | null;
|
|
61
64
|
export interface ChatTurnDividerProps extends Omit<ComponentPropsWithRef<'div'>, 'children'> {
|
|
@@ -6,6 +6,7 @@ import { Icon } from "../Icon/Icon.js";
|
|
|
6
6
|
import { Divider } from "../Divider/Divider.js";
|
|
7
7
|
import { ThinkingState } from "../ThinkingState/ThinkingState.js";
|
|
8
8
|
import { Fragment, createContext, useContext, useState } from "react";
|
|
9
|
+
import { XIcon } from "@phosphor-icons/react/dist/ssr/X";
|
|
9
10
|
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
|
|
10
11
|
import { WarningCircleIcon } from "@phosphor-icons/react/dist/ssr/WarningCircle";
|
|
11
12
|
import { CopySimpleIcon } from "@phosphor-icons/react/dist/ssr/CopySimple";
|
|
@@ -42,7 +43,9 @@ var settledStatuses = /* @__PURE__ */ new Set([
|
|
|
42
43
|
/**
|
|
43
44
|
* One message in a conversation. Renders a header and the message's content
|
|
44
45
|
* blocks, or `children` in their place for custom layouts. The footer is
|
|
45
|
-
* 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.
|
|
46
49
|
*/
|
|
47
50
|
function ChatMessage({ message, footer, avatar, name, align, isLatest = false, animateParagraphs = false, className, contentClassName, children, ...props }) {
|
|
48
51
|
const alignment = align ?? (message.role === "user" ? "end" : "start");
|
|
@@ -54,6 +57,7 @@ function ChatMessage({ message, footer, avatar, name, align, isLatest = false, a
|
|
|
54
57
|
role: "article",
|
|
55
58
|
"aria-label": `${typeof name === "string" ? name : avatar?.label || roleLabels[message.role]} message`,
|
|
56
59
|
"aria-busy": isStreaming || message.status === "submitting",
|
|
60
|
+
"data-chat-message-id": message.id,
|
|
57
61
|
className: cn("group/chat-message flex w-full min-w-0 text-primary", alignment === "end" && "justify-end", className),
|
|
58
62
|
...props,
|
|
59
63
|
children: /* @__PURE__ */ jsxs("div", {
|
|
@@ -131,7 +135,7 @@ function ChatMessageBody({ blocks, animateParagraphs = false, className, ...prop
|
|
|
131
135
|
const alignment = useContext(ChatMessageAlignmentContext);
|
|
132
136
|
if (blocks.length === 0) return null;
|
|
133
137
|
return /* @__PURE__ */ jsx("div", {
|
|
134
|
-
className: cn("flex w-full min-w-0 max-w-full flex-col gap-space-3 [overflow-wrap:anywhere]", alignment === "end" && "items-end", "[&_img]:max-w-full [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto", className),
|
|
138
|
+
className: cn("flex w-full min-w-0 max-w-full flex-col gap-space-3 [overflow-wrap:anywhere]", alignment === "end" && "items-end", "[&_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", className),
|
|
135
139
|
...props,
|
|
136
140
|
children: blocks.map((block) => {
|
|
137
141
|
const content = block.type === "text" ? /* @__PURE__ */ jsx(Text, {
|
|
@@ -163,21 +167,31 @@ var actionDefinitions = [
|
|
|
163
167
|
name: "retry",
|
|
164
168
|
label: "Retry message",
|
|
165
169
|
icon: ArrowClockwiseIcon
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
name: "cancel",
|
|
173
|
+
label: "Cancel queued message",
|
|
174
|
+
icon: XIcon
|
|
166
175
|
}
|
|
167
176
|
];
|
|
168
177
|
function canChangeMessage(status, readOnly) {
|
|
169
178
|
return !readOnly && status !== "queued" && status !== "submitting" && status !== "streaming";
|
|
170
179
|
}
|
|
180
|
+
function isActionAvailable(name, status, readOnly) {
|
|
181
|
+
if (name === "copy") return true;
|
|
182
|
+
if (name === "cancel") return !readOnly && status === "queued";
|
|
183
|
+
return canChangeMessage(status, readOnly);
|
|
184
|
+
}
|
|
171
185
|
/**
|
|
172
|
-
* Copy, edit, and
|
|
173
|
-
* and retry are hidden while the message is pending or read-only;
|
|
174
|
-
*
|
|
186
|
+
* Copy, edit, retry, and cancel buttons, plus any host actions in `children`.
|
|
187
|
+
* Edit and retry are hidden while the message is pending or read-only; cancel
|
|
188
|
+
* appears only on a queued message; copy stays available. Renders nothing
|
|
189
|
+
* when no actions remain.
|
|
175
190
|
*/
|
|
176
191
|
function ChatMessageActions({ actions, status = "completed", readOnly = false, children, className, ...props }) {
|
|
177
|
-
const canChange = canChangeMessage(status, readOnly);
|
|
178
192
|
const visibleActions = actionDefinitions.flatMap((definition) => {
|
|
179
193
|
const action = actions?.[definition.name];
|
|
180
|
-
return action && (definition.name
|
|
194
|
+
return action && isActionAvailable(definition.name, status, readOnly) ? [{
|
|
181
195
|
...definition,
|
|
182
196
|
action
|
|
183
197
|
}] : [];
|
|
@@ -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';\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.\n '[&_img]:max-w-full [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_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];\n\nfunction canChangeMessage(status: ChatMessageStatus, readOnly: boolean) {\n return (\n !readOnly &&\n status !== 'queued' &&\n status !== 'submitting' &&\n status !== 'streaming'\n );\n}\n\nexport interface ChatMessageActionsProps extends ComponentPropsWithRef<'div'> {\n actions?: ChatMessageActionCapabilities;\n status?: ChatMessageStatus;\n readOnly?: boolean;\n}\n\n/**\n * Copy, edit, and retry buttons, plus any host actions in `children`. Edit\n * and retry are hidden while the message is pending or read-only; copy stays\n * available. Renders nothing 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 canChange = canChangeMessage(status, readOnly);\n const visibleActions = actionDefinitions.flatMap((definition) => {\n const action = actions?.[definition.name];\n return action && (definition.name === 'copy' || canChange)\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":";;;;;;;;;;;;;;;;;;AAkCA,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;EAEJ,UAAA,qBAAC,OAAD;GACE,WAAW,GACT,gDACA,cAAc,QAAQ,gCAAgC,UACt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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":";;;;;;;;;;;;;;;;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AAW;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"}
|
|
@@ -21,6 +21,8 @@ export interface ChatMessageActionCapabilities {
|
|
|
21
21
|
copy?: ChatMessageAction;
|
|
22
22
|
edit?: ChatMessageAction;
|
|
23
23
|
retry?: ChatMessageAction;
|
|
24
|
+
/** Withdraws a queued message before it sends. Shown only while queued. */
|
|
25
|
+
cancel?: ChatMessageAction;
|
|
24
26
|
}
|
|
25
27
|
/** Render-ready presentation data; product payloads and parsing stay in adapters. */
|
|
26
28
|
export interface ChatMessageModel {
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type ChatPlanItemStatus = 'pending' | 'in-progress' | 'completed';
|
|
2
|
+
export interface ChatPlanItem {
|
|
3
|
+
/** Stable across updates, so items keep their place as the plan changes. */
|
|
4
|
+
id: string;
|
|
5
|
+
label: string;
|
|
6
|
+
status: ChatPlanItemStatus;
|
|
7
|
+
}
|
|
8
|
+
export interface ChatPlanProps {
|
|
9
|
+
/** Items in the agent's order. Renders nothing when empty. */
|
|
10
|
+
items: readonly ChatPlanItem[];
|
|
11
|
+
/** Defaults to "Plan". */
|
|
12
|
+
title?: string;
|
|
13
|
+
/**
|
|
14
|
+
* `drawer` fits `ChatComposer`'s drawer slot, alone or stacked with other
|
|
15
|
+
* drawer content.
|
|
16
|
+
*/
|
|
17
|
+
presentation?: 'block' | 'drawer';
|
|
18
|
+
expanded?: boolean;
|
|
19
|
+
defaultExpanded?: boolean;
|
|
20
|
+
onExpandedChange?: (expanded: boolean) => void;
|
|
21
|
+
className?: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* An agent's task list, such as the todos a deep agent writes as it works.
|
|
25
|
+
* Collapsed, it shows progress and the current task; expanded, every task.
|
|
26
|
+
*/
|
|
27
|
+
export declare function ChatPlan({ items, title, presentation, expanded, defaultExpanded, onExpandedChange, className, }: ChatPlanProps): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { cn } from "../../utils/cn.js";
|
|
2
|
+
import { Text } from "../Text/Text.js";
|
|
3
|
+
import { Button } from "../Button/Button.js";
|
|
4
|
+
import { ChatToolCallCaret } from "../ChatToolCall/ChatToolCallCaret.js";
|
|
5
|
+
import { ChatToolCallCollapse } from "../ChatToolCall/ChatToolCallCollapse.js";
|
|
6
|
+
import { CircularProgress } from "../CircularProgress/CircularProgress.js";
|
|
7
|
+
import { useId, useState } from "react";
|
|
8
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
9
|
+
import { useControllableState } from "@radix-ui/react-use-controllable-state";
|
|
10
|
+
import { CheckCircleIcon } from "@phosphor-icons/react/dist/ssr/CheckCircle";
|
|
11
|
+
import { CircleIcon } from "@phosphor-icons/react/dist/ssr/Circle";
|
|
12
|
+
import { CircleDashedIcon } from "@phosphor-icons/react/dist/ssr/CircleDashed";
|
|
13
|
+
//#region packages/components/src/components/ChatPlan/ChatPlan.tsx
|
|
14
|
+
var ITEM_PRESENTATIONS = {
|
|
15
|
+
pending: {
|
|
16
|
+
label: "Pending",
|
|
17
|
+
icon: CircleIcon,
|
|
18
|
+
iconClassName: "text-icon-tertiary",
|
|
19
|
+
textColor: "secondary"
|
|
20
|
+
},
|
|
21
|
+
"in-progress": {
|
|
22
|
+
label: "In progress",
|
|
23
|
+
icon: CircleDashedIcon,
|
|
24
|
+
iconClassName: "text-icon-secondary",
|
|
25
|
+
textColor: "primary"
|
|
26
|
+
},
|
|
27
|
+
completed: {
|
|
28
|
+
label: "Completed",
|
|
29
|
+
icon: CheckCircleIcon,
|
|
30
|
+
iconClassName: "text-icon-success",
|
|
31
|
+
textColor: "tertiary"
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
var ENTER = "animate-in fade-in ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none";
|
|
35
|
+
function summarize(items) {
|
|
36
|
+
const total = items.length;
|
|
37
|
+
const done = items.filter((item) => item.status === "completed").length;
|
|
38
|
+
const currentIndex = items.findIndex((item) => item.status === "in-progress");
|
|
39
|
+
if (currentIndex !== -1) return {
|
|
40
|
+
done,
|
|
41
|
+
progress: `Task ${currentIndex + 1} of ${total}`,
|
|
42
|
+
current: items[currentIndex].label
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
done,
|
|
46
|
+
progress: done === total ? `All ${total} done` : `${done} of ${total} done`,
|
|
47
|
+
current: void 0
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* An agent's task list, such as the todos a deep agent writes as it works.
|
|
52
|
+
* Collapsed, it shows progress and the current task; expanded, every task.
|
|
53
|
+
*/
|
|
54
|
+
function ChatPlan({ items, title = "Plan", presentation = "block", expanded, defaultExpanded = false, onExpandedChange, className }) {
|
|
55
|
+
const listId = useId();
|
|
56
|
+
const currentId = useId();
|
|
57
|
+
const [isExpanded = false, setExpanded] = useControllableState({
|
|
58
|
+
prop: expanded,
|
|
59
|
+
defaultProp: defaultExpanded,
|
|
60
|
+
onChange: onExpandedChange
|
|
61
|
+
});
|
|
62
|
+
const [initial] = useState(() => ({
|
|
63
|
+
completed: new Set(items.filter((item) => item.status === "completed").map((item) => item.id)),
|
|
64
|
+
current: summarize(items).current
|
|
65
|
+
}));
|
|
66
|
+
if (items.length === 0) return null;
|
|
67
|
+
const isDrawer = presentation === "drawer";
|
|
68
|
+
const { done, progress, current } = summarize(items);
|
|
69
|
+
return /* @__PURE__ */ jsxs("section", {
|
|
70
|
+
"aria-label": title,
|
|
71
|
+
className: cn("flex min-w-0 max-w-full flex-col font-sans text-primary", isDrawer ? cn("bg-surface-level-2 px-space-4 py-space-2", ENTER, "duration-normal") : "rounded-lg border border-subtle bg-elevated px-space-3 py-space-2", className),
|
|
72
|
+
children: [/* @__PURE__ */ jsxs(Button, {
|
|
73
|
+
type: "button",
|
|
74
|
+
variant: "plain",
|
|
75
|
+
color: "secondary",
|
|
76
|
+
size: "sm",
|
|
77
|
+
"aria-label": `${title}: ${progress}`,
|
|
78
|
+
"aria-describedby": current && !isExpanded ? currentId : void 0,
|
|
79
|
+
"aria-expanded": isExpanded,
|
|
80
|
+
"aria-controls": listId,
|
|
81
|
+
onClick: () => setExpanded(!isExpanded),
|
|
82
|
+
className: "h-auto min-w-0 justify-start gap-space-2 border-0 bg-transparent px-0 py-space-1 text-left shadow-none hover:bg-transparent",
|
|
83
|
+
children: [
|
|
84
|
+
/* @__PURE__ */ jsx(CircularProgress, {
|
|
85
|
+
size: 14,
|
|
86
|
+
strokeWidth: 2,
|
|
87
|
+
segments: [{
|
|
88
|
+
variant: "success",
|
|
89
|
+
percentage: done / items.length
|
|
90
|
+
}],
|
|
91
|
+
className: "shrink-0"
|
|
92
|
+
}),
|
|
93
|
+
/* @__PURE__ */ jsx(Text, {
|
|
94
|
+
as: "span",
|
|
95
|
+
variant: "xs",
|
|
96
|
+
weight: "medium",
|
|
97
|
+
className: "shrink-0",
|
|
98
|
+
children: title
|
|
99
|
+
}),
|
|
100
|
+
/* @__PURE__ */ jsx(Text, {
|
|
101
|
+
as: "span",
|
|
102
|
+
variant: "xs",
|
|
103
|
+
color: "secondary",
|
|
104
|
+
className: "shrink-0 tabular-nums",
|
|
105
|
+
children: progress
|
|
106
|
+
}),
|
|
107
|
+
current && !isExpanded && /* @__PURE__ */ jsx(Text, {
|
|
108
|
+
id: currentId,
|
|
109
|
+
as: "span",
|
|
110
|
+
variant: "xs",
|
|
111
|
+
color: "tertiary",
|
|
112
|
+
className: cn("min-w-0 truncate", current !== initial.current && cn(ENTER, "slide-in-from-bottom-1 duration-normal")),
|
|
113
|
+
children: current
|
|
114
|
+
}, current),
|
|
115
|
+
/* @__PURE__ */ jsx(ChatToolCallCaret, {
|
|
116
|
+
open: isExpanded,
|
|
117
|
+
className: "ml-auto"
|
|
118
|
+
})
|
|
119
|
+
]
|
|
120
|
+
}), /* @__PURE__ */ jsx(ChatToolCallCollapse, {
|
|
121
|
+
open: isExpanded,
|
|
122
|
+
id: listId,
|
|
123
|
+
children: /* @__PURE__ */ jsx("ol", {
|
|
124
|
+
"aria-label": `${title} tasks`,
|
|
125
|
+
className: cn("m-0 flex list-none flex-col gap-space-1 p-0 pb-space-1 pt-space-1", isDrawer && "max-h-[min(12rem,30dvh)] overflow-y-auto overscroll-contain"),
|
|
126
|
+
children: items.map((item) => {
|
|
127
|
+
const { icon: StatusIcon, iconClassName, label, textColor } = ITEM_PRESENTATIONS[item.status];
|
|
128
|
+
const justCompleted = item.status === "completed" && !initial.completed.has(item.id);
|
|
129
|
+
return /* @__PURE__ */ jsxs("li", {
|
|
130
|
+
"data-status": item.status,
|
|
131
|
+
className: "flex min-w-0 items-start gap-space-2",
|
|
132
|
+
children: [/* @__PURE__ */ jsx(StatusIcon, {
|
|
133
|
+
size: 14,
|
|
134
|
+
weight: "regular",
|
|
135
|
+
"aria-hidden": "true",
|
|
136
|
+
className: cn("mt-0.5 shrink-0", iconClassName, justCompleted && cn(ENTER, "zoom-in-75 duration-normal"))
|
|
137
|
+
}, item.status), /* @__PURE__ */ jsxs(Text, {
|
|
138
|
+
as: "span",
|
|
139
|
+
variant: "xs",
|
|
140
|
+
color: textColor,
|
|
141
|
+
className: "min-w-0 leading-5 transition-colors duration-slow [overflow-wrap:anywhere] motion-reduce:transition-none",
|
|
142
|
+
children: [item.label, /* @__PURE__ */ jsx("span", {
|
|
143
|
+
className: "sr-only",
|
|
144
|
+
children: ` (${label})`
|
|
145
|
+
})]
|
|
146
|
+
})]
|
|
147
|
+
}, item.id);
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
})]
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
export { ChatPlan };
|
|
155
|
+
|
|
156
|
+
//# sourceMappingURL=ChatPlan.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ChatPlan.js","names":[],"sources":["../../../src/components/ChatPlan/ChatPlan.tsx"],"sourcesContent":["import { useId, useState } from 'react';\n\nimport { CheckCircleIcon } from '@phosphor-icons/react/dist/ssr/CheckCircle';\nimport { CircleIcon } from '@phosphor-icons/react/dist/ssr/Circle';\nimport { CircleDashedIcon } from '@phosphor-icons/react/dist/ssr/CircleDashed';\nimport { useControllableState } from '@radix-ui/react-use-controllable-state';\n\nimport { cn } from '../../utils/cn';\nimport { Button } from '../Button';\nimport { ChatToolCallCaret } from '../ChatToolCall/ChatToolCallCaret';\nimport { ChatToolCallCollapse } from '../ChatToolCall/ChatToolCallCollapse';\nimport { CircularProgress } from '../CircularProgress';\nimport { Text } from '../Text';\n\nexport type ChatPlanItemStatus = 'pending' | 'in-progress' | 'completed';\n\nexport interface ChatPlanItem {\n /** Stable across updates, so items keep their place as the plan changes. */\n id: string;\n label: string;\n status: ChatPlanItemStatus;\n}\n\nexport interface ChatPlanProps {\n /** Items in the agent's order. Renders nothing when empty. */\n items: readonly ChatPlanItem[];\n /** Defaults to \"Plan\". */\n title?: string;\n /**\n * `drawer` fits `ChatComposer`'s drawer slot, alone or stacked with other\n * drawer content.\n */\n presentation?: 'block' | 'drawer';\n expanded?: boolean;\n defaultExpanded?: boolean;\n onExpandedChange?: (expanded: boolean) => void;\n className?: string;\n}\n\n// Outline icons in ChatState's colors, so a plan reads like the rest of the chat.\nconst ITEM_PRESENTATIONS = {\n pending: {\n label: 'Pending',\n icon: CircleIcon,\n iconClassName: 'text-icon-tertiary',\n textColor: 'secondary',\n },\n 'in-progress': {\n label: 'In progress',\n icon: CircleDashedIcon,\n iconClassName: 'text-icon-secondary',\n textColor: 'primary',\n },\n completed: {\n label: 'Completed',\n icon: CheckCircleIcon,\n iconClassName: 'text-icon-success',\n textColor: 'tertiary',\n },\n} as const;\n\nconst ENTER =\n 'animate-in fade-in ease-[cubic-bezier(0.32,0.72,0,1)] motion-reduce:animate-none';\n\nfunction summarize(items: readonly ChatPlanItem[]) {\n const total = items.length;\n const done = items.filter((item) => item.status === 'completed').length;\n const currentIndex = items.findIndex((item) => item.status === 'in-progress');\n if (currentIndex !== -1) {\n return {\n done,\n progress: `Task ${currentIndex + 1} of ${total}`,\n current: items[currentIndex].label,\n };\n }\n return {\n done,\n progress: done === total ? `All ${total} done` : `${done} of ${total} done`,\n current: undefined,\n };\n}\n\n/**\n * An agent's task list, such as the todos a deep agent writes as it works.\n * Collapsed, it shows progress and the current task; expanded, every task.\n */\nexport function ChatPlan({\n items,\n title = 'Plan',\n presentation = 'block',\n expanded,\n defaultExpanded = false,\n onExpandedChange,\n className,\n}: ChatPlanProps) {\n const listId = useId();\n const currentId = useId();\n const [isExpanded = false, setExpanded] = useControllableState({\n prop: expanded,\n defaultProp: defaultExpanded,\n onChange: onExpandedChange,\n });\n // A plan restored from history appears at rest; only changes animate.\n const [initial] = useState(() => ({\n completed: new Set(\n items.filter((item) => item.status === 'completed').map((item) => item.id)\n ),\n current: summarize(items).current,\n }));\n if (items.length === 0) return null;\n\n const isDrawer = presentation === 'drawer';\n const { done, progress, current } = summarize(items);\n\n return (\n <section\n aria-label={title}\n className={cn(\n 'flex min-w-0 max-w-full flex-col font-sans text-primary',\n isDrawer\n ? // Its own neutral surface keeps the plan neutral when it shares a\n // drawer whose intent colors a question or notice.\n cn(\n 'bg-surface-level-2 px-space-4 py-space-2',\n ENTER,\n 'duration-normal'\n )\n : 'rounded-lg border border-subtle bg-elevated px-space-3 py-space-2',\n className\n )}\n >\n <Button\n type=\"button\"\n variant=\"plain\"\n color=\"secondary\"\n size=\"sm\"\n aria-label={`${title}: ${progress}`}\n aria-describedby={current && !isExpanded ? currentId : undefined}\n aria-expanded={isExpanded}\n aria-controls={listId}\n onClick={() => setExpanded(!isExpanded)}\n className=\"h-auto min-w-0 justify-start gap-space-2 border-0 bg-transparent px-0 py-space-1 text-left shadow-none hover:bg-transparent\"\n >\n <CircularProgress\n size={14}\n strokeWidth={2}\n segments={[{ variant: 'success', percentage: done / items.length }]}\n className=\"shrink-0\"\n />\n <Text as=\"span\" variant=\"xs\" weight=\"medium\" className=\"shrink-0\">\n {title}\n </Text>\n <Text\n as=\"span\"\n variant=\"xs\"\n color=\"secondary\"\n className=\"shrink-0 tabular-nums\"\n >\n {progress}\n </Text>\n {current && !isExpanded && (\n <Text\n // The next task crossfades in as the agent moves on.\n key={current}\n id={currentId}\n as=\"span\"\n variant=\"xs\"\n color=\"tertiary\"\n className={cn(\n 'min-w-0 truncate',\n current !== initial.current &&\n cn(ENTER, 'slide-in-from-bottom-1 duration-normal')\n )}\n >\n {current}\n </Text>\n )}\n <ChatToolCallCaret open={isExpanded} className=\"ml-auto\" />\n </Button>\n <ChatToolCallCollapse open={isExpanded} id={listId}>\n <ol\n aria-label={`${title} tasks`}\n className={cn(\n 'm-0 flex list-none flex-col gap-space-1 p-0 pb-space-1 pt-space-1',\n // Short enough that a question sharing the drawer stays in view.\n isDrawer &&\n 'max-h-[min(12rem,30dvh)] overflow-y-auto overscroll-contain'\n )}\n >\n {items.map((item) => {\n const {\n icon: StatusIcon,\n iconClassName,\n label,\n textColor,\n } = ITEM_PRESENTATIONS[item.status];\n const justCompleted =\n item.status === 'completed' && !initial.completed.has(item.id);\n return (\n <li\n key={item.id}\n data-status={item.status}\n className=\"flex min-w-0 items-start gap-space-2\"\n >\n <StatusIcon\n // Remounts on each status change so a new check pops in.\n key={item.status}\n size={14}\n weight=\"regular\"\n aria-hidden=\"true\"\n className={cn(\n 'mt-0.5 shrink-0',\n iconClassName,\n justCompleted && cn(ENTER, 'zoom-in-75 duration-normal')\n )}\n />\n <Text\n as=\"span\"\n variant=\"xs\"\n color={textColor}\n className=\"min-w-0 leading-5 transition-colors duration-slow [overflow-wrap:anywhere] motion-reduce:transition-none\"\n >\n {item.label}\n <span className=\"sr-only\">{` (${label})`}</span>\n </Text>\n </li>\n );\n })}\n </ol>\n </ChatToolCallCollapse>\n </section>\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAwCA,IAAM,qBAAqB;CACzB,SAAS;EACP,OAAO;EACP,MAAM;EACN,eAAe;EACf,WAAW;CACb;CACA,eAAe;EACb,OAAO;EACP,MAAM;EACN,eAAe;EACf,WAAW;CACb;CACA,WAAW;EACT,OAAO;EACP,MAAM;EACN,eAAe;EACf,WAAW;CACb;AACF;AAEA,IAAM,QACJ;AAEF,SAAS,UAAU,OAAgC;CACjD,MAAM,QAAQ,MAAM;CACpB,MAAM,OAAO,MAAM,QAAQ,SAAS,KAAK,WAAW,WAAW,CAAC,CAAC;CACjE,MAAM,eAAe,MAAM,WAAW,SAAS,KAAK,WAAW,aAAa;CAC5E,IAAI,iBAAiB,IACnB,OAAO;EACL;EACA,UAAU,QAAQ,eAAe,EAAE,MAAM;EACzC,SAAS,MAAM,aAAa,CAAC;CAC/B;CAEF,OAAO;EACL;EACA,UAAU,SAAS,QAAQ,OAAO,MAAM,SAAS,GAAG,KAAK,MAAM,MAAM;EACrE,SAAS,KAAA;CACX;AACF;;;;;AAMA,SAAgB,SAAS,EACvB,OACA,QAAQ,QACR,eAAe,SACf,UACA,kBAAkB,OAClB,kBACA,aACgB;CAChB,MAAM,SAAS,MAAM;CACrB,MAAM,YAAY,MAAM;CACxB,MAAM,CAAC,aAAa,OAAO,eAAe,qBAAqB;EAC7D,MAAM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