@langchain/macaw-components 1.7.8 → 1.7.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/catalog.json +771 -741
  2. package/dist/components/ChatComposer/ChatComposer.d.ts +10 -1
  3. package/dist/components/ChatComposer/ChatComposer.js +16 -9
  4. package/dist/components/ChatComposer/ChatComposer.js.map +1 -1
  5. package/dist/components/ChatComposer/ChatComposerContext.d.ts +1 -1
  6. package/dist/components/ChatComposer/ChatComposerContext.js.map +1 -1
  7. package/dist/components/ChatComposer/ChatComposerRichInput.js +13 -2
  8. package/dist/components/ChatComposer/ChatComposerRichInput.js.map +1 -1
  9. package/dist/components/ChatMessage/ChatMessage.d.ts +4 -3
  10. package/dist/components/ChatMessage/ChatMessage.js +17 -6
  11. package/dist/components/ChatMessage/ChatMessage.js.map +1 -1
  12. package/dist/components/ChatMessage/ChatMessage.types.d.ts +2 -0
  13. package/dist/components/ChatPlan/ChatPlan.d.ts +27 -0
  14. package/dist/components/ChatPlan/ChatPlan.js +156 -0
  15. package/dist/components/ChatPlan/ChatPlan.js.map +1 -0
  16. package/dist/components/ChatPlan/index.d.ts +2 -0
  17. package/dist/components/ChatPlan/index.js +2 -0
  18. package/dist/components/ChatRichContent/ChatRichContent.js +79 -28
  19. package/dist/components/ChatRichContent/ChatRichContent.js.map +1 -1
  20. package/dist/components/ChatRichContent/ChatRichContent.types.d.ts +18 -0
  21. package/dist/components/ChatRichContent/index.d.ts +1 -1
  22. package/dist/components/ChatState/ChatState.d.ts +14 -1
  23. package/dist/components/ChatState/ChatState.js +6 -5
  24. package/dist/components/ChatState/ChatState.js.map +1 -1
  25. package/dist/components/ChatState/ChatStateTimer.d.ts +3 -1
  26. package/dist/components/ChatState/ChatStateTimer.js +24 -11
  27. package/dist/components/ChatState/ChatStateTimer.js.map +1 -1
  28. package/dist/components/ChatState/formatChatDuration.d.ts +16 -0
  29. package/dist/components/ChatState/formatChatDuration.js +19 -0
  30. package/dist/components/ChatState/formatChatDuration.js.map +1 -0
  31. package/dist/components/ChatState/index.d.ts +2 -0
  32. package/dist/components/ChatState/index.js +2 -1
  33. package/dist/components/ChatToolCall/ChatToolCall.d.ts +12 -2
  34. package/dist/components/ChatToolCall/ChatToolCall.js +29 -15
  35. package/dist/components/ChatToolCall/ChatToolCall.js.map +1 -1
  36. package/dist/components/ChatToolCall/ChatToolCallAccordion.d.ts +3 -1
  37. package/dist/components/ChatToolCall/ChatToolCallAccordion.js +40 -26
  38. package/dist/components/ChatToolCall/ChatToolCallAccordion.js.map +1 -1
  39. package/dist/components/ChatToolCall/ChatToolCallCaret.d.ts +5 -0
  40. package/dist/components/ChatToolCall/ChatToolCallCaret.js +20 -0
  41. package/dist/components/ChatToolCall/ChatToolCallCaret.js.map +1 -0
  42. package/dist/components/ChatToolCall/ChatToolCallCollapse.d.ts +12 -0
  43. package/dist/components/ChatToolCall/ChatToolCallCollapse.js +66 -0
  44. package/dist/components/ChatToolCall/ChatToolCallCollapse.js.map +1 -0
  45. package/dist/components/ChatToolCall/ChatToolCallGroup.d.ts +20 -2
  46. package/dist/components/ChatToolCall/ChatToolCallGroup.js +52 -37
  47. package/dist/components/ChatToolCall/ChatToolCallGroup.js.map +1 -1
  48. package/dist/components/ChatToolCall/ChatToolCallGroupContext.d.ts +24 -0
  49. package/dist/components/ChatToolCall/ChatToolCallGroupContext.js +61 -0
  50. package/dist/components/ChatToolCall/ChatToolCallGroupContext.js.map +1 -0
  51. package/dist/components/ChatToolCall/ChatToolCallIcon.d.ts +4 -0
  52. package/dist/components/ChatToolCall/ChatToolCallIcon.js +13 -0
  53. package/dist/components/ChatToolCall/ChatToolCallIcon.js.map +1 -0
  54. package/dist/components/ChatToolCall/ChatToolCallReasoning.d.ts +11 -3
  55. package/dist/components/ChatToolCall/ChatToolCallReasoning.js +34 -17
  56. package/dist/components/ChatToolCall/ChatToolCallReasoning.js.map +1 -1
  57. package/dist/components/ChatToolCall/ChatToolCallRowStatus.d.ts +14 -0
  58. package/dist/components/ChatToolCall/ChatToolCallRowStatus.js +25 -0
  59. package/dist/components/ChatToolCall/ChatToolCallRowStatus.js.map +1 -0
  60. package/dist/components/ChatToolCall/ChatToolCallStatusRow.d.ts +3 -1
  61. package/dist/components/ChatToolCall/ChatToolCallStatusRow.js +29 -18
  62. package/dist/components/ChatToolCall/ChatToolCallStatusRow.js.map +1 -1
  63. package/dist/utilities.css +1 -1
  64. package/docs/CHAT.md +45 -1
  65. package/docs/DESIGN.md +10 -6
  66. package/package.json +6 -2
@@ -2,7 +2,11 @@ import type { ComponentPropsWithRef, ReactNode } from 'react';
2
2
  import type { IconButtonProps } from '../IconButton/index.js';
3
3
  export type ChatComposerDrawerIntent = 'neutral' | 'info' | 'warning' | 'error';
4
4
  export type ChatComposerProps = ComponentPropsWithRef<'form'> & {
5
- /** Supplementary content attached above the editor, inside the composer form. */
5
+ /**
6
+ * Supplementary content attached above the editor, inside the composer form.
7
+ * Several items, such as a plan and a question, stack with dividers; put the
8
+ * one the input answers last, next to it.
9
+ */
6
10
  drawer?: ReactNode;
7
11
  /**
8
12
  * Drawer surface color. Color alone doesn't convey severity, so the drawer
@@ -23,6 +27,11 @@ export type ChatComposerProps = ComponentPropsWithRef<'form'> & {
23
27
  } | {
24
28
  action: 'stop';
25
29
  onStop: () => void;
30
+ }
31
+ /** A stop request is pending; Stop shows progress and sending stays blocked. */
32
+ | {
33
+ action: 'stopping';
34
+ onStop?: never;
26
35
  });
27
36
  export declare function ChatComposer({ children, drawer, drawerIntent, className, ref, disabled, submitDisabled, action, onStop, onSubmit, onFilesSelected, onDragOver, onDragLeave, onDropCapture, onPasteCapture, noValidate, ...props }: ChatComposerProps): import("react").JSX.Element;
28
37
  export interface ChatComposerToolbarProps extends ComponentPropsWithRef<'div'> {
@@ -8,14 +8,15 @@ import { jsx, jsxs } from "react/jsx-runtime";
8
8
  import { StopIcon } from "@phosphor-icons/react/dist/ssr/Stop";
9
9
  //#region packages/components/src/components/ChatComposer/ChatComposer.tsx
10
10
  var DRAWER_INTENT_CLASSES = {
11
- neutral: "border-subtle bg-surface-level-2",
12
- info: "border-brand-subtle bg-brand-subtle",
13
- warning: "border-warning bg-warning",
14
- error: "border-error bg-error"
11
+ neutral: "border-subtle divide-subtle bg-surface-level-2",
12
+ info: "border-brand-subtle divide-brand-subtle bg-brand-subtle",
13
+ warning: "border-warning divide-warning bg-warning",
14
+ error: "border-error divide-error bg-error"
15
15
  };
16
16
  function isAttachmentTargetBlocked(target) {
17
17
  return target instanceof Element && target.closest(":disabled, [readonly], [aria-disabled=\"true\"], [aria-readonly=\"true\"]") !== null;
18
18
  }
19
+ var COMPOSER_CLICK_TARGET_SELECTOR = "a[href], button, input, select, textarea, label, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"]), [role=\"button\"], [role=\"link\"], [role=\"menuitem\"], [role=\"option\"], [role=\"combobox\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"switch\"], [role=\"tab\"]";
19
20
  function reportFieldsetValidity(fieldset) {
20
21
  for (const element of fieldset?.elements ?? []) if ((element instanceof HTMLInputElement || element instanceof HTMLSelectElement || element instanceof HTMLTextAreaElement) && !element.reportValidity()) return false;
21
22
  return true;
@@ -87,11 +88,15 @@ function ChatComposer({ children, drawer, drawerIntent = "neutral", className, r
87
88
  },
88
89
  children: [hasDrawer && /* @__PURE__ */ jsx("fieldset", {
89
90
  disabled,
90
- className: cn("mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none", DRAWER_INTENT_CLASSES[drawerIntent], disabled && "border-disabled"),
91
+ className: cn("mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 divide-y overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none", DRAWER_INTENT_CLASSES[drawerIntent], disabled && "border-disabled divide-disabled"),
91
92
  children: drawer
92
93
  }), /* @__PURE__ */ jsx("fieldset", {
93
94
  ref: fieldsetRef,
94
95
  disabled: disabled && action !== "stop",
96
+ onClick: (event) => {
97
+ if (event.defaultPrevented || !(event.target instanceof Element) || event.target.closest(COMPOSER_CLICK_TARGET_SELECTOR) || window.getSelection()?.isCollapsed === false) return;
98
+ inputFocusRef.current?.();
99
+ },
95
100
  className: cn("relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-lg border border-subtle bg-elevated p-space-2 transition-[border-color,box-shadow,background-color] duration-normal motion-reduce:transition-none", "has-[:is(textarea,[contenteditable=true]):focus]:border-focus has-[:is(textarea,[contenteditable=true]):focus]:shadow-[0_0_0_1px_var(--border-focus)]", disabled && "border-disabled bg-input-disabled", isDropTarget && !disabled && "border-focus bg-surface-level-2 shadow-[0_0_0_1px_var(--border-focus)]"),
96
101
  children
97
102
  })]
@@ -117,22 +122,24 @@ function ChatComposerToolbar({ children, modelSelector, actions = /* @__PURE__ *
117
122
  var ACTION_LABELS = {
118
123
  send: "Send message",
119
124
  sending: "Sending message",
120
- stop: "Stop response"
125
+ stop: "Stop response",
126
+ stopping: "Stopping response"
121
127
  };
122
128
  function ChatComposerAction({ disabled, label, ...props }) {
123
129
  const composer = useChatComposerContext();
124
130
  const isStop = composer.action === "stop";
131
+ const isStopping = composer.action === "stopping";
125
132
  return /* @__PURE__ */ jsx(IconButton, {
126
133
  size: "sm",
127
134
  round: true,
128
135
  color: "primary",
129
136
  iconWeight: "regular",
130
137
  ...props,
131
- type: isStop ? "button" : "submit",
132
- icon: isStop ? StopIcon : ArrowUpIcon,
138
+ type: isStop || isStopping ? "button" : "submit",
139
+ icon: isStop || isStopping ? StopIcon : ArrowUpIcon,
133
140
  label: label ?? ACTION_LABELS[composer.action],
134
141
  disabled: disabled || !isStop && !composer.canSubmit,
135
- loading: composer.action === "sending",
142
+ loading: composer.action === "sending" || isStopping,
136
143
  onClick: isStop ? composer.onStop : void 0
137
144
  });
138
145
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ChatComposer.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposer.tsx"],"sourcesContent":["import type { ComponentPropsWithRef, ReactNode } from 'react';\nimport { useRef, useState } from 'react';\n\nimport { ArrowUpIcon } from '@phosphor-icons/react/dist/ssr/ArrowUp';\nimport { StopIcon } from '@phosphor-icons/react/dist/ssr/Stop';\n\nimport { cn } from '../../utils/cn';\nimport { mergeRefs } from '../../utils/merge-refs';\nimport { IconButton } from '../IconButton';\nimport type { IconButtonProps } from '../IconButton';\nimport {\n ChatComposerContext,\n type ChatComposerContextValue,\n useChatComposerContext,\n} from './ChatComposerContext';\n\nexport type ChatComposerDrawerIntent = 'neutral' | 'info' | 'warning' | 'error';\n\nconst DRAWER_INTENT_CLASSES: Record<ChatComposerDrawerIntent, string> = {\n neutral: 'border-subtle bg-surface-level-2',\n info: 'border-brand-subtle bg-brand-subtle',\n warning: 'border-warning bg-warning',\n error: 'border-error bg-error',\n};\n\nexport type ChatComposerProps = ComponentPropsWithRef<'form'> & {\n /** Supplementary content attached above the editor, inside the composer form. */\n drawer?: ReactNode;\n /**\n * Drawer surface color. Color alone doesn't convey severity, so the drawer\n * content should also say it in text or with an icon.\n */\n drawerIntent?: ChatComposerDrawerIntent;\n /**\n * Blocks writing and sending. Stop stays available while `action` is\n * `stop`, so host controls inside the composer must take `disabled`\n * themselves to stay disabled during a response.\n */\n disabled?: boolean;\n submitDisabled?: boolean;\n onFilesSelected?: (files: File[]) => void;\n} & (\n | { action?: 'send' | 'sending'; onStop?: never }\n | { action: 'stop'; onStop: () => void }\n );\n\n// A disabled or read-only part of the composer, such as a read-only message\n// input, does not accept input, so files dropped or pasted onto it are not\n// attached either.\nfunction isAttachmentTargetBlocked(target: EventTarget) {\n return (\n target instanceof Element &&\n target.closest(\n ':disabled, [readonly], [aria-disabled=\"true\"], [aria-readonly=\"true\"]'\n ) !== null\n );\n}\n\n// A fieldset is barred from constraint validation, so its own\n// reportValidity() never inspects the controls inside it.\nfunction reportFieldsetValidity(fieldset: HTMLFieldSetElement | null) {\n for (const element of fieldset?.elements ?? []) {\n if (\n (element instanceof HTMLInputElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement) &&\n !element.reportValidity()\n )\n return false;\n }\n return true;\n}\n\nexport function ChatComposer({\n children,\n drawer,\n drawerIntent = 'neutral',\n className,\n ref,\n disabled = false,\n submitDisabled = false,\n action = 'send',\n onStop,\n onSubmit,\n onFilesSelected,\n onDragOver,\n onDragLeave,\n onDropCapture,\n onPasteCapture,\n noValidate,\n ...props\n}: ChatComposerProps) {\n const formRef = useRef<HTMLFormElement>(null);\n const [isDropTarget, setIsDropTarget] = useState(false);\n const canSubmit =\n !disabled && !submitDisabled && action === 'send' && !!onSubmit;\n const hasDrawer = Boolean(drawer);\n const fieldsetRef = useRef<HTMLFieldSetElement>(null);\n const inputFocusRef = useRef<(() => boolean) | null>(null);\n // Inert drawer fields cannot be focused to report errors, so the drawer's\n // host validates them; fields outside the drawer keep native checks.\n const validatesFieldsetOnly = noValidate === undefined && hasDrawer;\n\n return (\n <ChatComposerContext.Provider\n value={{\n disabled,\n canSubmit,\n action,\n onStop,\n onFilesSelected,\n inputFocusRef,\n submit: onSubmit\n ? () => {\n if (canSubmit) formRef.current?.requestSubmit();\n }\n : undefined,\n }}\n >\n <form\n {...props}\n ref={mergeRefs([formRef, ref])}\n noValidate={noValidate ?? hasDrawer}\n className={cn('isolate w-full min-w-0 @container/composer', className)}\n onSubmit={(event) => {\n event.preventDefault();\n if (!canSubmit) return;\n if (\n validatesFieldsetOnly &&\n !reportFieldsetValidity(fieldsetRef.current)\n )\n return;\n onSubmit?.(event);\n }}\n onDragOver={(event) => {\n onDragOver?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n if (!event.dataTransfer.types.includes('Files')) return;\n event.preventDefault();\n const canAttach =\n !disabled && !isAttachmentTargetBlocked(event.target);\n event.dataTransfer.dropEffect = canAttach ? 'copy' : 'none';\n setIsDropTarget(canAttach);\n }}\n onDragLeave={(event) => {\n onDragLeave?.(event);\n if (\n !(event.relatedTarget instanceof Node) ||\n !event.currentTarget.contains(event.relatedTarget)\n ) {\n setIsDropTarget(false);\n }\n }}\n onDropCapture={(event) => {\n onDropCapture?.(event);\n setIsDropTarget(false);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.dataTransfer.files);\n if (!files.length) return;\n event.preventDefault();\n if (!disabled && !isAttachmentTargetBlocked(event.target)) {\n onFilesSelected(files);\n }\n }}\n onPasteCapture={(event) => {\n onPasteCapture?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.clipboardData.files);\n if (!files.length) return;\n if (disabled || isAttachmentTargetBlocked(event.target)) {\n event.preventDefault();\n return;\n }\n // Let the focused editor preserve mixed-paste text and its selection.\n if (!event.clipboardData.getData('text/plain')) {\n event.preventDefault();\n }\n onFilesSelected(files);\n }}\n >\n {hasDrawer && (\n <fieldset\n disabled={disabled}\n className={cn(\n // Extends under the composer's rounded top so the seam stays hidden.\n 'mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none',\n DRAWER_INTENT_CLASSES[drawerIntent],\n disabled && 'border-disabled'\n )}\n >\n {drawer}\n </fieldset>\n )}\n <fieldset\n ref={fieldsetRef}\n // A disabled fieldset would also disable Stop; the composer's own\n // parts read `disabled` from context instead.\n disabled={disabled && action !== 'stop'}\n className={cn(\n 'relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-lg border border-subtle bg-elevated p-space-2 transition-[border-color,box-shadow,background-color] duration-normal motion-reduce:transition-none',\n // Toolbar menus portal out, so focus-within would flash as focus\n // moves from their trigger to the menu; only typing shows focus.\n 'has-[:is(textarea,[contenteditable=true]):focus]:border-focus has-[:is(textarea,[contenteditable=true]):focus]:shadow-[0_0_0_1px_var(--border-focus)]',\n disabled && 'border-disabled bg-input-disabled',\n isDropTarget &&\n !disabled &&\n 'border-focus bg-surface-level-2 shadow-[0_0_0_1px_var(--border-focus)]'\n )}\n >\n {children}\n </fieldset>\n </form>\n </ChatComposerContext.Provider>\n );\n}\n\nexport interface ChatComposerToolbarProps extends ComponentPropsWithRef<'div'> {\n modelSelector?: ReactNode;\n actions?: ReactNode;\n}\n\nexport function ChatComposerToolbar({\n children,\n modelSelector,\n actions = <ChatComposerAction />,\n className,\n ...props\n}: ChatComposerToolbarProps) {\n return (\n <div\n {...props}\n className={cn('flex min-w-0 items-center gap-space-2', className)}\n >\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-space-1 @[440px]/composer:gap-space-2\">\n {children}\n {modelSelector != null && (\n <div className=\"min-w-0 max-w-full [&>*]:max-w-full\">\n {modelSelector}\n </div>\n )}\n </div>\n <div className=\"flex shrink-0 items-center gap-space-1\">{actions}</div>\n </div>\n );\n}\n\nconst ACTION_LABELS = {\n send: 'Send message',\n sending: 'Sending message',\n stop: 'Stop response',\n} satisfies Record<ChatComposerContextValue['action'], string>;\n\n// Pending sends use the composer's action=\"sending\", which also blocks the\n// send shortcuts; a button-level loading state would only block clicks.\nexport type ChatComposerActionProps = Omit<\n IconButtonProps,\n 'icon' | 'type' | 'onClick' | 'asChild' | 'label' | 'loading'\n> & { label?: string };\n\nexport function ChatComposerAction({\n disabled,\n label,\n ...props\n}: ChatComposerActionProps) {\n const composer = useChatComposerContext();\n const isStop = composer.action === 'stop';\n return (\n <IconButton\n size=\"sm\"\n round\n color=\"primary\"\n iconWeight=\"regular\"\n {...props}\n type={isStop ? 'button' : 'submit'}\n icon={isStop ? StopIcon : ArrowUpIcon}\n label={label ?? ACTION_LABELS[composer.action]}\n // canSubmit already accounts for a disabled composer; Stop ignores it.\n disabled={disabled || (!isStop && !composer.canSubmit)}\n loading={composer.action === 'sending'}\n onClick={isStop ? composer.onStop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ACO,CAAA,CACN;;CACsB,CAAA;AAElC;AAOA,SAAgB,oBAAoB,EAClC,UACA,eACA,UAAU,oBAAC,oBAAD,CAAqB,CAAA,GAC/B,WACA,GAAG,SACwB;CAC3B,OACE,qBAAC,OAAD;EACE,GAAI;EACJ,WAAW,GAAG,yCAAyC,SAAS;EAFlE,UAAA,CAIE,qBAAC,OAAD;GAAK,WAAU;GAAf,UAAA,CACG,UACA,iBAAiB,QAChB,oBAAC,OAAD;IAAK,WAAU;IACZ,UAAA;GACE,CAAA,CAEJ;EACL,CAAA,GAAA,oBAAC,OAAD;GAAK,WAAU;GAA0C,UAAA;EAAa,CAAA,CACnE;;AAET;AAEA,IAAM,gBAAgB;CACpB,MAAM;CACN,SAAS;CACT,MAAM;AACR;AASA,SAAgB,mBAAmB,EACjC,UACA,OACA,GAAG,SACuB;CAC1B,MAAM,WAAW,uBAAuB;CACxC,MAAM,SAAS,SAAS,WAAW;CACnC,OACE,oBAAC,YAAD;EACE,MAAK;EACL,OAAA;EACA,OAAM;EACN,YAAW;EACX,GAAI;EACJ,MAAM,SAAS,WAAW;EAC1B,MAAM,SAAS,WAAW;EAC1B,OAAO,SAAS,cAAc,SAAS;EAEvC,UAAU,YAAa,CAAC,UAAU,CAAC,SAAS;EAC5C,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,SAAS,SAAS,KAAA;CACrC,CAAA;AAEL"}
1
+ {"version":3,"file":"ChatComposer.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposer.tsx"],"sourcesContent":["import type { ComponentPropsWithRef, ReactNode } from 'react';\nimport { useRef, useState } from 'react';\n\nimport { ArrowUpIcon } from '@phosphor-icons/react/dist/ssr/ArrowUp';\nimport { StopIcon } from '@phosphor-icons/react/dist/ssr/Stop';\n\nimport { cn } from '../../utils/cn';\nimport { mergeRefs } from '../../utils/merge-refs';\nimport { IconButton } from '../IconButton';\nimport type { IconButtonProps } from '../IconButton';\nimport {\n ChatComposerContext,\n type ChatComposerContextValue,\n useChatComposerContext,\n} from './ChatComposerContext';\n\nexport type ChatComposerDrawerIntent = 'neutral' | 'info' | 'warning' | 'error';\n\n// Dividers match the drawer border, so stacked drawer content reads as one surface.\nconst DRAWER_INTENT_CLASSES: Record<ChatComposerDrawerIntent, string> = {\n neutral: 'border-subtle divide-subtle bg-surface-level-2',\n info: 'border-brand-subtle divide-brand-subtle bg-brand-subtle',\n warning: 'border-warning divide-warning bg-warning',\n error: 'border-error divide-error bg-error',\n};\n\nexport type ChatComposerProps = ComponentPropsWithRef<'form'> & {\n /**\n * Supplementary content attached above the editor, inside the composer form.\n * Several items, such as a plan and a question, stack with dividers; put the\n * one the input answers last, next to it.\n */\n drawer?: ReactNode;\n /**\n * Drawer surface color. Color alone doesn't convey severity, so the drawer\n * content should also say it in text or with an icon.\n */\n drawerIntent?: ChatComposerDrawerIntent;\n /**\n * Blocks writing and sending. Stop stays available while `action` is\n * `stop`, so host controls inside the composer must take `disabled`\n * themselves to stay disabled during a response.\n */\n disabled?: boolean;\n submitDisabled?: boolean;\n onFilesSelected?: (files: File[]) => void;\n} & (\n | { action?: 'send' | 'sending'; onStop?: never }\n | { action: 'stop'; onStop: () => void }\n /** A stop request is pending; Stop shows progress and sending stays blocked. */\n | { action: 'stopping'; onStop?: never }\n );\n\n// A disabled or read-only part of the composer, such as a read-only message\n// input, does not accept input, so files dropped or pasted onto it are not\n// attached either.\nfunction isAttachmentTargetBlocked(target: EventTarget) {\n return (\n target instanceof Element &&\n target.closest(\n ':disabled, [readonly], [aria-disabled=\"true\"], [aria-readonly=\"true\"]'\n ) !== null\n );\n}\n\n// Clicks on the composer's own empty space go to the message input; clicks on\n// controls, fields, links, and the editor itself keep their behavior.\nconst COMPOSER_CLICK_TARGET_SELECTOR =\n 'a[href], button, input, select, textarea, label, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"]), [role=\"button\"], [role=\"link\"], [role=\"menuitem\"], [role=\"option\"], [role=\"combobox\"], [role=\"checkbox\"], [role=\"radio\"], [role=\"switch\"], [role=\"tab\"]';\n\n// A fieldset is barred from constraint validation, so its own\n// reportValidity() never inspects the controls inside it.\nfunction reportFieldsetValidity(fieldset: HTMLFieldSetElement | null) {\n for (const element of fieldset?.elements ?? []) {\n if (\n (element instanceof HTMLInputElement ||\n element instanceof HTMLSelectElement ||\n element instanceof HTMLTextAreaElement) &&\n !element.reportValidity()\n )\n return false;\n }\n return true;\n}\n\nexport function ChatComposer({\n children,\n drawer,\n drawerIntent = 'neutral',\n className,\n ref,\n disabled = false,\n submitDisabled = false,\n action = 'send',\n onStop,\n onSubmit,\n onFilesSelected,\n onDragOver,\n onDragLeave,\n onDropCapture,\n onPasteCapture,\n noValidate,\n ...props\n}: ChatComposerProps) {\n const formRef = useRef<HTMLFormElement>(null);\n const [isDropTarget, setIsDropTarget] = useState(false);\n const canSubmit =\n !disabled && !submitDisabled && action === 'send' && !!onSubmit;\n const hasDrawer = Boolean(drawer);\n const fieldsetRef = useRef<HTMLFieldSetElement>(null);\n const inputFocusRef = useRef<(() => boolean) | null>(null);\n // Inert drawer fields cannot be focused to report errors, so the drawer's\n // host validates them; fields outside the drawer keep native checks.\n const validatesFieldsetOnly = noValidate === undefined && hasDrawer;\n\n return (\n <ChatComposerContext.Provider\n value={{\n disabled,\n canSubmit,\n action,\n onStop,\n onFilesSelected,\n inputFocusRef,\n submit: onSubmit\n ? () => {\n if (canSubmit) formRef.current?.requestSubmit();\n }\n : undefined,\n }}\n >\n <form\n {...props}\n ref={mergeRefs([formRef, ref])}\n noValidate={noValidate ?? hasDrawer}\n className={cn('isolate w-full min-w-0 @container/composer', className)}\n onSubmit={(event) => {\n event.preventDefault();\n if (!canSubmit) return;\n if (\n validatesFieldsetOnly &&\n !reportFieldsetValidity(fieldsetRef.current)\n )\n return;\n onSubmit?.(event);\n }}\n onDragOver={(event) => {\n onDragOver?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n if (!event.dataTransfer.types.includes('Files')) return;\n event.preventDefault();\n const canAttach =\n !disabled && !isAttachmentTargetBlocked(event.target);\n event.dataTransfer.dropEffect = canAttach ? 'copy' : 'none';\n setIsDropTarget(canAttach);\n }}\n onDragLeave={(event) => {\n onDragLeave?.(event);\n if (\n !(event.relatedTarget instanceof Node) ||\n !event.currentTarget.contains(event.relatedTarget)\n ) {\n setIsDropTarget(false);\n }\n }}\n onDropCapture={(event) => {\n onDropCapture?.(event);\n setIsDropTarget(false);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.dataTransfer.files);\n if (!files.length) return;\n event.preventDefault();\n if (!disabled && !isAttachmentTargetBlocked(event.target)) {\n onFilesSelected(files);\n }\n }}\n onPasteCapture={(event) => {\n onPasteCapture?.(event);\n if (event.defaultPrevented || !onFilesSelected) return;\n const files = Array.from(event.clipboardData.files);\n if (!files.length) return;\n if (disabled || isAttachmentTargetBlocked(event.target)) {\n event.preventDefault();\n return;\n }\n // Let the focused editor preserve mixed-paste text and its selection.\n if (!event.clipboardData.getData('text/plain')) {\n event.preventDefault();\n }\n onFilesSelected(files);\n }}\n >\n {hasDrawer && (\n <fieldset\n disabled={disabled}\n className={cn(\n // Extends under the composer's rounded top so the seam stays hidden.\n 'mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 divide-y overflow-y-auto overscroll-contain rounded-t-lg border border-b-0 pb-space-3 duration-normal ease-out animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none',\n DRAWER_INTENT_CLASSES[drawerIntent],\n disabled && 'border-disabled divide-disabled'\n )}\n >\n {drawer}\n </fieldset>\n )}\n <fieldset\n ref={fieldsetRef}\n // A disabled fieldset would also disable Stop; the composer's own\n // parts read `disabled` from context instead.\n disabled={disabled && action !== 'stop'}\n onClick={(event) => {\n if (\n event.defaultPrevented ||\n !(event.target instanceof Element) ||\n event.target.closest(COMPOSER_CLICK_TARGET_SELECTOR) ||\n // Finishing a drag selection, such as in an attachment name.\n window.getSelection()?.isCollapsed === false\n )\n return;\n inputFocusRef.current?.();\n }}\n className={cn(\n 'relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-lg border border-subtle bg-elevated p-space-2 transition-[border-color,box-shadow,background-color] duration-normal motion-reduce:transition-none',\n // Toolbar menus portal out, so focus-within would flash as focus\n // moves from their trigger to the menu; only typing shows focus.\n 'has-[:is(textarea,[contenteditable=true]):focus]:border-focus has-[:is(textarea,[contenteditable=true]):focus]:shadow-[0_0_0_1px_var(--border-focus)]',\n disabled && 'border-disabled bg-input-disabled',\n isDropTarget &&\n !disabled &&\n 'border-focus bg-surface-level-2 shadow-[0_0_0_1px_var(--border-focus)]'\n )}\n >\n {children}\n </fieldset>\n </form>\n </ChatComposerContext.Provider>\n );\n}\n\nexport interface ChatComposerToolbarProps extends ComponentPropsWithRef<'div'> {\n modelSelector?: ReactNode;\n actions?: ReactNode;\n}\n\nexport function ChatComposerToolbar({\n children,\n modelSelector,\n actions = <ChatComposerAction />,\n className,\n ...props\n}: ChatComposerToolbarProps) {\n return (\n <div\n {...props}\n className={cn('flex min-w-0 items-center gap-space-2', className)}\n >\n <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-space-1 @[440px]/composer:gap-space-2\">\n {children}\n {modelSelector != null && (\n <div className=\"min-w-0 max-w-full [&>*]:max-w-full\">\n {modelSelector}\n </div>\n )}\n </div>\n <div className=\"flex shrink-0 items-center gap-space-1\">{actions}</div>\n </div>\n );\n}\n\nconst ACTION_LABELS = {\n send: 'Send message',\n sending: 'Sending message',\n stop: 'Stop response',\n stopping: 'Stopping response',\n} satisfies Record<ChatComposerContextValue['action'], string>;\n\n// Pending sends use the composer's action=\"sending\", which also blocks the\n// send shortcuts; a button-level loading state would only block clicks.\nexport type ChatComposerActionProps = Omit<\n IconButtonProps,\n 'icon' | 'type' | 'onClick' | 'asChild' | 'label' | 'loading'\n> & { label?: string };\n\nexport function ChatComposerAction({\n disabled,\n label,\n ...props\n}: ChatComposerActionProps) {\n const composer = useChatComposerContext();\n const isStop = composer.action === 'stop';\n const isStopping = composer.action === 'stopping';\n return (\n <IconButton\n size=\"sm\"\n round\n color=\"primary\"\n iconWeight=\"regular\"\n {...props}\n type={isStop || isStopping ? 'button' : 'submit'}\n icon={isStop || isStopping ? StopIcon : ArrowUpIcon}\n label={label ?? ACTION_LABELS[composer.action]}\n // canSubmit is false while disabled, sending, or stopping, so this also\n // disables Stop once a stop is pending; Stop ignores `disabled` otherwise.\n disabled={disabled || (!isStop && !composer.canSubmit)}\n loading={composer.action === 'sending' || isStopping}\n onClick={isStop ? composer.onStop : undefined}\n />\n );\n}\n"],"mappings":";;;;;;;;;AAmBA,IAAM,wBAAkE;CACtE,SAAS;CACT,MAAM;CACN,SAAS;CACT,OAAO;AACT;AAgCA,SAAS,0BAA0B,QAAqB;CACtD,OACE,kBAAkB,WAClB,OAAO,QACL,2EACF,MAAM;AAEV;AAIA,IAAM,iCACJ;AAIF,SAAS,uBAAuB,UAAsC;CACpE,KAAK,MAAM,WAAW,UAAU,YAAY,CAAC,GAC3C,KACG,mBAAmB,oBAClB,mBAAmB,qBACnB,mBAAmB,wBACrB,CAAC,QAAQ,eAAe,GAExB,OAAO;CAEX,OAAO;AACT;AAEA,SAAgB,aAAa,EAC3B,UACA,QACA,eAAe,WACf,WACA,KACA,WAAW,OACX,iBAAiB,OACjB,SAAS,QACT,QACA,UACA,iBACA,YACA,aACA,eACA,gBACA,YACA,GAAG,SACiB;CACpB,MAAM,UAAU,OAAwB,IAAI;CAC5C,MAAM,CAAC,cAAc,mBAAmB,SAAS,KAAK;CACtD,MAAM,YACJ,CAAC,YAAY,CAAC,kBAAkB,WAAW,UAAU,CAAC,CAAC;CACzD,MAAM,YAAY,QAAQ,MAAM;CAChC,MAAM,cAAc,OAA4B,IAAI;CACpD,MAAM,gBAAgB,OAA+B,IAAI;CAGzD,MAAM,wBAAwB,eAAe,KAAA,KAAa;CAE1D,OACE,oBAAC,oBAAoB,UAArB;EACE,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACA,QAAQ,iBACE;IACJ,IAAI,WAAW,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UAAU,aAAa,WAAW;EACxC,OAAO,SAAS,cAAc,SAAS;EAGvC,UAAU,YAAa,CAAC,UAAU,CAAC,SAAS;EAC5C,SAAS,SAAS,WAAW,aAAa;EAC1C,SAAS,SAAS,SAAS,SAAS,KAAA;CACrC,CAAA;AAEL"}
@@ -2,7 +2,7 @@ import { type RefObject } from 'react';
2
2
  export interface ChatComposerContextValue {
3
3
  disabled: boolean;
4
4
  canSubmit: boolean;
5
- action: 'send' | 'sending' | 'stop';
5
+ action: 'send' | 'sending' | 'stop' | 'stopping';
6
6
  submit?: () => void;
7
7
  onStop?: () => void;
8
8
  onFilesSelected?: (files: File[]) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"ChatComposerContext.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerContext.ts"],"sourcesContent":["import { createContext, useContext, type RefObject } from 'react';\n\nexport interface ChatComposerContextValue {\n disabled: boolean;\n canSubmit: boolean;\n action: 'send' | 'sending' | 'stop';\n submit?: () => void;\n onStop?: () => void;\n onFilesSelected?: (files: File[]) => void;\n /** Set by ChatComposerInput; returns false when the input cannot take focus. */\n inputFocusRef?: RefObject<(() => boolean) | null>;\n}\n\nexport const ChatComposerContext =\n createContext<ChatComposerContextValue | null>(null);\n\n// Node views render through portals and need input-level editability updates.\nexport const ChatComposerInputEditableContext = createContext(false);\n\nexport function useChatComposerContext() {\n const context = useContext(ChatComposerContext);\n if (!context) {\n throw new Error('ChatComposer parts must be inside a ChatComposer.');\n }\n return context;\n}\n\nexport function isComposerSubmitKey(event: KeyboardEvent, multiline = false) {\n return (\n event.key === 'Enter' &&\n !event.shiftKey &&\n !event.altKey &&\n !event.isComposing &&\n // Safari can end composition before dispatching the confirming Enter.\n event.keyCode !== 229 &&\n (!multiline || event.metaKey || event.ctrlKey)\n );\n}\n"],"mappings":";;AAaA,IAAa,sBACX,cAA+C,IAAI;AAGrD,IAAa,mCAAmC,cAAc,KAAK;AAEnE,SAAgB,yBAAyB;CACvC,MAAM,UAAU,WAAW,mBAAmB;CAC9C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,mDAAmD;CAErE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAAsB,YAAY,OAAO;CAC3E,OACE,MAAM,QAAQ,WACd,CAAC,MAAM,YACP,CAAC,MAAM,UACP,CAAC,MAAM,eAEP,MAAM,YAAY,QACjB,CAAC,aAAa,MAAM,WAAW,MAAM;AAE1C"}
1
+ {"version":3,"file":"ChatComposerContext.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerContext.ts"],"sourcesContent":["import { createContext, useContext, type RefObject } from 'react';\n\nexport interface ChatComposerContextValue {\n disabled: boolean;\n canSubmit: boolean;\n action: 'send' | 'sending' | 'stop' | 'stopping';\n submit?: () => void;\n onStop?: () => void;\n onFilesSelected?: (files: File[]) => void;\n /** Set by ChatComposerInput; returns false when the input cannot take focus. */\n inputFocusRef?: RefObject<(() => boolean) | null>;\n}\n\nexport const ChatComposerContext =\n createContext<ChatComposerContextValue | null>(null);\n\n// Node views render through portals and need input-level editability updates.\nexport const ChatComposerInputEditableContext = createContext(false);\n\nexport function useChatComposerContext() {\n const context = useContext(ChatComposerContext);\n if (!context) {\n throw new Error('ChatComposer parts must be inside a ChatComposer.');\n }\n return context;\n}\n\nexport function isComposerSubmitKey(event: KeyboardEvent, multiline = false) {\n return (\n event.key === 'Enter' &&\n !event.shiftKey &&\n !event.altKey &&\n !event.isComposing &&\n // Safari can end composition before dispatching the confirming Enter.\n event.keyCode !== 229 &&\n (!multiline || event.metaKey || event.ctrlKey)\n );\n}\n"],"mappings":";;AAaA,IAAa,sBACX,cAA+C,IAAI;AAGrD,IAAa,mCAAmC,cAAc,KAAK;AAEnE,SAAgB,yBAAyB;CACvC,MAAM,UAAU,WAAW,mBAAmB;CAC9C,IAAI,CAAC,SACH,MAAM,IAAI,MAAM,mDAAmD;CAErE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAAsB,YAAY,OAAO;CAC3E,OACE,MAAM,QAAQ,WACd,CAAC,MAAM,YACP,CAAC,MAAM,UACP,CAAC,MAAM,eAEP,MAAM,YAAY,QACjB,CAAC,aAAa,MAAM,WAAW,MAAM;AAE1C"}
@@ -1,7 +1,7 @@
1
1
  import { cn } from "../../utils/cn.js";
2
2
  import { ChatComposerInputEditableContext, useChatComposerContext } from "./ChatComposerContext.js";
3
3
  import { useChatComposerEditor } from "./useChatComposerEditor.js";
4
- import { useImperativeHandle } from "react";
4
+ import { useEffect, useImperativeHandle, useRef } from "react";
5
5
  import { jsx } from "react/jsx-runtime";
6
6
  import { EditorContent } from "@tiptap/react";
7
7
  var ChatComposerRichInput_module_default = { editor: "_editor_1jx45_3" };
@@ -33,9 +33,20 @@ function ChatComposerRichInput({ ref, value, onChange, placeholder = "Write a me
33
33
  useImperativeHandle(ref, () => ({ focus: () => {
34
34
  if (editable) editor?.commands.focus("end");
35
35
  } }), [editor, editable]);
36
+ const hasFocusedRef = useRef(false);
37
+ useEffect(() => {
38
+ if (!editor) return;
39
+ const markFocused = () => {
40
+ hasFocusedRef.current = true;
41
+ };
42
+ editor.on("focus", markFocused);
43
+ return () => {
44
+ editor.off("focus", markFocused);
45
+ };
46
+ }, [editor]);
36
47
  useImperativeHandle(composer.inputFocusRef, () => () => {
37
48
  if (!editable || !editor) return false;
38
- editor.commands.focus("end");
49
+ editor.commands.focus(hasFocusedRef.current ? null : "end");
39
50
  return true;
40
51
  }, [editor, editable]);
41
52
  return /* @__PURE__ */ jsx("div", {
@@ -1 +1 @@
1
- {"version":3,"file":"ChatComposerRichInput.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerRichInput.module.css","../../../src/components/ChatComposer/ChatComposerRichInput.tsx"],"sourcesContent":["@reference \"../../styles/tailwind.css\";\n\n.editor :global(p.is-editor-empty:first-child)::before {\n @apply pointer-events-none float-left h-0 text-placeholder;\n content: attr(data-placeholder);\n}\n\n.editor p {\n @apply m-0;\n}\n\n.editor > * + * {\n @apply mt-space-2;\n}\n\n.editor h1,\n.editor h2,\n.editor h3,\n.editor h4,\n.editor h5,\n.editor h6 {\n @apply text-base font-semibold;\n}\n\n.editor ul {\n @apply list-outside list-disc pl-space-5;\n}\n\n.editor ol {\n @apply list-outside list-decimal pl-space-5;\n}\n\n.editor a {\n @apply text-link underline underline-offset-2;\n}\n\n.editor blockquote {\n @apply border-l-2 border-default pl-space-3 text-secondary;\n}\n\n.editor :not(pre) > code {\n @apply rounded-sm bg-surface-level-2 px-space-1 font-mono;\n}\n\n.editor pre code {\n @apply bg-transparent p-0;\n}\n\n.editor hr {\n @apply border-default;\n}\n","import { useImperativeHandle } from 'react';\n\nimport { EditorContent } from '@tiptap/react';\n\nimport { cn } from '../../utils/cn';\nimport {\n ChatComposerInputEditableContext,\n useChatComposerContext,\n} from './ChatComposerContext';\nimport type { ChatComposerInputProps } from './ChatComposerInput';\nimport { useChatComposerEditor } from './useChatComposerEditor';\n\nimport styles from './ChatComposerRichInput.module.css';\n\ninterface ChatComposerRichInputProps extends ChatComposerInputProps {\n minHeight: number;\n maxHeight: number;\n}\n\nexport function ChatComposerRichInput({\n ref,\n value,\n onChange,\n placeholder = 'Write a message…',\n disabled = false,\n readOnly = false,\n autoFocus = false,\n minHeight,\n maxHeight,\n className,\n 'aria-label': ariaLabel = 'Message',\n 'aria-describedby': ariaDescribedBy,\n}: ChatComposerRichInputProps) {\n 'use no memo';\n\n const composer = useChatComposerContext();\n const isDisabled = composer.disabled || disabled;\n const editable = !isDisabled && !readOnly;\n const { editor } = useChatComposerEditor({\n value,\n onChange,\n onSubmit: composer.submit,\n placeholder,\n editable,\n autofocus: autoFocus,\n editorClassName: cn(\n styles.editor,\n 'min-w-0 break-words px-space-1 text-sm leading-relaxed text-primary outline-hidden',\n // Read-only text is still the user's message, such as a prefilled draft\n // being typed in, so only disabled input looks unavailable.\n isDisabled && 'text-disabled'\n ),\n editorAttributes: {\n role: 'textbox',\n style: `min-height: ${minHeight}px`,\n 'aria-label': ariaLabel,\n 'aria-multiline': 'true',\n 'aria-disabled': String(isDisabled),\n 'aria-readonly': String(readOnly),\n ...(ariaDescribedBy ? { 'aria-describedby': ariaDescribedBy } : {}),\n },\n });\n\n useImperativeHandle(\n ref,\n () => ({\n focus: () => {\n if (editable) editor?.commands.focus('end');\n },\n }),\n [editor, editable]\n );\n\n useImperativeHandle(\n composer.inputFocusRef,\n () => () => {\n if (!editable || !editor) return false;\n editor.commands.focus('end');\n return true;\n },\n [editor, editable]\n );\n\n return (\n <div\n className={cn('min-w-0 overflow-y-auto overscroll-contain', className)}\n style={{ maxHeight }}\n >\n <ChatComposerInputEditableContext.Provider value={editable}>\n <EditorContent editor={editor} />\n </ChatComposerInputEditableContext.Provider>\n </div>\n );\n}\n"],"mappings":";;;;;;;;;ACmBA,SAAgB,sBAAsB,EACpC,KACA,OACA,UACA,cAAc,oBACd,WAAW,OACX,WAAW,OACX,YAAY,OACZ,WACA,WACA,WACA,cAAc,YAAY,WAC1B,oBAAoB,mBACS;CAC7B;CAEA,MAAM,WAAW,uBAAuB;CACxC,MAAM,aAAa,SAAS,YAAY;CACxC,MAAM,WAAW,CAAC,cAAc,CAAC;CACjC,MAAM,EAAE,WAAW,sBAAsB;EACvC;EACA;EACA,UAAU,SAAS;EACnB;EACA;EACA,WAAW;EACX,iBAAiB,GACf,qCAAO,QACP,sFAGA,cAAc,eAChB;EACA,kBAAkB;GAChB,MAAM;GACN,OAAO,eAAe,UAAU;GAChC,cAAc;GACd,kBAAkB;GAClB,iBAAiB,OAAO,UAAU;GAClC,iBAAiB,OAAO,QAAQ;GAChC,GAAI,kBAAkB,EAAE,oBAAoB,gBAAgB,IAAI,CAAC;EACnE;CACF,CAAC;CAED,oBACE,YACO,EACL,aAAa;EACX,IAAI,UAAU,QAAQ,SAAS,MAAM,KAAK;CAC5C,EACF,IACA,CAAC,QAAQ,QAAQ,CACnB;CAEA,oBACE,SAAS,2BACG;EACV,IAAI,CAAC,YAAY,CAAC,QAAQ,OAAO;EACjC,OAAO,SAAS,MAAM,KAAK;EAC3B,OAAO;CACT,GACA,CAAC,QAAQ,QAAQ,CACnB;CAEA,OACE,oBAAC,OAAD;EACE,WAAW,GAAG,8CAA8C,SAAS;EACrE,OAAO,EAAE,UAAU;EAEnB,UAAA,oBAAC,iCAAiC,UAAlC;GAA2C,OAAO;GAChD,UAAA,oBAAC,eAAD,EAAuB,OAAS,CAAA;EACS,CAAA;CACxC,CAAA;AAET"}
1
+ {"version":3,"file":"ChatComposerRichInput.js","names":[],"sources":["../../../src/components/ChatComposer/ChatComposerRichInput.module.css","../../../src/components/ChatComposer/ChatComposerRichInput.tsx"],"sourcesContent":["@reference \"../../styles/tailwind.css\";\n\n.editor :global(p.is-editor-empty:first-child)::before {\n @apply pointer-events-none float-left h-0 text-placeholder;\n content: attr(data-placeholder);\n}\n\n.editor p {\n @apply m-0;\n}\n\n.editor > * + * {\n @apply mt-space-2;\n}\n\n.editor h1,\n.editor h2,\n.editor h3,\n.editor h4,\n.editor h5,\n.editor h6 {\n @apply text-base font-semibold;\n}\n\n.editor ul {\n @apply list-outside list-disc pl-space-5;\n}\n\n.editor ol {\n @apply list-outside list-decimal pl-space-5;\n}\n\n.editor a {\n @apply text-link underline underline-offset-2;\n}\n\n.editor blockquote {\n @apply border-l-2 border-default pl-space-3 text-secondary;\n}\n\n.editor :not(pre) > code {\n @apply rounded-sm bg-surface-level-2 px-space-1 font-mono;\n}\n\n.editor pre code {\n @apply bg-transparent p-0;\n}\n\n.editor hr {\n @apply border-default;\n}\n","import { useEffect, useImperativeHandle, useRef } from 'react';\n\nimport { EditorContent } from '@tiptap/react';\n\nimport { cn } from '../../utils/cn';\nimport {\n ChatComposerInputEditableContext,\n useChatComposerContext,\n} from './ChatComposerContext';\nimport type { ChatComposerInputProps } from './ChatComposerInput';\nimport { useChatComposerEditor } from './useChatComposerEditor';\n\nimport styles from './ChatComposerRichInput.module.css';\n\ninterface ChatComposerRichInputProps extends ChatComposerInputProps {\n minHeight: number;\n maxHeight: number;\n}\n\nexport function ChatComposerRichInput({\n ref,\n value,\n onChange,\n placeholder = 'Write a message…',\n disabled = false,\n readOnly = false,\n autoFocus = false,\n minHeight,\n maxHeight,\n className,\n 'aria-label': ariaLabel = 'Message',\n 'aria-describedby': ariaDescribedBy,\n}: ChatComposerRichInputProps) {\n 'use no memo';\n\n const composer = useChatComposerContext();\n const isDisabled = composer.disabled || disabled;\n const editable = !isDisabled && !readOnly;\n const { editor } = useChatComposerEditor({\n value,\n onChange,\n onSubmit: composer.submit,\n placeholder,\n editable,\n autofocus: autoFocus,\n editorClassName: cn(\n styles.editor,\n 'min-w-0 break-words px-space-1 text-sm leading-relaxed text-primary outline-hidden',\n // Read-only text is still the user's message, such as a prefilled draft\n // being typed in, so only disabled input looks unavailable.\n isDisabled && 'text-disabled'\n ),\n editorAttributes: {\n role: 'textbox',\n style: `min-height: ${minHeight}px`,\n 'aria-label': ariaLabel,\n 'aria-multiline': 'true',\n 'aria-disabled': String(isDisabled),\n 'aria-readonly': String(readOnly),\n ...(ariaDescribedBy ? { 'aria-describedby': ariaDescribedBy } : {}),\n },\n });\n\n useImperativeHandle(\n ref,\n () => ({\n focus: () => {\n if (editable) editor?.commands.focus('end');\n },\n }),\n [editor, editable]\n );\n\n // Until the user first places the caret, ProseMirror's selection sits at the\n // start of the draft, so composer-level focus starts at the end instead.\n const hasFocusedRef = useRef(false);\n useEffect(() => {\n if (!editor) return;\n const markFocused = () => {\n hasFocusedRef.current = true;\n };\n editor.on('focus', markFocused);\n return () => {\n editor.off('focus', markFocused);\n };\n }, [editor]);\n\n useImperativeHandle(\n composer.inputFocusRef,\n () => () => {\n if (!editable || !editor) return false;\n editor.commands.focus(hasFocusedRef.current ? null : 'end');\n return true;\n },\n [editor, editable]\n );\n\n return (\n <div\n className={cn('min-w-0 overflow-y-auto overscroll-contain', className)}\n style={{ maxHeight }}\n >\n <ChatComposerInputEditableContext.Provider value={editable}>\n <EditorContent editor={editor} />\n </ChatComposerInputEditableContext.Provider>\n </div>\n );\n}\n"],"mappings":";;;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,OAAS,CAAA;EACS,CAAA;CACxC,CAAA;AAET"}
@@ -53,9 +53,10 @@ export interface ChatMessageActionsProps extends ComponentPropsWithRef<'div'> {
53
53
  readOnly?: boolean;
54
54
  }
55
55
  /**
56
- * Copy, edit, and retry buttons, plus any host actions in `children`. Edit
57
- * and retry are hidden while the message is pending or read-only; copy stays
58
- * available. Renders nothing when no actions remain.
56
+ * Copy, edit, retry, and cancel buttons, plus any host actions in `children`.
57
+ * Edit and retry are hidden while the message is pending or read-only; cancel
58
+ * appears only on a queued message; copy stays available. Renders nothing
59
+ * when no actions remain.
59
60
  */
60
61
  export declare function ChatMessageActions({ actions, status, readOnly, children, className, ...props }: ChatMessageActionsProps): import("react").JSX.Element | null;
61
62
  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";
@@ -131,7 +132,7 @@ function ChatMessageBody({ blocks, animateParagraphs = false, className, ...prop
131
132
  const alignment = useContext(ChatMessageAlignmentContext);
132
133
  if (blocks.length === 0) return null;
133
134
  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),
135
+ 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
136
  ...props,
136
137
  children: blocks.map((block) => {
137
138
  const content = block.type === "text" ? /* @__PURE__ */ jsx(Text, {
@@ -163,21 +164,31 @@ var actionDefinitions = [
163
164
  name: "retry",
164
165
  label: "Retry message",
165
166
  icon: ArrowClockwiseIcon
167
+ },
168
+ {
169
+ name: "cancel",
170
+ label: "Cancel queued message",
171
+ icon: XIcon
166
172
  }
167
173
  ];
168
174
  function canChangeMessage(status, readOnly) {
169
175
  return !readOnly && status !== "queued" && status !== "submitting" && status !== "streaming";
170
176
  }
177
+ function isActionAvailable(name, status, readOnly) {
178
+ if (name === "copy") return true;
179
+ if (name === "cancel") return !readOnly && status === "queued";
180
+ return canChangeMessage(status, readOnly);
181
+ }
171
182
  /**
172
- * Copy, edit, and retry buttons, plus any host actions in `children`. Edit
173
- * and retry are hidden while the message is pending or read-only; copy stays
174
- * available. Renders nothing when no actions remain.
183
+ * Copy, edit, retry, and cancel buttons, plus any host actions in `children`.
184
+ * Edit and retry are hidden while the message is pending or read-only; cancel
185
+ * appears only on a queued message; copy stays available. Renders nothing
186
+ * when no actions remain.
175
187
  */
176
188
  function ChatMessageActions({ actions, status = "completed", readOnly = false, children, className, ...props }) {
177
- const canChange = canChangeMessage(status, readOnly);
178
189
  const visibleActions = actionDefinitions.flatMap((definition) => {
179
190
  const action = actions?.[definition.name];
180
- return action && (definition.name === "copy" || canChange) ? [{
191
+ return action && isActionAvailable(definition.name, status, readOnly) ? [{
181
192
  ...definition,
182
193
  action
183
194
  }] : [];
@@ -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,aA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AAgB,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.\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;C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A;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