@langchain/macaw-components 1.7.4 → 1.7.6

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.
@@ -28,7 +28,7 @@ var Avatar = forwardRef(({ size = "md", shape = "square", badge, tooltip, classN
28
28
  const rounding = shape === "circle" ? "rounded-full" : "rounded-sm";
29
29
  const inner = /* @__PURE__ */ jsxs("div", {
30
30
  ref,
31
- className: cn("relative inline-flex shrink-0 cursor-default items-center justify-center text-center font-medium uppercase text-white/90 transition-all", rounding, BOX_SIZE[size], TEXT_SIZE[size], active && "bg-brand", className),
31
+ className: cn("relative inline-flex shrink-0 items-center justify-center text-center font-medium uppercase text-white/90 transition-all", rounding, BOX_SIZE[size], TEXT_SIZE[size], active && "bg-brand", className),
32
32
  style: active ? void 0 : { backgroundImage: `linear-gradient(to bottom right, ${startColor}, #aaaaaa)` },
33
33
  children: [imageUrl ? /* @__PURE__ */ jsx("div", {
34
34
  className: cn("absolute inset-0 size-full bg-cover bg-center", rounding),
@@ -1 +1 @@
1
- {"version":3,"file":"Avatar.js","names":[],"sources":["../../../src/components/Avatar/Avatar.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { forwardRef } from 'react';\n\nimport { cn } from '../../utils/cn';\nimport {\n VISUAL_ELEMENT_SIZES,\n type VisualElementSize,\n} from '../../utils/componentSizes';\nimport { getColorByString } from '../../utils/get-color-by-string';\nimport { sanitizeImageSrc } from '../../utils/sanitizeImageSrc';\nimport { Tooltip } from '../Tooltip';\n\ntype AvatarSize = VisualElementSize | 'lg' | 'xl';\ntype AvatarShape = 'circle' | 'square';\n\ninterface AvatarProps {\n /** Outer box size: xxs=12px, xs=16px, sm=20px, md=24px, lg=36px, xl=48px. */\n size?: AvatarSize;\n shape?: AvatarShape;\n /** Show a small notification dot in the top-right corner. */\n badge?: boolean;\n /** Wrap the avatar in a tooltip with this title. */\n tooltip?: string;\n /** Extra classes on the avatar box. Can override size/text/color via `twMerge`. */\n className?: string;\n /** Text used for the initial and, unless `color` is set, the color hash. */\n label: string;\n /** Renders an image instead of the initial when present. */\n imageUrl?: string;\n /** Overrides the color-from-string hash with an explicit gradient start color. */\n color?: string;\n /** Rendered instead of the initial when `label` is empty. */\n fallbackIcon?: ReactNode;\n /** Highlighted brand-fill state (e.g. the current user's own entry). */\n active?: boolean;\n}\n\n// The shared tiers use the visual-element scale. Identity-specific lg/xl tiers\n// remain larger so existing Avatar presentations retain their geometry.\nconst BOX_SIZE: Record<AvatarSize, string> = {\n xxs: VISUAL_ELEMENT_SIZES.xxs.className,\n xs: VISUAL_ELEMENT_SIZES.xs.className,\n sm: VISUAL_ELEMENT_SIZES.sm.className,\n md: VISUAL_ELEMENT_SIZES.md.className,\n lg: 'size-9',\n xl: 'size-12',\n};\n\nconst TEXT_SIZE: Record<AvatarSize, string> = {\n xxs: 'text-[0.625rem] leading-none',\n xs: 'text-xxs',\n sm: 'text-xs',\n md: 'text-sm',\n lg: 'text-lg',\n xl: 'text-xl',\n};\n\n// Keeps the URL inside a quoted CSS `url(\"\")` string.\nconst escapeCssString = (value: string) =>\n value.replace(/[\"\\\\\\n\\r\\f]/g, (c) => `\\\\${c.charCodeAt(0).toString(16)} `);\n\nconst Avatar = forwardRef<HTMLDivElement, AvatarProps>(\n (\n {\n size = 'md',\n shape = 'square',\n badge,\n tooltip,\n className,\n label,\n imageUrl,\n color,\n fallbackIcon,\n active,\n },\n ref\n ) => {\n const startColor = color ?? getColorByString(label);\n const rounding = shape === 'circle' ? 'rounded-full' : 'rounded-sm';\n\n const inner = (\n // The box is intentionally not `overflow-hidden` so the badge dot can\n // overflow the top-right corner. The image child clips itself instead.\n <div\n ref={ref}\n className={cn(\n 'relative inline-flex shrink-0 cursor-default items-center justify-center text-center font-medium uppercase text-white/90 transition-all',\n rounding,\n BOX_SIZE[size],\n TEXT_SIZE[size],\n active && 'bg-brand',\n className\n )}\n style={\n active\n ? undefined\n : {\n backgroundImage: `linear-gradient(to bottom right, ${startColor}, #aaaaaa)`,\n }\n }\n >\n {imageUrl ? (\n <div\n className={cn(\n 'absolute inset-0 size-full bg-cover bg-center',\n rounding\n )}\n style={{\n backgroundImage: `url(\"${escapeCssString(sanitizeImageSrc(imageUrl))}\")`,\n }}\n />\n ) : label ? (\n <span>{label.charAt(0)}</span>\n ) : (\n (fallbackIcon ?? null)\n )}\n\n {badge && (\n <div\n className={cn(\n 'absolute rounded-full border-current bg-error-strong outline-transparent',\n size === 'xxs'\n ? '-right-0.5 -top-0.5 size-1.5 border'\n : '-right-1 -top-1 size-3 border-2'\n )}\n />\n )}\n </div>\n );\n\n if (tooltip) {\n return <Tooltip title={tooltip}>{inner}</Tooltip>;\n }\n\n return inner;\n }\n);\n\nAvatar.displayName = 'Avatar';\n\nexport { Avatar };\nexport type { AvatarProps, AvatarSize };\n"],"mappings":";;;;;;;;AAuCA,IAAM,WAAuC;CAC3C,KAAK,qBAAqB,IAAI;CAC9B,IAAI,qBAAqB,GAAG;CAC5B,IAAI,qBAAqB,GAAG;CAC5B,IAAI,qBAAqB,GAAG;CAC5B,IAAI;CACJ,IAAI;AACN;AAEA,IAAM,YAAwC;CAC5C,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAGA,IAAM,mBAAmB,UACvB,MAAM,QAAQ,iBAAiB,MAAM,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,EAAE,EAAE;AAE3E,IAAM,SAAS,YAEX,EACE,OAAO,MACP,QAAQ,UACR,OACA,SACA,WACA,OACA,UACA,OACA,cACA,UAEF,QACG;CACH,MAAM,aAAa,SAAS,iBAAiB,KAAK;CAClD,MAAM,WAAW,UAAU,WAAW,iBAAiB;CAEvD,MAAM,QAGJ,qBAAC,OAAD;EACO;EACL,WAAW,GACT,2IACA,UACA,SAAS,OACT,UAAU,OACV,UAAU,YACV,SACF;EACA,OACE,SACI,KAAA,IACA,EACE,iBAAiB,oCAAoC,WAAW,YAClE;EAfR,UAAA,CAkBG,WACC,oBAAC,OAAD;GACE,WAAW,GACT,iDACA,QACF;GACA,OAAO,EACL,iBAAiB,QAAQ,gBAAgB,iBAAiB,QAAQ,CAAC,EAAE,IACvE;EACD,CAAA,IACC,QACF,oBAAC,QAAD,EAAA,UAAO,MAAM,OAAO,CAAC,EAAQ,CAAA,IAE5B,gBAAgB,MAGlB,SACC,oBAAC,OAAD,EACE,WAAW,GACT,4EACA,SAAS,QACL,wCACA,iCACN,EACD,CAAA,CAEA;;CAGP,IAAI,SACF,OAAO,oBAAC,SAAD;EAAS,OAAO;EAAU,UAAA;CAAe,CAAA;CAGlD,OAAO;AACT,CACF;AAEA,OAAO,cAAc"}
1
+ {"version":3,"file":"Avatar.js","names":[],"sources":["../../../src/components/Avatar/Avatar.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\nimport { forwardRef } from 'react';\n\nimport { cn } from '../../utils/cn';\nimport {\n VISUAL_ELEMENT_SIZES,\n type VisualElementSize,\n} from '../../utils/componentSizes';\nimport { getColorByString } from '../../utils/get-color-by-string';\nimport { sanitizeImageSrc } from '../../utils/sanitizeImageSrc';\nimport { Tooltip } from '../Tooltip';\n\ntype AvatarSize = VisualElementSize | 'lg' | 'xl';\ntype AvatarShape = 'circle' | 'square';\n\ninterface AvatarProps {\n /** Outer box size: xxs=12px, xs=16px, sm=20px, md=24px, lg=36px, xl=48px. */\n size?: AvatarSize;\n shape?: AvatarShape;\n /** Show a small notification dot in the top-right corner. */\n badge?: boolean;\n /** Wrap the avatar in a tooltip with this title. */\n tooltip?: string;\n /** Extra classes on the avatar box. Can override size/text/color via `twMerge`. */\n className?: string;\n /** Text used for the initial and, unless `color` is set, the color hash. */\n label: string;\n /** Renders an image instead of the initial when present. */\n imageUrl?: string;\n /** Overrides the color-from-string hash with an explicit gradient start color. */\n color?: string;\n /** Rendered instead of the initial when `label` is empty. */\n fallbackIcon?: ReactNode;\n /** Highlighted brand-fill state (e.g. the current user's own entry). */\n active?: boolean;\n}\n\n// The shared tiers use the visual-element scale. Identity-specific lg/xl tiers\n// remain larger so existing Avatar presentations retain their geometry.\nconst BOX_SIZE: Record<AvatarSize, string> = {\n xxs: VISUAL_ELEMENT_SIZES.xxs.className,\n xs: VISUAL_ELEMENT_SIZES.xs.className,\n sm: VISUAL_ELEMENT_SIZES.sm.className,\n md: VISUAL_ELEMENT_SIZES.md.className,\n lg: 'size-9',\n xl: 'size-12',\n};\n\nconst TEXT_SIZE: Record<AvatarSize, string> = {\n xxs: 'text-[0.625rem] leading-none',\n xs: 'text-xxs',\n sm: 'text-xs',\n md: 'text-sm',\n lg: 'text-lg',\n xl: 'text-xl',\n};\n\n// Keeps the URL inside a quoted CSS `url(\"\")` string.\nconst escapeCssString = (value: string) =>\n value.replace(/[\"\\\\\\n\\r\\f]/g, (c) => `\\\\${c.charCodeAt(0).toString(16)} `);\n\nconst Avatar = forwardRef<HTMLDivElement, AvatarProps>(\n (\n {\n size = 'md',\n shape = 'square',\n badge,\n tooltip,\n className,\n label,\n imageUrl,\n color,\n fallbackIcon,\n active,\n },\n ref\n ) => {\n const startColor = color ?? getColorByString(label);\n const rounding = shape === 'circle' ? 'rounded-full' : 'rounded-sm';\n\n const inner = (\n // The box is intentionally not `overflow-hidden` so the badge dot can\n // overflow the top-right corner. The image child clips itself instead.\n <div\n ref={ref}\n className={cn(\n 'relative inline-flex shrink-0 items-center justify-center text-center font-medium uppercase text-white/90 transition-all',\n rounding,\n BOX_SIZE[size],\n TEXT_SIZE[size],\n active && 'bg-brand',\n className\n )}\n style={\n active\n ? undefined\n : {\n backgroundImage: `linear-gradient(to bottom right, ${startColor}, #aaaaaa)`,\n }\n }\n >\n {imageUrl ? (\n <div\n className={cn(\n 'absolute inset-0 size-full bg-cover bg-center',\n rounding\n )}\n style={{\n backgroundImage: `url(\"${escapeCssString(sanitizeImageSrc(imageUrl))}\")`,\n }}\n />\n ) : label ? (\n <span>{label.charAt(0)}</span>\n ) : (\n (fallbackIcon ?? null)\n )}\n\n {badge && (\n <div\n className={cn(\n 'absolute rounded-full border-current bg-error-strong outline-transparent',\n size === 'xxs'\n ? '-right-0.5 -top-0.5 size-1.5 border'\n : '-right-1 -top-1 size-3 border-2'\n )}\n />\n )}\n </div>\n );\n\n if (tooltip) {\n return <Tooltip title={tooltip}>{inner}</Tooltip>;\n }\n\n return inner;\n }\n);\n\nAvatar.displayName = 'Avatar';\n\nexport { Avatar };\nexport type { AvatarProps, AvatarSize };\n"],"mappings":";;;;;;;;AAuCA,IAAM,WAAuC;CAC3C,KAAK,qBAAqB,IAAI;CAC9B,IAAI,qBAAqB,GAAG;CAC5B,IAAI,qBAAqB,GAAG;CAC5B,IAAI,qBAAqB,GAAG;CAC5B,IAAI;CACJ,IAAI;AACN;AAEA,IAAM,YAAwC;CAC5C,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAGA,IAAM,mBAAmB,UACvB,MAAM,QAAQ,iBAAiB,MAAM,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,SAAS,EAAE,EAAE,EAAE;AAE3E,IAAM,SAAS,YAEX,EACE,OAAO,MACP,QAAQ,UACR,OACA,SACA,WACA,OACA,UACA,OACA,cACA,UAEF,QACG;CACH,MAAM,aAAa,SAAS,iBAAiB,KAAK;CAClD,MAAM,WAAW,UAAU,WAAW,iBAAiB;CAEvD,MAAM,QAGJ,qBAAC,OAAD;EACO;EACL,WAAW,GACT,4HACA,UACA,SAAS,OACT,UAAU,OACV,UAAU,YACV,SACF;EACA,OACE,SACI,KAAA,IACA,EACE,iBAAiB,oCAAoC,WAAW,YAClE;EAfR,UAAA,CAkBG,WACC,oBAAC,OAAD;GACE,WAAW,GACT,iDACA,QACF;GACA,OAAO,EACL,iBAAiB,QAAQ,gBAAgB,iBAAiB,QAAQ,CAAC,EAAE,IACvE;EACD,CAAA,IACC,QACF,oBAAC,QAAD,EAAA,UAAO,MAAM,OAAO,CAAC,EAAQ,CAAA,IAE5B,gBAAgB,MAGlB,SACC,oBAAC,OAAD,EACE,WAAW,GACT,4EACA,SAAS,QACL,wCACA,iCACN,EACD,CAAA,CAEA;;CAGP,IAAI,SACF,OAAO,oBAAC,SAAD;EAAS,OAAO;EAAU,UAAA;CAAe,CAAA;CAGlD,OAAO;AACT,CACF;AAEA,OAAO,cAAc"}
@@ -87,12 +87,12 @@ function ChatComposer({ children, drawer, drawerIntent = "neutral", className, r
87
87
  },
88
88
  children: [hasDrawer && /* @__PURE__ */ jsx("fieldset", {
89
89
  disabled,
90
- className: cn("mx-space-3 -mb-space-3 max-h-[50dvh] min-w-0 overflow-y-auto overscroll-contain rounded-t-xl 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"),
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
91
  children: drawer
92
92
  }), /* @__PURE__ */ jsx("fieldset", {
93
93
  ref: fieldsetRef,
94
94
  disabled,
95
- className: cn("relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-xl 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)]"),
95
+ 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
96
  children
97
97
  })]
98
98
  })
@@ -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 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-xl 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 disabled={disabled}\n className={cn(\n 'relative m-0 flex w-full min-w-0 flex-col gap-space-2 rounded-xl 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 disabled={\n composer.disabled || disabled || (!isStop && !composer.canSubmit)\n }\n loading={composer.action === 'sending'}\n onClick={isStop ? composer.onStop : undefined}\n />\n );\n}\n"],"mappings":";;;;;;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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;EACvC,UACE,SAAS,YAAY,YAAa,CAAC,UAAU,CAAC,SAAS;EAEzD,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\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 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 disabled={disabled}\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 disabled={\n composer.disabled || disabled || (!isStop && !composer.canSubmit)\n }\n loading={composer.action === 'sending'}\n onClick={isStop ? composer.onStop : undefined}\n />\n );\n}\n"],"mappings":";;;;;;;;;AAkBA,IAAM,wBAAkE;CACtE,SAAS;CACT,MAAM;CACN,SAAS;CACT,OAAO;AACT;AAqBA,SAAS,0BAA0B,QAAqB;CACtD,OACE,kBAAkB,WAClB,OAAO,QACL,2EACF,MAAM;AAEV;AAIA,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,kB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AAI;EACJ,MAAM,SAAS,WAAW;EAC1B,MAAM,SAAS,WAAW;EAC1B,OAAO,SAAS,cAAc,SAAS;EACvC,UACE,SAAS,YAAY,YAAa,CAAC,UAAU,CAAC,SAAS;EAEzD,SAAS,SAAS,WAAW;EAC7B,SAAS,SAAS,SAAS,SAAS,KAAA;CACrC,CAAA;AAEL"}
@@ -5,13 +5,18 @@ import { IconButton } from "../IconButton/IconButton.js";
5
5
  import { Icon } from "../Icon/Icon.js";
6
6
  import { Divider } from "../Divider/Divider.js";
7
7
  import { ThinkingState } from "../ThinkingState/ThinkingState.js";
8
- import { Fragment, useState } from "react";
8
+ import { Fragment, createContext, useContext, useState } from "react";
9
9
  import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
10
10
  import { WarningCircleIcon } from "@phosphor-icons/react/dist/ssr/WarningCircle";
11
11
  import { CopySimpleIcon } from "@phosphor-icons/react/dist/ssr/CopySimple";
12
12
  import { PencilSimpleIcon } from "@phosphor-icons/react/dist/ssr/PencilSimple";
13
13
  import { ArrowClockwiseIcon } from "@phosphor-icons/react/dist/ssr/ArrowClockwise";
14
14
  //#region packages/components/src/components/ChatMessage/ChatMessage.tsx
15
+ /**
16
+ * The message's alignment, so a host-supplied `ChatMessageBody` lines up its
17
+ * blocks the same way the default body does.
18
+ */
19
+ var ChatMessageAlignmentContext = createContext("start");
15
20
  var roleLabels = {
16
21
  user: "User",
17
22
  assistant: "Assistant",
@@ -53,15 +58,17 @@ function ChatMessage({ message, footer, avatar, name, align, isLatest = false, a
53
58
  ...props,
54
59
  children: /* @__PURE__ */ jsxs("div", {
55
60
  className: cn("flex min-w-0 max-w-full flex-col gap-space-2", alignment === "end" ? "w-fit max-w-[85%] items-end" : "w-full", contentClassName),
56
- children: [children ?? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(ChatMessageHeader, {
57
- avatar,
58
- name,
59
- status: message.status
60
- }), /* @__PURE__ */ jsx(ChatMessageBody, {
61
- blocks: message.content,
62
- animateParagraphs: animateParagraphs && !isHistory,
63
- className: alignment === "end" ? "items-end" : void 0
64
- })] }), footer != null && /* @__PURE__ */ jsx("div", {
61
+ children: [/* @__PURE__ */ jsx(ChatMessageAlignmentContext.Provider, {
62
+ value: alignment,
63
+ children: children ?? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(ChatMessageHeader, {
64
+ avatar,
65
+ name,
66
+ status: message.status
67
+ }), /* @__PURE__ */ jsx(ChatMessageBody, {
68
+ blocks: message.content,
69
+ animateParagraphs: animateParagraphs && !isHistory
70
+ })] })
71
+ }), footer != null && /* @__PURE__ */ jsx("div", {
65
72
  inert: isStreaming,
66
73
  className: cn("flex min-w-0 max-w-full flex-wrap items-center gap-space-2 [overflow-wrap:anywhere]", isStreaming && "invisible", !isLatest && "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"),
67
74
  children: footer
@@ -121,9 +128,10 @@ function ChatMessageHeader({ avatar, name, status = "completed", children, class
121
128
  }
122
129
  /** Content blocks in order. Text blocks render as escaped plain text. */
123
130
  function ChatMessageBody({ blocks, animateParagraphs = false, className, ...props }) {
131
+ const alignment = useContext(ChatMessageAlignmentContext);
124
132
  if (blocks.length === 0) return null;
125
133
  return /* @__PURE__ */ jsx("div", {
126
- className: cn("flex w-full min-w-0 max-w-full flex-col gap-space-3 [overflow-wrap:anywhere]", "[&_img]:max-w-full [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto", className),
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),
127
135
  ...props,
128
136
  children: blocks.map((block) => {
129
137
  const content = block.type === "text" ? /* @__PURE__ */ jsx(Text, {
@@ -134,7 +142,7 @@ function ChatMessageBody({ blocks, animateParagraphs = false, className, ...prop
134
142
  children: block.text
135
143
  }) : block.content;
136
144
  return block.appearance === "bubble" ? /* @__PURE__ */ jsx("div", {
137
- className: "w-fit min-w-0 max-w-full rounded-xl bg-surface-level-2 px-space-3 py-space-2",
145
+ className: "w-fit min-w-0 max-w-full rounded-lg bg-surface-level-2 px-space-3 py-space-2",
138
146
  children: content
139
147
  }, block.id) : /* @__PURE__ */ jsx(Fragment, { children: content }, block.id);
140
148
  })
@@ -1 +1 @@
1
- {"version":3,"file":"ChatMessage.js","names":[],"sources":["../../../src/components/ChatMessage/ChatMessage.tsx"],"sourcesContent":["import {\n Fragment,\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\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 {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 className={alignment === 'end' ? 'items-end' : undefined}\n />\n </>\n )}\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 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 // 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-xl 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":";;;;;;;;;;;;;;AA4BA,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,UACtD,gBACF;GALF,UAAA,CAOG,YACC,qBAAA,YAAA,EAAA,UAAA,CACE,oBAAC,mBAAD;IACU;IACF;I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,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';\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;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UAAmB;CACtE,OACE,CAAC,YACD,WAAW,YACX,WAAW,gBACX,WAAW;AAEf;;;;;;AAaA,SAAgB,mBAAmB,EACjC,SACA,SAAS,aACT,WAAW,OACX,UACA,WACA,GAAG,SACuB;CAC1B,MAAM,YAAY,iBAAiB,QAAQ,QAAQ;CACnD,MAAM,iBAAiB,kBAAkB,SAAS,eAAe;EAC/D,MAAM,SAAS,UAAU,WAAW;EACpC,OAAO,WAAW,WAAW,SAAS,UAAU,aAC5C,CAAC;GAAE,GAAG;GAAY;EAAO,CAAC,IAC1B,CAAC;CACP,CAAC;CACD,IAAI,eAAe,WAAW,KAAK,YAAY,MAAM,OAAO;CAE5D,OACE,qBAAC,OAAD;EACE,MAAK;EACL,cAAW;EACX,WAAW,GACT,8DACA,SACF;EACA,GAAI;EAPN,UAAA,CASG,eAAe,KAAK,EAAE,MAAM,OAAO,MAAM,aACxC,oBAAC,YAAD;GAEQ;GACN,YAAW;GACX,OAAO,OAAO,SAAS;GACvB,OAAM;GACN,SAAQ;GACR,MAAK;GACL,SAAS,OAAO;EACjB,GARM,IAQN,CACF,GACA,QACE;;AAET;AASA,SAAgB,gBAAgB,EAC9B,OACA,WACA,GAAG,SACoB;CACvB,OACE,qBAAC,OAAD;EACE,MAAK;EACL,cAAY;EACZ,oBAAiB;EACjB,WAAW,GACT,2DACA,SACF;EACA,GAAI;EARN,UAAA;GAUE,oBAAC,SAAD,EAAS,WAAU,uBAAwB,CAAA;GAC3C,oBAAC,MAAD;IACE,SAAQ;IACR,OAAM;IACN,WAAU;IAET,UAAA;GACG,CAAA;GACN,oBAAC,SAAD,EAAS,WAAU,uBAAwB,CAAA;EACxC;;AAET"}
@@ -54,7 +54,7 @@ function ChatState({ status, variant = "default", label, showElapsed = variant =
54
54
  const statusContent = /* @__PURE__ */ jsxs("span", {
55
55
  className: cn("inline-flex min-w-0 items-center", status === "streaming" ? "gap-space-2" : "gap-space-1"),
56
56
  children: [status === "streaming" ? /* @__PURE__ */ jsx(LoadingIndicator, {
57
- size: "xs",
57
+ size: "sm",
58
58
  tone: "neutral"
59
59
  }) : StatusIcon ? /* @__PURE__ */ jsx(StatusIcon, {
60
60
  size: 12,
@@ -1 +1 @@
1
- {"version":3,"file":"ChatState.js","names":[],"sources":["../../../src/components/ChatState/ChatState.tsx"],"sourcesContent":["import { type ReactNode, useId } from 'react';\n\nimport { CheckCircleIcon } from '@phosphor-icons/react/dist/ssr/CheckCircle';\nimport { ClockIcon } from '@phosphor-icons/react/dist/ssr/Clock';\nimport { PauseCircleIcon } from '@phosphor-icons/react/dist/ssr/PauseCircle';\nimport { ProhibitIcon } from '@phosphor-icons/react/dist/ssr/Prohibit';\nimport { QuestionIcon } from '@phosphor-icons/react/dist/ssr/Question';\nimport { WarningCircleIcon } from '@phosphor-icons/react/dist/ssr/WarningCircle';\n\nimport { cn } from '../../utils/cn';\nimport { VISUAL_ELEMENT_SIZES } from '../../utils/componentSizes';\nimport { Text } from '../Text';\nimport { LoadingIndicator } from '../ThinkingState';\nimport { ChatStateTimer } from './ChatStateTimer';\n\nexport type ChatStateStatus =\n | 'pending'\n | 'streaming'\n | 'completed'\n | 'failed'\n | 'interrupted'\n | 'canceled'\n | 'input-required';\n\nexport type ChatStateTimerPrecision = 'seconds' | 'tenths';\n\nconst STATIC_STATES = {\n pending: {\n label: 'Pending',\n icon: ClockIcon,\n iconClassName: 'text-icon-tertiary',\n },\n completed: {\n label: 'Completed',\n icon: CheckCircleIcon,\n iconClassName: 'text-icon-success',\n },\n failed: {\n label: 'Failed',\n icon: WarningCircleIcon,\n iconClassName: 'text-icon-error',\n },\n interrupted: {\n label: 'Interrupted',\n icon: PauseCircleIcon,\n iconClassName: 'text-icon-warning',\n },\n canceled: {\n label: 'Canceled',\n icon: ProhibitIcon,\n iconClassName: 'text-icon-tertiary',\n },\n 'input-required': {\n label: 'Needs input',\n icon: QuestionIcon,\n iconClassName: 'text-icon-warning',\n },\n} satisfies Record<\n Exclude<ChatStateStatus, 'streaming'>,\n { label: string; icon: typeof CheckCircleIcon; iconClassName: string }\n>;\n\nexport interface ChatStateProps {\n status: ChatStateStatus;\n variant?: 'default' | 'simple';\n /** Visible in default; accessible name in simple. Parents own tooltips. */\n label?: ReactNode;\n /** Defaults to true in simple and false in default. */\n showElapsed?: boolean;\n /** Host-supplied duration takes precedence over the internal streaming clock. */\n elapsedMs?: number;\n timerPrecision?: ChatStateTimerPrecision;\n className?: string;\n}\n\nexport function ChatState({\n status,\n variant = 'default',\n label,\n showElapsed = variant === 'simple',\n elapsedMs,\n timerPrecision = 'seconds',\n className,\n}: ChatStateProps) {\n const labelId = useId();\n const simple = variant === 'simple';\n const presentation = status === 'streaming' ? null : STATIC_STATES[status];\n const StatusIcon = presentation?.icon;\n const defaultLabel = presentation?.label ?? 'Streaming';\n const stateLabel = simple\n ? label || defaultLabel\n : label === undefined\n ? defaultLabel\n : label;\n\n const statusContent = (\n <span\n className={cn(\n 'inline-flex min-w-0 items-center',\n status === 'streaming' ? 'gap-space-2' : 'gap-space-1'\n )}\n >\n {status === 'streaming' ? (\n <LoadingIndicator size=\"xs\" tone=\"neutral\" />\n ) : StatusIcon ? (\n <StatusIcon\n size={12}\n weight=\"regular\"\n aria-hidden=\"true\"\n className={cn(\n 'shrink-0',\n VISUAL_ELEMENT_SIZES.xs.className,\n presentation?.iconClassName\n )}\n />\n ) : null}\n <Text\n id={simple ? labelId : undefined}\n as=\"span\"\n variant=\"xs\"\n weight=\"normal\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n className={cn(\n simple\n ? 'sr-only'\n : 'inline-flex min-w-0 items-center break-words leading-4 tracking-normal',\n status === 'failed' ? 'text-error-secondary' : 'text-secondary'\n )}\n >\n {stateLabel}\n </Text>\n </span>\n );\n\n const compactStatus = (\n <span\n role=\"group\"\n aria-labelledby={labelId}\n className=\"inline-flex shrink-0 items-center\"\n >\n {statusContent}\n </span>\n );\n\n return (\n <div\n className={cn(\n 'inline-flex min-h-5 max-w-full items-center gap-space-2 align-middle font-sans',\n simple && 'gap-space-1',\n className\n )}\n >\n {simple ? compactStatus : statusContent}\n <ChatStateTimer\n visible={showElapsed}\n elapsedMs={elapsedMs}\n precision={simple ? 'seconds' : timerPrecision}\n format={simple ? 'seconds' : 'duration'}\n running={status === 'streaming'}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,IAAM,gBAAgB;CACpB,SAAS;EACP,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,WAAW;EACT,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,QAAQ;EACN,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,aAAa;EACX,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,UAAU;EACR,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,kBAAkB;EAChB,OAAO;EACP,MAAM;EACN,eAAe;CACjB;AACF;AAkBA,SAAgB,UAAU,EACxB,QACA,UAAU,WACV,OACA,cAAc,YAAY,UAC1B,WACA,iBAAiB,WACjB,aACiB;CACjB,MAAM,UAAU,MAAM;CACtB,MAAM,SAAS,YAAY;CAC3B,MAAM,eAAe,WAAW,cAAc,OAAO,cAAc;CACnE,MAAM,aAAa,cAAc;CACjC,MAAM,eAAe,cAAc,SAAS;CAC5C,MAAM,aAAa,SACf,SAAS,eACT,UAAU,KAAA,IACR,eACA;CAEN,MAAM,gBACJ,qBAAC,QAAD;EACE,WAAW,GACT,oCACA,WAAW,cAAc,gBAAgB,aAC3C;EAJF,UAAA,CAMG,WAAW,cACV,oBAAC,kBAAD;GAAkB,MAAK;GAAK,MAAK;EAAW,CAAA,IAC1C,aACF,oBAAC,YAAD;GACE,MAAM;GACN,QAAO;GACP,eAAY;GACZ,WAAW,GACT,YACA,qBAAqB,GAAG,WACxB,cAAc,aAChB;EACD,CAAA,IACC,MACJ,oBAAC,MAAD;GACE,IAAI,SAAS,UAAU,KAAA;GACvB,IAAG;GACH,SAAQ;GACR,QAAO;GACP,MAAK;GACL,aAAU;GACV,eAAY;GACZ,WAAW,GACT,SACI,YACA,0EACJ,WAAW,WAAW,yBAAyB,gBACjD;GAEC,UAAA;EACG,CAAA,CACF;;CAGR,MAAM,gBACJ,oBAAC,QAAD;EACE,MAAK;EACL,mBAAiB;EACjB,WAAU;EAET,UAAA;CACG,CAAA;CAGR,OACE,qBAAC,OAAD;EACE,WAAW,GACT,kFACA,UAAU,eACV,SACF;EALF,UAAA,CAOG,SAAS,gBAAgB,eAC1B,oBAAC,gBAAD;GACE,SAAS;GACE;GACX,WAAW,SAAS,YAAY;GAChC,QAAQ,SAAS,YAAY;GAC7B,SAAS,WAAW;EACrB,CAAA,CACE;;AAET"}
1
+ {"version":3,"file":"ChatState.js","names":[],"sources":["../../../src/components/ChatState/ChatState.tsx"],"sourcesContent":["import { type ReactNode, useId } from 'react';\n\nimport { CheckCircleIcon } from '@phosphor-icons/react/dist/ssr/CheckCircle';\nimport { ClockIcon } from '@phosphor-icons/react/dist/ssr/Clock';\nimport { PauseCircleIcon } from '@phosphor-icons/react/dist/ssr/PauseCircle';\nimport { ProhibitIcon } from '@phosphor-icons/react/dist/ssr/Prohibit';\nimport { QuestionIcon } from '@phosphor-icons/react/dist/ssr/Question';\nimport { WarningCircleIcon } from '@phosphor-icons/react/dist/ssr/WarningCircle';\n\nimport { cn } from '../../utils/cn';\nimport { VISUAL_ELEMENT_SIZES } from '../../utils/componentSizes';\nimport { Text } from '../Text';\nimport { LoadingIndicator } from '../ThinkingState';\nimport { ChatStateTimer } from './ChatStateTimer';\n\nexport type ChatStateStatus =\n | 'pending'\n | 'streaming'\n | 'completed'\n | 'failed'\n | 'interrupted'\n | 'canceled'\n | 'input-required';\n\nexport type ChatStateTimerPrecision = 'seconds' | 'tenths';\n\nconst STATIC_STATES = {\n pending: {\n label: 'Pending',\n icon: ClockIcon,\n iconClassName: 'text-icon-tertiary',\n },\n completed: {\n label: 'Completed',\n icon: CheckCircleIcon,\n iconClassName: 'text-icon-success',\n },\n failed: {\n label: 'Failed',\n icon: WarningCircleIcon,\n iconClassName: 'text-icon-error',\n },\n interrupted: {\n label: 'Interrupted',\n icon: PauseCircleIcon,\n iconClassName: 'text-icon-warning',\n },\n canceled: {\n label: 'Canceled',\n icon: ProhibitIcon,\n iconClassName: 'text-icon-tertiary',\n },\n 'input-required': {\n label: 'Needs input',\n icon: QuestionIcon,\n iconClassName: 'text-icon-warning',\n },\n} satisfies Record<\n Exclude<ChatStateStatus, 'streaming'>,\n { label: string; icon: typeof CheckCircleIcon; iconClassName: string }\n>;\n\nexport interface ChatStateProps {\n status: ChatStateStatus;\n variant?: 'default' | 'simple';\n /** Visible in default; accessible name in simple. Parents own tooltips. */\n label?: ReactNode;\n /** Defaults to true in simple and false in default. */\n showElapsed?: boolean;\n /** Host-supplied duration takes precedence over the internal streaming clock. */\n elapsedMs?: number;\n timerPrecision?: ChatStateTimerPrecision;\n className?: string;\n}\n\nexport function ChatState({\n status,\n variant = 'default',\n label,\n showElapsed = variant === 'simple',\n elapsedMs,\n timerPrecision = 'seconds',\n className,\n}: ChatStateProps) {\n const labelId = useId();\n const simple = variant === 'simple';\n const presentation = status === 'streaming' ? null : STATIC_STATES[status];\n const StatusIcon = presentation?.icon;\n const defaultLabel = presentation?.label ?? 'Streaming';\n const stateLabel = simple\n ? label || defaultLabel\n : label === undefined\n ? defaultLabel\n : label;\n\n const statusContent = (\n <span\n className={cn(\n 'inline-flex min-w-0 items-center',\n status === 'streaming' ? 'gap-space-2' : 'gap-space-1'\n )}\n >\n {status === 'streaming' ? (\n <LoadingIndicator size=\"sm\" tone=\"neutral\" />\n ) : StatusIcon ? (\n <StatusIcon\n size={12}\n weight=\"regular\"\n aria-hidden=\"true\"\n className={cn(\n 'shrink-0',\n VISUAL_ELEMENT_SIZES.xs.className,\n presentation?.iconClassName\n )}\n />\n ) : null}\n <Text\n id={simple ? labelId : undefined}\n as=\"span\"\n variant=\"xs\"\n weight=\"normal\"\n role=\"status\"\n aria-live=\"polite\"\n aria-atomic=\"true\"\n className={cn(\n simple\n ? 'sr-only'\n : 'inline-flex min-w-0 items-center break-words leading-4 tracking-normal',\n status === 'failed' ? 'text-error-secondary' : 'text-secondary'\n )}\n >\n {stateLabel}\n </Text>\n </span>\n );\n\n const compactStatus = (\n <span\n role=\"group\"\n aria-labelledby={labelId}\n className=\"inline-flex shrink-0 items-center\"\n >\n {statusContent}\n </span>\n );\n\n return (\n <div\n className={cn(\n 'inline-flex min-h-5 max-w-full items-center gap-space-2 align-middle font-sans',\n simple && 'gap-space-1',\n className\n )}\n >\n {simple ? compactStatus : statusContent}\n <ChatStateTimer\n visible={showElapsed}\n elapsedMs={elapsedMs}\n precision={simple ? 'seconds' : timerPrecision}\n format={simple ? 'seconds' : 'duration'}\n running={status === 'streaming'}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AA0BA,IAAM,gBAAgB;CACpB,SAAS;EACP,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,WAAW;EACT,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,QAAQ;EACN,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,aAAa;EACX,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,UAAU;EACR,OAAO;EACP,MAAM;EACN,eAAe;CACjB;CACA,kBAAkB;EAChB,OAAO;EACP,MAAM;EACN,eAAe;CACjB;AACF;AAkBA,SAAgB,UAAU,EACxB,QACA,UAAU,WACV,OACA,cAAc,YAAY,UAC1B,WACA,iBAAiB,WACjB,aACiB;CACjB,MAAM,UAAU,MAAM;CACtB,MAAM,SAAS,YAAY;CAC3B,MAAM,eAAe,WAAW,cAAc,OAAO,cAAc;CACnE,MAAM,aAAa,cAAc;CACjC,MAAM,eAAe,cAAc,SAAS;CAC5C,MAAM,aAAa,SACf,SAAS,eACT,UAAU,KAAA,IACR,eACA;CAEN,MAAM,gBACJ,qBAAC,QAAD;EACE,WAAW,GACT,oCACA,WAAW,cAAc,gBAAgB,aAC3C;EAJF,UAAA,CAMG,WAAW,cACV,oBAAC,kBAAD;GAAkB,MAAK;GAAK,MAAK;EAAW,CAAA,IAC1C,aACF,oBAAC,YAAD;GACE,MAAM;GACN,QAAO;GACP,eAAY;GACZ,WAAW,GACT,YACA,qBAAqB,GAAG,WACxB,cAAc,aAChB;EACD,CAAA,IACC,MACJ,oBAAC,MAAD;GACE,IAAI,SAAS,UAAU,KAAA;GACvB,IAAG;GACH,SAAQ;GACR,QAAO;GACP,MAAK;GACL,aAAU;GACV,eAAY;GACZ,WAAW,GACT,SACI,YACA,0EACJ,WAAW,WAAW,yBAAyB,gBACjD;GAEC,UAAA;EACG,CAAA,CACF;;CAGR,MAAM,gBACJ,oBAAC,QAAD;EACE,MAAK;EACL,mBAAiB;EACjB,WAAU;EAET,UAAA;CACG,CAAA;CAGR,OACE,qBAAC,OAAD;EACE,WAAW,GACT,kFACA,UAAU,eACV,SACF;EALF,UAAA,CAOG,SAAS,gBAAgB,eAC1B,oBAAC,gBAAD;GACE,SAAS;GACE;GACX,WAAW,SAAS,YAAY;GAChC,QAAQ,SAAS,YAAY;GAC7B,SAAS,WAAW;EACrB,CAAA,CACE;;AAET"}
@@ -166,7 +166,7 @@ function CodeLiteCode(props) {
166
166
  });
167
167
  if (!isBlock) return /* @__PURE__ */ jsxs(Fragment$1, { children: [content, props.children] });
168
168
  return /* @__PURE__ */ jsxs("div", {
169
- className: "border-subtle bg-surface-level-1 w-full max-w-full min-w-0 overflow-hidden rounded-lg border",
169
+ className: "border-subtle dark:border-muted bg-surface-level-1 w-full max-w-full min-w-0 overflow-hidden rounded-lg border",
170
170
  children: [
171
171
  props.toolbar === void 0 ? /* @__PURE__ */ jsx(CodeToolbar, {
172
172
  className: "bg-surface-level-1 pl-space-4 pr-space-3 min-h-8",
@@ -1 +1 @@
1
- {"version":3,"file":"CodeLite.js","names":[],"sources":["../../../src/components/Code/CodeLite.tsx"],"sourcesContent":["import {\n type ReactNode,\n lazy,\n memo,\n Suspense,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { TableVirtuoso } from 'react-virtuoso';\n\nimport { DotsThreeIcon } from '@phosphor-icons/react/dist/ssr/DotsThree';\n\nimport { CaretDownIcon } from '../../icons/PaddedPhosphorIcons';\nimport { cn } from '../../utils/cn';\nimport { useCodeMirror } from '../../utils/useCodeMirror';\nimport { CopyIconButton } from '../CopyButton';\nimport { IconButton } from '../IconButton';\nimport { Text } from '../Text';\nimport {\n type ParsedFile,\n convertFile,\n getVisibleLines,\n parseFile,\n} from './CodeLite.utils';\nimport { CodeToolbar } from './CodeToolbar';\nimport type { LANGUAGES } from './languages/languages';\n\nexport interface CodeLiteCodeProps {\n value: string | undefined;\n language: keyof typeof LANGUAGES | 'plaintext';\n variant?: 'plain' | 'block';\n label?: string;\n toolbar?: ReactNode;\n virtualize?: boolean;\n className?: string;\n children?: ReactNode;\n showGutter?: boolean;\n wrapLines?: boolean;\n highlightText?: string;\n}\n\nexport interface CodeLiteDiffProps {\n variant: 'diff';\n oldString: string;\n newString: string;\n fileName?: string;\n className?: string;\n contextLines?: number;\n children?: ReactNode;\n}\n\nexport type CodeLiteProps = CodeLiteCodeProps | CodeLiteDiffProps;\n\nconst LazyCodeLiteDiff = lazy(() =>\n import('./CodeLiteDiff').then((module) => ({ default: module.CodeLiteDiff }))\n);\n\n/**\n * The preferred component for read-only syntax-highlighted code. It avoids\n * mounting a full CodeMirror editor, making it more performant when rendering\n * multiple code blocks, while retaining folding and optional virtualization.\n * The diff variant loads the unified diff renderer only when requested.\n * Use `Code` only when editing or custom CodeMirror extensions are required.\n */\nexport const CodeLite = memo((props: CodeLiteProps) => {\n if (props.variant === 'diff') {\n return (\n <>\n <Suspense\n fallback={\n <Text role=\"status\" variant=\"xs\" color=\"tertiary\">\n Loading changes…\n </Text>\n }\n >\n <LazyCodeLiteDiff {...props} />\n </Suspense>\n {props.children}\n </>\n );\n }\n\n return <CodeLiteCode {...props} />;\n});\n\nfunction CodeLiteCode(props: CodeLiteCodeProps) {\n const cm = useCodeMirror(props.language !== 'plaintext');\n const reqCount = useRef(0);\n const [parse, setParse] = useState<{\n id: number;\n data: Awaited<ReturnType<typeof parseFile>> | null;\n error: unknown | null;\n }>({ id: -1, data: null, error: null });\n\n useEffect(() => {\n if (!cm || props.language === 'plaintext') return;\n\n const controller = new AbortController();\n const signal = controller.signal;\n const requestId = ++reqCount.current;\n\n setParse({ id: requestId, data: null, error: null });\n\n parseFile(cm, props.language, props.value, { signal }).then(\n (data) => {\n if (signal.aborted) return;\n setParse((prev) => {\n if (prev.id !== requestId) return prev;\n return { id: requestId, data, error: null };\n });\n },\n (error) => {\n if (signal.aborted) return;\n setParse((prev) => {\n if (prev.id !== requestId) return prev;\n return { id: requestId, data: null, error };\n });\n }\n );\n\n return () => controller.abort();\n }, [cm, props.language, props.value]);\n\n const data =\n props.language === 'plaintext'\n ? convertFile(props.value)\n : (parse.data ?? convertFile(props.value));\n\n const [foldIdx, setFoldIdx] = useState<Set<number>>(new Set());\n\n const visibleLines = getVisibleLines(data, foldIdx);\n const showGutter = props.showGutter ?? true;\n const wrapLines = props.wrapLines ?? true;\n const isBlock = props.variant === 'block';\n\n const toggleFold = (n: number) => {\n setFoldIdx((prev) => {\n const curr = new Set(prev);\n if (curr.has(n)) curr.delete(n);\n else curr.add(n);\n return curr;\n });\n };\n\n const itemContent = (_index: number, line: ParsedFile['file'][number]) => (\n <>\n {showGutter && (\n <td\n data-search-ignore=\"\"\n className={cn(\n 'px-px py-0 align-top select-none',\n isBlock && wrapLines && 'w-12'\n )}\n >\n <div className=\"gap-space-1 text-quaternary flex items-center justify-between font-mono whitespace-pre\">\n <span className=\"min-w-8 pl-2.5 text-right\">{line.n}</span>\n\n {line.fold ? (\n <IconButton\n icon={CaretDownIcon}\n label={`${foldIdx.has(line.n) ? 'Expand' : 'Collapse'} code at line ${line.n}`}\n size=\"xxs\"\n variant=\"plain\"\n color=\"secondary\"\n aria-expanded={!foldIdx.has(line.n)}\n onClick={() => toggleFold(line.n)}\n iconWeight=\"regular\"\n iconClassName={cn(\n 'duration-fast transition-transform motion-reduce:transition-none',\n foldIdx.has(line.n) && '-rotate-90'\n )}\n />\n ) : (\n <span className=\"size-4\" />\n )}\n </div>\n </td>\n )}\n\n <td\n data-code-line=\"\"\n className={cn(\n 'px-1.5 py-0 font-mono',\n wrapLines ? 'whitespace-pre-wrap' : 'whitespace-pre',\n isBlock &&\n (wrapLines ? '[overflow-wrap:anywhere]' : '[overflow-wrap:normal]')\n )}\n >\n {line.line.map((token, index) => {\n const tokenText = data.code.slice(token.from, token.to);\n const highlightText = props.highlightText;\n const highlightIndex = highlightText\n ? tokenText.indexOf(highlightText)\n : -1;\n\n return (\n <span key={index} className={cn(token.classes || 'text-tertiary')}>\n {highlightIndex === -1 || !highlightText ? (\n tokenText\n ) : (\n <>\n {tokenText.slice(0, highlightIndex)}\n <span\n data-code-highlight\n className=\"bg-brand-subtle text-brand-primary rounded-xs\"\n >\n {highlightText}\n </span>\n {tokenText.slice(highlightIndex + highlightText.length)}\n </>\n )}\n </span>\n );\n })}\n\n {line.line.length === 0 && (\n <span className=\"text-tertiary\">{'\\n'}</span>\n )}\n\n {foldIdx.has(line.n) && (\n <IconButton\n icon={DotsThreeIcon}\n iconWeight=\"regular\"\n label={`Show folded lines after line ${line.n}`}\n size=\"xxs\"\n variant=\"outlined\"\n color=\"secondary\"\n className=\"border-subtle bg-surface-level-2 text-quaternary hover:bg-surface-level-2-hover\"\n onClick={() => toggleFold(line.n)}\n />\n )}\n </td>\n </>\n );\n\n const className = cn('font-mono text-xs', props.className);\n const accessibleLabel = props.label?.trim() || 'Code block';\n\n const focusClassName =\n 'focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus';\n\n const content = props.virtualize ? (\n <TableVirtuoso\n data={visibleLines}\n className={cn(\n className,\n isBlock && focusClassName,\n isBlock && '[&_table]:!table',\n isBlock && wrapLines && '[&_table]:w-full [&_table]:table-fixed'\n )}\n role={isBlock ? 'region' : undefined}\n aria-label={isBlock ? accessibleLabel : undefined}\n itemContent={itemContent}\n />\n ) : (\n <table\n data-code-lite=\"\"\n className={cn(\n 'w-fit border-spacing-0 [overflow-anchor:none]',\n isBlock && '!table',\n isBlock && wrapLines && 'w-full table-fixed',\n className\n )}\n >\n <tbody>\n {visibleLines.map((line, index) => (\n <tr key={index} className=\"[overflow-anchor:none]\">\n {itemContent(index, line)}\n </tr>\n ))}\n </tbody>\n </table>\n );\n\n if (!isBlock) {\n return (\n <>\n {content}\n {props.children}\n </>\n );\n }\n\n return (\n <div className=\"border-subtle bg-surface-level-1 w-full max-w-full min-w-0 overflow-hidden rounded-lg border\">\n {props.toolbar === undefined ? (\n <CodeToolbar\n className=\"bg-surface-level-1 pl-space-4 pr-space-3 min-h-8\"\n language={\n props.label ??\n (props.language === 'plaintext' ? 'text' : props.language)\n }\n >\n <CopyIconButton copy={props.value ?? ''} label=\"Copy code\" />\n </CodeToolbar>\n ) : (\n props.toolbar\n )}\n <div\n role={props.virtualize ? undefined : 'region'}\n aria-label={props.virtualize ? undefined : accessibleLabel}\n tabIndex={props.virtualize ? undefined : 0}\n className={cn(\n 'bg-brand-muted p-space-3 min-w-0',\n !props.virtualize && 'overflow-x-auto',\n !props.virtualize && focusClassName\n )}\n >\n {content}\n </div>\n {props.children}\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;AAuDA,IAAM,mBAAmB,WACvB,OAAO,oBAAiB,CAAC,MAAM,YAAY,EAAE,SAAS,OAAO,aAAa,EAAE,CAC9E;;;;;;;;AASA,IAAa,WAAW,MAAM,UAAyB;CACrD,IAAI,MAAM,YAAY,QACpB,OACE,qBAAA,YAAA,EAAA,UAAA,CACE,oBAAC,UAAD;EACE,UACE,oBAAC,MAAD;GAAM,MAAK;GAAS,SAAQ;GAAK,OAAM;GAAW,UAAA;EAE5C,CAAA;EAGR,UAAA,oBAAC,kBAAD,EAAkB,GAAI,MAAQ,CAAA;CACtB,CAAA,GACT,MAAM,QACP,EAAA,CAAA;CA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;IAGnD,UAAA,oBAAC,gBAAD;KAAgB,MAAM,MAAM,SAAS;KAAI,OAAM;IAAa,CAAA;GACjD,CAAA,IAEb,MAAM;GAER,oBAAC,OAAD;IACE,MAAM,MAAM,aAAa,KAAA,IAAY;IACrC,cAAY,MAAM,aAAa,KAAA,IAAY;IAC3C,UAAU,MAAM,aAAa,KAAA,IAAY;IACzC,WAAW,GACT,oCACA,CAAC,MAAM,cAAc,mBACrB,CAAC,MAAM,cAAc,cACvB;IAEC,UAAA;GACE,CAAA;GACJ,MAAM;EACJ;;AAET"}
1
+ {"version":3,"file":"CodeLite.js","names":[],"sources":["../../../src/components/Code/CodeLite.tsx"],"sourcesContent":["import {\n type ReactNode,\n lazy,\n memo,\n Suspense,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { TableVirtuoso } from 'react-virtuoso';\n\nimport { DotsThreeIcon } from '@phosphor-icons/react/dist/ssr/DotsThree';\n\nimport { CaretDownIcon } from '../../icons/PaddedPhosphorIcons';\nimport { cn } from '../../utils/cn';\nimport { useCodeMirror } from '../../utils/useCodeMirror';\nimport { CopyIconButton } from '../CopyButton';\nimport { IconButton } from '../IconButton';\nimport { Text } from '../Text';\nimport {\n type ParsedFile,\n convertFile,\n getVisibleLines,\n parseFile,\n} from './CodeLite.utils';\nimport { CodeToolbar } from './CodeToolbar';\nimport type { LANGUAGES } from './languages/languages';\n\nexport interface CodeLiteCodeProps {\n value: string | undefined;\n language: keyof typeof LANGUAGES | 'plaintext';\n variant?: 'plain' | 'block';\n label?: string;\n toolbar?: ReactNode;\n virtualize?: boolean;\n className?: string;\n children?: ReactNode;\n showGutter?: boolean;\n wrapLines?: boolean;\n highlightText?: string;\n}\n\nexport interface CodeLiteDiffProps {\n variant: 'diff';\n oldString: string;\n newString: string;\n fileName?: string;\n className?: string;\n contextLines?: number;\n children?: ReactNode;\n}\n\nexport type CodeLiteProps = CodeLiteCodeProps | CodeLiteDiffProps;\n\nconst LazyCodeLiteDiff = lazy(() =>\n import('./CodeLiteDiff').then((module) => ({ default: module.CodeLiteDiff }))\n);\n\n/**\n * The preferred component for read-only syntax-highlighted code. It avoids\n * mounting a full CodeMirror editor, making it more performant when rendering\n * multiple code blocks, while retaining folding and optional virtualization.\n * The diff variant loads the unified diff renderer only when requested.\n * Use `Code` only when editing or custom CodeMirror extensions are required.\n */\nexport const CodeLite = memo((props: CodeLiteProps) => {\n if (props.variant === 'diff') {\n return (\n <>\n <Suspense\n fallback={\n <Text role=\"status\" variant=\"xs\" color=\"tertiary\">\n Loading changes…\n </Text>\n }\n >\n <LazyCodeLiteDiff {...props} />\n </Suspense>\n {props.children}\n </>\n );\n }\n\n return <CodeLiteCode {...props} />;\n});\n\nfunction CodeLiteCode(props: CodeLiteCodeProps) {\n const cm = useCodeMirror(props.language !== 'plaintext');\n const reqCount = useRef(0);\n const [parse, setParse] = useState<{\n id: number;\n data: Awaited<ReturnType<typeof parseFile>> | null;\n error: unknown | null;\n }>({ id: -1, data: null, error: null });\n\n useEffect(() => {\n if (!cm || props.language === 'plaintext') return;\n\n const controller = new AbortController();\n const signal = controller.signal;\n const requestId = ++reqCount.current;\n\n setParse({ id: requestId, data: null, error: null });\n\n parseFile(cm, props.language, props.value, { signal }).then(\n (data) => {\n if (signal.aborted) return;\n setParse((prev) => {\n if (prev.id !== requestId) return prev;\n return { id: requestId, data, error: null };\n });\n },\n (error) => {\n if (signal.aborted) return;\n setParse((prev) => {\n if (prev.id !== requestId) return prev;\n return { id: requestId, data: null, error };\n });\n }\n );\n\n return () => controller.abort();\n }, [cm, props.language, props.value]);\n\n const data =\n props.language === 'plaintext'\n ? convertFile(props.value)\n : (parse.data ?? convertFile(props.value));\n\n const [foldIdx, setFoldIdx] = useState<Set<number>>(new Set());\n\n const visibleLines = getVisibleLines(data, foldIdx);\n const showGutter = props.showGutter ?? true;\n const wrapLines = props.wrapLines ?? true;\n const isBlock = props.variant === 'block';\n\n const toggleFold = (n: number) => {\n setFoldIdx((prev) => {\n const curr = new Set(prev);\n if (curr.has(n)) curr.delete(n);\n else curr.add(n);\n return curr;\n });\n };\n\n const itemContent = (_index: number, line: ParsedFile['file'][number]) => (\n <>\n {showGutter && (\n <td\n data-search-ignore=\"\"\n className={cn(\n 'px-px py-0 align-top select-none',\n isBlock && wrapLines && 'w-12'\n )}\n >\n <div className=\"gap-space-1 text-quaternary flex items-center justify-between font-mono whitespace-pre\">\n <span className=\"min-w-8 pl-2.5 text-right\">{line.n}</span>\n\n {line.fold ? (\n <IconButton\n icon={CaretDownIcon}\n label={`${foldIdx.has(line.n) ? 'Expand' : 'Collapse'} code at line ${line.n}`}\n size=\"xxs\"\n variant=\"plain\"\n color=\"secondary\"\n aria-expanded={!foldIdx.has(line.n)}\n onClick={() => toggleFold(line.n)}\n iconWeight=\"regular\"\n iconClassName={cn(\n 'duration-fast transition-transform motion-reduce:transition-none',\n foldIdx.has(line.n) && '-rotate-90'\n )}\n />\n ) : (\n <span className=\"size-4\" />\n )}\n </div>\n </td>\n )}\n\n <td\n data-code-line=\"\"\n className={cn(\n 'px-1.5 py-0 font-mono',\n wrapLines ? 'whitespace-pre-wrap' : 'whitespace-pre',\n isBlock &&\n (wrapLines ? '[overflow-wrap:anywhere]' : '[overflow-wrap:normal]')\n )}\n >\n {line.line.map((token, index) => {\n const tokenText = data.code.slice(token.from, token.to);\n const highlightText = props.highlightText;\n const highlightIndex = highlightText\n ? tokenText.indexOf(highlightText)\n : -1;\n\n return (\n <span key={index} className={cn(token.classes || 'text-tertiary')}>\n {highlightIndex === -1 || !highlightText ? (\n tokenText\n ) : (\n <>\n {tokenText.slice(0, highlightIndex)}\n <span\n data-code-highlight\n className=\"bg-brand-subtle text-brand-primary rounded-xs\"\n >\n {highlightText}\n </span>\n {tokenText.slice(highlightIndex + highlightText.length)}\n </>\n )}\n </span>\n );\n })}\n\n {line.line.length === 0 && (\n <span className=\"text-tertiary\">{'\\n'}</span>\n )}\n\n {foldIdx.has(line.n) && (\n <IconButton\n icon={DotsThreeIcon}\n iconWeight=\"regular\"\n label={`Show folded lines after line ${line.n}`}\n size=\"xxs\"\n variant=\"outlined\"\n color=\"secondary\"\n className=\"border-subtle bg-surface-level-2 text-quaternary hover:bg-surface-level-2-hover\"\n onClick={() => toggleFold(line.n)}\n />\n )}\n </td>\n </>\n );\n\n const className = cn('font-mono text-xs', props.className);\n const accessibleLabel = props.label?.trim() || 'Code block';\n\n const focusClassName =\n 'focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-focus';\n\n const content = props.virtualize ? (\n <TableVirtuoso\n data={visibleLines}\n className={cn(\n className,\n isBlock && focusClassName,\n isBlock && '[&_table]:!table',\n isBlock && wrapLines && '[&_table]:w-full [&_table]:table-fixed'\n )}\n role={isBlock ? 'region' : undefined}\n aria-label={isBlock ? accessibleLabel : undefined}\n itemContent={itemContent}\n />\n ) : (\n <table\n data-code-lite=\"\"\n className={cn(\n 'w-fit border-spacing-0 [overflow-anchor:none]',\n isBlock && '!table',\n isBlock && wrapLines && 'w-full table-fixed',\n className\n )}\n >\n <tbody>\n {visibleLines.map((line, index) => (\n <tr key={index} className=\"[overflow-anchor:none]\">\n {itemContent(index, line)}\n </tr>\n ))}\n </tbody>\n </table>\n );\n\n if (!isBlock) {\n return (\n <>\n {content}\n {props.children}\n </>\n );\n }\n\n return (\n <div className=\"border-subtle dark:border-muted bg-surface-level-1 w-full max-w-full min-w-0 overflow-hidden rounded-lg border\">\n {props.toolbar === undefined ? (\n <CodeToolbar\n className=\"bg-surface-level-1 pl-space-4 pr-space-3 min-h-8\"\n language={\n props.label ??\n (props.language === 'plaintext' ? 'text' : props.language)\n }\n >\n <CopyIconButton copy={props.value ?? ''} label=\"Copy code\" />\n </CodeToolbar>\n ) : (\n props.toolbar\n )}\n <div\n role={props.virtualize ? undefined : 'region'}\n aria-label={props.virtualize ? undefined : accessibleLabel}\n tabIndex={props.virtualize ? undefined : 0}\n className={cn(\n 'bg-brand-muted p-space-3 min-w-0',\n !props.virtualize && 'overflow-x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A,IAED,oBAAC,SAAD;EACE,kBAAe;EACf,WAAW,GACT,iDACA,WAAW,UACX,WAAW,aAAa,sBACxB,SACF;EAEA,UAAA,oBAAC,SAAD,EAAA,UACG,aAAa,KAAK,MAAM,UACvB,oBAAC,MAAD;GAAgB,WAAU;GACvB,UAAA,YAAY,OAAO,IAAI;EACtB,GAFK,KAEL,CACL,EACI,CAAA;CACF,CAAA;CAGT,IAAI,CAAC,SACH,OACE,qBAAA,YAAA,EAAA,UAAA,CACG,SACA,MAAM,QACP,EAAA,CAAA;CAIN,OACE,qBAAC,OAAD;EAAK,WAAU;EAAf,UAAA;GACG,MAAM,YAAY,KAAA,IACjB,oBAAC,aAAD;IACE,WAAU;IACV,UACE,MAAM,UACL,MAAM,aAAa,cAAc,SAAS,MAAM;IAGnD,UAAA,oBAAC,gBAAD;KAAgB,MAAM,MAAM,SAAS;KAAI,OAAM;IAAa,CAAA;GACjD,CAAA,IAEb,MAAM;GAER,oBAAC,OAAD;IACE,MAAM,MAAM,aAAa,KAAA,IAAY;IACrC,cAAY,MAAM,aAAa,KAAA,IAAY;IAC3C,UAAU,MAAM,aAAa,KAAA,IAAY;IACzC,WAAW,GACT,oCACA,CAAC,MAAM,cAAc,mBACrB,CAAC,MAAM,cAAc,cACvB;IAEC,UAAA;GACE,CAAA;GACJ,MAAM;EACJ;;AAET"}
@@ -47,7 +47,7 @@ var CodeLiteDiff = ({ oldString, newString, fileName, className, contextLines })
47
47
  const displayFileName = fileName ? fileName.split("/").pop() : null;
48
48
  const hasChanges = fileDiff.hunks.length > 0;
49
49
  return /* @__PURE__ */ jsxs("div", {
50
- className: cn("border-subtle bg-surface-level-1 w-full min-w-0 overflow-hidden rounded-lg border", className),
50
+ className: cn("border-subtle dark:border-muted bg-surface-level-1 w-full min-w-0 overflow-hidden rounded-lg border", className),
51
51
  children: [/* @__PURE__ */ jsx(CodeToolbar, {
52
52
  className: cn("bg-surface-level-1 px-space-4", hasChanges ? "min-h-9" : "min-h-11 border-0"),
53
53
  language: displayFileName && /* @__PURE__ */ jsxs("span", {
@@ -1 +1 @@
1
- {"version":3,"file":"CodeLiteDiff.js","names":[],"sources":["../../../src/components/Code/CodeLiteDiff.tsx"],"sourcesContent":["import { useMemo } from 'react';\n\nimport { FileCodeIcon } from '@phosphor-icons/react/dist/ssr/FileCode';\nimport { parseDiffFromFile } from '@pierre/diffs';\nimport type { FileContents } from '@pierre/diffs';\nimport { FileDiff } from '@pierre/diffs/react';\n\nimport { useColorScheme } from '../../hooks/useColorScheme';\nimport { cn } from '../../utils/cn';\nimport { Icon } from '../Icon';\nimport { Text } from '../Text';\nimport type { CodeLiteDiffProps } from './CodeLite';\nimport { CodeToolbar } from './CodeToolbar';\n\nconst DIFF_THEME = { light: 'github-light', dark: 'github-dark' };\n\nconst withTrailingNewline = (text: string): string =>\n text.length > 0 && !text.endsWith('\\n') ? `${text}\\n` : text;\n\nexport const CodeLiteDiff = ({\n oldString,\n newString,\n fileName,\n className,\n contextLines,\n}: CodeLiteDiffProps) => {\n const { resolvedMode } = useColorScheme();\n\n const { fileDiff, additions, deletions } = useMemo(() => {\n const name = fileName || 'file';\n const oldFile: FileContents = {\n name,\n contents: withTrailingNewline(oldString),\n };\n const newFile: FileContents = {\n name,\n contents: withTrailingNewline(newString),\n };\n const fileDiff = parseDiffFromFile(\n oldFile,\n newFile,\n contextLines != null ? { context: contextLines } : undefined\n );\n\n let additions = 0;\n let deletions = 0;\n for (const hunk of fileDiff.hunks) {\n additions += hunk.additionLines;\n deletions += hunk.deletionLines;\n }\n return { fileDiff, additions, deletions };\n }, [oldString, newString, fileName, contextLines]);\n\n const displayFileName = fileName ? fileName.split('/').pop() : null;\n const hasChanges = fileDiff.hunks.length > 0;\n\n return (\n <div\n className={cn(\n 'border-subtle bg-surface-level-1 w-full min-w-0 overflow-hidden rounded-lg border',\n className\n )}\n >\n <CodeToolbar\n className={cn(\n 'bg-surface-level-1 px-space-4',\n hasChanges ? 'min-h-9' : 'min-h-11 border-0'\n )}\n language={\n displayFileName && (\n <span className=\"gap-space-2 flex min-w-0 items-center\">\n <Icon\n icon={FileCodeIcon}\n size=\"md\"\n weight=\"regular\"\n aria-hidden\n className=\"text-icon-tertiary\"\n />\n <span className=\"min-w-0 break-all\">{displayFileName}</span>\n </span>\n )\n }\n >\n {hasChanges ? (\n <>\n <Text\n as=\"span\"\n variant=\"xs\"\n className=\"text-success-secondary tabular-nums\"\n >\n +{additions}\n </Text>\n <Text\n as=\"span\"\n variant=\"xs\"\n className=\"text-error-secondary tabular-nums\"\n >\n -{deletions}\n </Text>\n </>\n ) : (\n <Text as=\"span\" variant=\"xs\" color=\"tertiary\">\n No changes\n </Text>\n )}\n </CodeToolbar>\n {hasChanges && (\n <div className=\"bg-brand-muted py-space-3 pl-space-3 max-h-64 min-w-0 overflow-auto text-xs\">\n <FileDiff\n className=\"[--diffs-bg:var(--bg-brand-muted)] [--diffs-gap-block:0px] [--diffs-overflow-override:auto]\"\n fileDiff={fileDiff}\n disableWorkerPool\n options={{\n diffStyle: 'unified',\n theme: DIFF_THEME,\n themeType: resolvedMode,\n preferredHighlighter: 'shiki-js',\n disableFileHeader: true,\n }}\n />\n </div>\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;AAcA,IAAM,aAAa;CAAE,OAAO;CAAgB,MAAM;AAAc;AAEhE,IAAM,uBAAuB,SAC3B,KAAK,SAAS,KAAK,CAAC,KAAK,SAAS,IAAI,IAAI,GAAG,KAAK,MAAM;AAE1D,IAAa,gBAAgB,EAC3B,WACA,WACA,UACA,WACA,mBACuB;CACvB,MAAM,EAAE,iBAAiB,eAAe;CAExC,MAAM,EAAE,UAAU,WAAW,cAAc,cAAc;EACvD,MAAM,OAAO,YAAY;EACzB,MAAM,UAAwB;GAC5B;GACA,UAAU,oBAAoB,SAAS;EACzC;EACA,MAAM,UAAwB;GAC5B;GACA,UAAU,oBAAoB,SAAS;EACzC;EACA,MAAM,WAAW,kBACf,SACA,SACA,gBAAgB,OAAO,EAAE,S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":[],"sources":["../../../src/components/Code/CodeLiteDiff.tsx"],"sourcesContent":["import { useMemo } from 'react';\n\nimport { FileCodeIcon } from '@phosphor-icons/react/dist/ssr/FileCode';\nimport { parseDiffFromFile } from '@pierre/diffs';\nimport type { FileContents } from '@pierre/diffs';\nimport { FileDiff } from '@pierre/diffs/react';\n\nimport { useColorScheme } from '../../hooks/useColorScheme';\nimport { cn } from '../../utils/cn';\nimport { Icon } from '../Icon';\nimport { Text } from '../Text';\nimport type { CodeLiteDiffProps } from './CodeLite';\nimport { CodeToolbar } from './CodeToolbar';\n\nconst DIFF_THEME = { light: 'github-light', dark: 'github-dark' };\n\nconst withTrailingNewline = (text: string): string =>\n text.length > 0 && !text.endsWith('\\n') ? `${text}\\n` : text;\n\nexport const CodeLiteDiff = ({\n oldString,\n newString,\n fileName,\n className,\n contextLines,\n}: CodeLiteDiffProps) => {\n const { resolvedMode } = useColorScheme();\n\n const { fileDiff, additions, deletions } = useMemo(() => {\n const name = fileName || 'file';\n const oldFile: FileContents = {\n name,\n contents: withTrailingNewline(oldString),\n };\n const newFile: FileContents = {\n name,\n contents: withTrailingNewline(newString),\n };\n const fileDiff = parseDiffFromFile(\n oldFile,\n newFile,\n contextLines != null ? { context: contextLines } : undefined\n );\n\n let additions = 0;\n let deletions = 0;\n for (const hunk of fileDiff.hunks) {\n additions += hunk.additionLines;\n deletions += hunk.deletionLines;\n }\n return { fileDiff, additions, deletions };\n }, [oldString, newString, fileName, contextLines]);\n\n const displayFileName = fileName ? fileName.split('/').pop() : null;\n const hasChanges = fileDiff.hunks.length > 0;\n\n return (\n <div\n className={cn(\n 'border-subtle dark:border-muted bg-surface-level-1 w-full min-w-0 overflow-hidden rounded-lg border',\n className\n )}\n >\n <CodeToolbar\n className={cn(\n 'bg-surface-level-1 px-space-4',\n hasChanges ? 'min-h-9' : 'min-h-11 border-0'\n )}\n language={\n displayFileName && (\n <span className=\"gap-space-2 flex min-w-0 items-center\">\n <Icon\n icon={FileCodeIcon}\n size=\"md\"\n weight=\"regular\"\n aria-hidden\n className=\"text-icon-tertiary\"\n />\n <span className=\"min-w-0 break-all\">{displayFileName}</span>\n </span>\n )\n }\n >\n {hasChanges ? (\n <>\n <Text\n as=\"span\"\n variant=\"xs\"\n className=\"text-success-secondary tabular-nums\"\n >\n +{additions}\n </Text>\n <Text\n as=\"span\"\n variant=\"xs\"\n className=\"text-error-secondary tabular-nums\"\n >\n -{deletions}\n </Text>\n </>\n ) : (\n <Text as=\"span\" variant=\"xs\" color=\"tertiary\">\n No changes\n </Text>\n )}\n </CodeToolbar>\n {hasChanges && (\n <div className=\"bg-brand-muted py-space-3 pl-space-3 max-h-64 min-w-0 overflow-auto text-xs\">\n <FileDiff\n className=\"[--diffs-bg:var(--bg-brand-muted)] [--diffs-gap-block:0px] [--diffs-overflow-override:auto]\"\n fileDiff={fileDiff}\n disableWorkerPool\n options={{\n diffStyle: 'unified',\n theme: DIFF_THEME,\n themeType: resolvedMode,\n preferredHighlighter: 'shiki-js',\n disableFileHeader: true,\n }}\n />\n </div>\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;AAcA,IAAM,aAAa;CAAE,OAAO;CAAgB,MAAM;AAAc;AAEhE,IAAM,uBAAuB,SAC3B,KAAK,SAAS,KAAK,CAAC,KAAK,SAAS,IAAI,IAAI,GAAG,KAAK,MAAM;AAE1D,IAAa,gBAAgB,EAC3B,WACA,WACA,UACA,WACA,mBACuB;CACvB,MAAM,EAAE,iBAAiB,eAAe;CAExC,MAAM,EAAE,UAAU,WAAW,cAAc,cAAc;EACvD,MAAM,OAAO,YAAY;EACzB,MAAM,UAAwB;GAC5B;GACA,UAAU,oBAAoB,SAAS;EACzC;EACA,MAAM,UAAwB;GAC5B;GACA,UAAU,oBAAoB,SAAS;EACzC;EACA,MAAM,WAAW,kBACf,SACA,SACA,gBAAgB,OAAO,EAAE,SAAS,aAAa,IAAI,KAAA,CACrD;EAEA,IAAI,YAAY;EAChB,IAAI,YAAY;EAChB,KAAK,MAAM,QAAQ,SAAS,OAAO;GACjC,aAAa,KAAK;GAClB,aAAa,KAAK;EACpB;EACA,OAAO;GAAE;GAAU;GAAW;EAAU;CAC1C,GAAG;EAAC;EAAW;EAAW;EAAU;CAAY,CAAC;CAEjD,MAAM,kBAAkB,WAAW,SAAS,MAAM,GAAG,CAAC,CAAC,IAAI,IAAI;CAC/D,MAAM,aAAa,SAAS,MAAM,SAAS;CAE3C,OACE,qBAAC,OAAD;EACE,WAAW,GACT,uGACA,SACF;EAJF,UAAA,CAME,oBAAC,aAAD;GACE,WAAW,GACT,iCACA,aAAa,YAAY,mBAC3B;GACA,UACE,mBACE,qBAAC,QAAD;IAAM,WAAU;IAAhB,UAAA,CACE,oBAAC,MAAD;KACE,MAAM;KACN,MAAK;KACL,QAAO;KACP,eAAA;KACA,WAAU;IACX,CAAA,GACD,oBAAC,QAAD;KAAM,WAAU;KAAqB,UAAA;IAAsB,CAAA,CACvD;;GAIT,UAAA,aACC,qBAAA,YAAA,EAAA,UAAA,CACE,qBAAC,MAAD;IACE,IAAG;IACH,SAAQ;IACR,WAAU;IAHZ,UAAA,CAIC,KACG,SACE;GACN,CAAA,GAAA,qBAAC,MAAD;IACE,IAAG;IACH,SAAQ;IACR,WAAU;IAHZ,UAAA,CAIC,KACG,SACE;GACN,CAAA,CAAA,EAAA,CAAA,IAEF,oBAAC,MAAD;IAAM,IAAG;IAAO,SAAQ;IAAK,OAAM;IAAW,UAAA;GAExC,CAAA;EAEG,CAAA,GACZ,cACC,oBAAC,OAAD;GAAK,WAAU;GACb,UAAA,oBAAC,UAAD;IACE,WAAU;IACA;IACV,mBAAA;IACA,SAAS;KACP,WAAW;KACX,OAAO;KACP,WAAW;KACX,sBAAsB;KACtB,mBAAmB;IACrB;GACD,CAAA;EACE,CAAA,CAEJ;;AAET"}
@@ -4,7 +4,7 @@ import { jsx, jsxs } from "react/jsx-runtime";
4
4
  //#region packages/components/src/components/Code/CodeToolbar.tsx
5
5
  function CodeToolbar({ language, children, className }) {
6
6
  return /* @__PURE__ */ jsxs("div", {
7
- className: cn("gap-space-1 border-subtle px-space-3 py-space-1 flex min-w-0 items-center justify-between border-b", className),
7
+ className: cn("gap-space-1 border-subtle dark:border-muted px-space-3 py-space-1 flex min-w-0 items-center justify-between border-b", className),
8
8
  children: [/* @__PURE__ */ jsx(Text, {
9
9
  as: "div",
10
10
  variant: "xs",
@@ -1 +1 @@
1
- {"version":3,"file":"CodeToolbar.js","names":[],"sources":["../../../src/components/Code/CodeToolbar.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { cn } from '../../utils/cn';\nimport { Text } from '../Text';\n\nexport interface CodeToolbarProps {\n language?: ReactNode;\n children?: ReactNode;\n className?: string;\n}\n\nexport function CodeToolbar({\n language,\n children,\n className,\n}: CodeToolbarProps) {\n return (\n <div\n className={cn(\n 'gap-space-1 border-subtle px-space-3 py-space-1 flex min-w-0 items-center justify-between border-b',\n className\n )}\n >\n <Text as=\"div\" variant=\"xs\" color=\"secondary\" className=\"min-w-0\">\n {language}\n </Text>\n {children && (\n <div className=\"gap-space-1 flex shrink-0 items-center\">{children}</div>\n )}\n </div>\n );\n}\n"],"mappings":";;;;AAWA,SAAgB,YAAY,EAC1B,UACA,UACA,aACmB;CACnB,OACE,qBAAC,OAAD;EACE,WAAW,GACT,sGACA,SACF;EAJF,UAAA,CAME,oBAAC,MAAD;GAAM,IAAG;GAAM,SAAQ;GAAK,OAAM;GAAY,WAAU;GACrD,UAAA;EACG,CAAA,GACL,YACC,oBAAC,OAAD;GAAK,WAAU;GAA0C;EAAc,CAAA,CAEtE;;AAET"}
1
+ {"version":3,"file":"CodeToolbar.js","names":[],"sources":["../../../src/components/Code/CodeToolbar.tsx"],"sourcesContent":["import type { ReactNode } from 'react';\n\nimport { cn } from '../../utils/cn';\nimport { Text } from '../Text';\n\nexport interface CodeToolbarProps {\n language?: ReactNode;\n children?: ReactNode;\n className?: string;\n}\n\nexport function CodeToolbar({\n language,\n children,\n className,\n}: CodeToolbarProps) {\n return (\n <div\n className={cn(\n 'gap-space-1 border-subtle dark:border-muted px-space-3 py-space-1 flex min-w-0 items-center justify-between border-b',\n className\n )}\n >\n <Text as=\"div\" variant=\"xs\" color=\"secondary\" className=\"min-w-0\">\n {language}\n </Text>\n {children && (\n <div className=\"gap-space-1 flex shrink-0 items-center\">{children}</div>\n )}\n </div>\n );\n}\n"],"mappings":";;;;AAWA,SAAgB,YAAY,EAC1B,UACA,UACA,aACmB;CACnB,OACE,qBAAC,OAAD;EACE,WAAW,GACT,wHACA,SACF;EAJF,UAAA,CAME,oBAAC,MAAD;GAAM,IAAG;GAAM,SAAQ;GAAK,OAAM;GAAY,WAAU;GACrD,UAAA;EACG,CAAA,GACL,YACC,oBAAC,OAAD;GAAK,WAAU;GAA0C;EAAc,CAAA,CAEtE;;AAET"}
@@ -131,7 +131,7 @@ var Code = ({ value, readOnly, onChange, autoFocus, placeholder, ariaLabel, lang
131
131
  });
132
132
  return /* @__PURE__ */ jsxs("div", {
133
133
  "data-testid": testId,
134
- className: cn("group relative text-xs", height && !hasToolbar && "h-full", hasToolbar && "flex flex-col overflow-hidden rounded-lg border border-subtle bg-surface-level-2"),
134
+ className: cn("group relative text-xs", height && !hasToolbar && "h-full", hasToolbar && "flex flex-col overflow-hidden rounded-lg border border-subtle dark:border-muted bg-surface-level-2"),
135
135
  style: hasToolbar ? {
136
136
  width,
137
137
  height
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/components/Code/index.tsx"],"sourcesContent":["import { type ReactNode, useMemo, useState } from 'react';\n\nimport type { Extension } from '@codemirror/state';\nimport type { EditorView, ViewUpdate } from '@codemirror/view';\n\nimport { useColorScheme } from '../../hooks/useColorScheme';\nimport { cn } from '../../utils/cn';\nimport { getNonce } from '../../utils/csp-nonce';\nimport { useCodeMirror } from '../../utils/useCodeMirror';\nimport { useZIndex } from '../../utils/useZIndex';\nimport zIndices from '../../utils/zIndices';\nimport { Banner } from '../Banner';\nimport { Button } from '../Button';\nimport { CopyButton } from '../CopyButton';\nimport { ErrorBoundary } from '../ErrorBoundary';\nimport { PlainTextEditor } from '../PlainTextEditor';\nimport {\n getLanguageExtension,\n getSyntaxTheme,\n useEditorTheme,\n} from './Code.utils';\nimport { MAX_CODE_LENGTH } from './constants';\nimport { getImageReplacerExtensions } from './ImageReplacerExtension';\nimport type { CodeLanguageType } from './types';\n\nexport { CodeLanguageSelect } from './CodeLanguageSelect';\nexport type { CodeLanguageSelectProps } from './CodeLanguageSelect';\nexport { CodeToolbar } from './CodeToolbar';\nexport type { CodeToolbarProps } from './CodeToolbar';\nexport { CODE_LANGUAGES, resolveCodeLanguage } from './codeLanguages';\nexport type { CodeLanguageType } from './types';\n\n/** Props for the syntax-highlighted CodeMirror block. */\nexport interface CodeProps {\n language: CodeLanguageType;\n extensions?: Extension[];\n value: string | undefined;\n onChange?: (code: string) => void;\n readOnly?: boolean;\n autoFocus?: boolean;\n height?: string;\n maxHeight?: string;\n omitMaxHeight?: boolean;\n width?: string;\n fontSize?: string;\n placeholder?: string;\n ariaLabel?: string;\n toolbar?: ReactNode;\n /** Floating copy control when no toolbar is supplied. */\n showCopyButton?: boolean;\n showFoldGutter?: boolean;\n testId?: string;\n variant?: 'plain' | 'full';\n onCreateEditor?: (view: EditorView) => void;\n /** Receives document and selection updates, including programmatic changes. */\n onUpdate?: (update: ViewUpdate) => void;\n converterExtensions?: Extension[];\n}\n\n/**\n * Renders syntax-highlighted code with optional editing and copy support.\n *\n * Import directly from `@langchain/macaw-components/Code` so the CodeMirror\n * dependency is only loaded by surfaces that use it.\n */\nexport const Code = ({\n value,\n readOnly,\n onChange,\n autoFocus,\n placeholder,\n ariaLabel,\n language,\n extensions,\n converterExtensions,\n height,\n maxHeight,\n omitMaxHeight,\n width,\n fontSize,\n onCreateEditor,\n onUpdate,\n variant = 'full',\n testId,\n toolbar,\n showCopyButton,\n showFoldGutter = true,\n}: CodeProps) => {\n const cm = useCodeMirror();\n const { isDarkMode } = useColorScheme();\n const copyButtonZIndex = useZIndex(zIndices.floatingBar);\n\n const [ignoreWarning, setIgnoreWarning] = useState(false);\n\n const lineCount = value?.split('\\n').length ?? 0;\n\n // Stable CM-derived values — memoized so StateField/ViewPlugin instances are\n // created once and not recreated on every render (which resets editor state).\n const imageReplacerExtensions = useMemo(\n () => (cm ? getImageReplacerExtensions(cm) : null),\n [cm]\n );\n const editorTheme = useEditorTheme(cm, { variant, showFoldGutter });\n const langExt = useMemo(\n () => (cm ? getLanguageExtension(cm, language) : null),\n [cm, language]\n );\n const syntaxTheme = useMemo(\n () => (cm ? getSyntaxTheme(cm, isDarkMode) : null),\n [cm, isDarkMode]\n );\n\n const nonce = getNonce();\n\n const mExtensions = useMemo(() => {\n if (!cm || !imageReplacerExtensions || !langExt || !editorTheme) return [];\n const { keymap, defaultKeymap, EditorView } = cm;\n const { decorationStateField, imageReplacerPlugin } =\n imageReplacerExtensions;\n return [\n keymap.of([{ key: 'Mod-Enter', run: () => true }, ...defaultKeymap]),\n langExt.language,\n ...(extensions ?? []),\n // YAML folding blocks rendering for large files, so cap it at 500 lines.\n ...(lineCount <= 500\n ? (converterExtensions ?? langExt.extensions ?? [])\n : []),\n imageReplacerPlugin,\n decorationStateField,\n EditorView.lineWrapping,\n editorTheme,\n // Untagged text otherwise uses the syntax theme's dim default.\n ...(language === 'plaintext'\n ? [\n EditorView.theme({\n '.cm-content': { color: 'var(--text-primary)' },\n }),\n ]\n : []),\n ...(ariaLabel\n ? [EditorView.contentAttributes.of({ 'aria-label': ariaLabel })]\n : []),\n ...(readOnly ? [EditorView.editable.of(false)] : []),\n ...(nonce ? [EditorView.cspNonce.of(nonce)] : []),\n ];\n // extensions/converterExtensions are caller-provided arrays. Include them\n // directly so changes propagate.\n }, [\n cm,\n imageReplacerExtensions,\n langExt,\n editorTheme,\n language,\n ariaLabel,\n extensions,\n converterExtensions,\n lineCount,\n readOnly,\n nonce,\n ]);\n\n if (value == null) return null;\n\n // Avoid mounting CodeMirror by default when style recomputation could block rendering.\n const showWarning = lineCount > MAX_CODE_LENGTH && !ignoreWarning;\n const hasToolbar = Boolean(toolbar);\n const CodeMirror = cm?.CodeMirror;\n const editorHeight = hasToolbar && height ? '100%' : height;\n const editor = showWarning ? (\n <Banner\n intent=\"warning\"\n action={\n <Button\n variant=\"underlined\"\n color=\"secondary\"\n size=\"sm\"\n onClick={() => setIgnoreWarning(true)}\n >\n Open anyway\n </Button>\n }\n >\n This content might be too long to display in the editor.\n </Banner>\n ) : !CodeMirror || !syntaxTheme ? (\n <PlainTextEditor\n value={value}\n readOnly={true}\n placeholder={placeholder}\n className={cn(\n 'font-mono text-xs',\n height && 'h-full overflow-auto',\n maxHeight && !omitMaxHeight && `max-h-[${maxHeight}]`\n )}\n />\n ) : (\n <ErrorBoundary fallback={() => <div>Error showing code</div>}>\n <CodeMirror\n value={value}\n readOnly={readOnly}\n autoFocus={autoFocus}\n placeholder={placeholder}\n height={editorHeight}\n maxHeight={omitMaxHeight ? undefined : (maxHeight ?? '50vh')}\n width={hasToolbar ? '100%' : width}\n style={{\n fontSize,\n backgroundColor: 'var(--bg-surface-level-2)',\n borderRadius: hasToolbar ? 0 : 'var(--radius-lg)',\n cursor: readOnly ? 'default' : 'text',\n ...(editorHeight ? { height: editorHeight } : {}),\n ...(width ? { width: hasToolbar ? '100%' : width } : {}),\n }}\n extensions={mExtensions}\n onCreateEditor={onCreateEditor}\n onUpdate={onUpdate}\n onChange={(code) => {\n if (!readOnly) {\n onChange?.(code);\n }\n }}\n theme={syntaxTheme}\n basicSetup={{\n foldGutter: showFoldGutter,\n highlightActiveLine: false,\n highlightActiveLineGutter: false,\n defaultKeymap: false,\n ...(variant === 'plain' && {\n lineNumbers: false,\n highlightSelectionMatches: false,\n }),\n }}\n />\n </ErrorBoundary>\n );\n\n return (\n <div\n data-testid={testId}\n className={cn(\n 'group relative text-xs',\n height && !hasToolbar && 'h-full',\n hasToolbar &&\n 'flex flex-col overflow-hidden rounded-lg border border-subtle bg-surface-level-2'\n )}\n style={hasToolbar ? { width, height } : undefined}\n >\n {hasToolbar ? (\n <>\n <div className=\"shrink-0\">{toolbar}</div>\n <div className={cn(height && 'min-h-0 flex-1 overflow-auto')}>\n {editor}\n </div>\n </>\n ) : (\n editor\n )}\n {!hasToolbar &&\n !showWarning &&\n CodeMirror &&\n syntaxTheme &&\n showCopyButton &&\n value && (\n <div\n onMouseDown={(e) => e.preventDefault()}\n className=\"absolute right-1 top-1 opacity-0 transition-opacity duration-300 group-hover:opacity-100\"\n style={{ zIndex: copyButtonZIndex }}\n >\n <CopyButton copy={value} variant=\"icon\" />\n </div>\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,IAAa,QAAQ,EACnB,OACA,UACA,UACA,WACA,aACA,WACA,UACA,YACA,qBACA,QACA,WACA,eACA,OACA,UACA,gBACA,UACA,UAAU,QACV,QACA,SACA,gBACA,iBAAiB,WACF;CACf,MAAM,KAAK,cAAc;CACzB,MAAM,EAAE,eAAe,eAAe;CACtC,MAAM,mBAAmB,UAAU,SAAS,WAAW;CAEvD,MAAM,CAAC,eAAe,oBAAoB,SAAS,KAAK;CAExD,MAAM,YAAY,OAAO,MAAM,IAAI,CAAC,CAAC,UAAU;CAI/C,MAAM,0BAA0B,cACvB,KAAK,2BAA2B,EAAE,IAAI,MAC7C,CAAC,EAAE,CACL;CACA,MAAM,cAAc,eAAe,IAAI;EAAE;EAAS;CAAe,CAAC;CAClE,MAAM,UAAU,cACP,KAAK,qBAAqB,IAAI,QAAQ,IAAI,MACjD,CAAC,IAAI,QAAQ,CACf;CACA,MAAM,cAAc,cACX,KAAK,eAAe,IAAI,UAAU,IAAI,MAC7C,CAAC,IAAI,UAAU,CACjB;CAEA,MAAM,QAAQ,SAAS;CAEvB,MAAM,cAAc,cAAc;EAChC,IAAI,CAAC,MAAM,CAAC,2BAA2B,CAAC,WAAW,CAAC,aAAa,OAAO,CAAC;EACzE,MAAM,EAAE,QAAQ,eAA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YAAD;GACS;GACG;GACC;GACE;GACb,QAAQ;GACR,WAAW,gBAAgB,KAAA,IAAa,aAAa;GACrD,OAAO,aAAa,SAAS;GAC7B,OAAO;IACL;IACA,iBAAiB;IACjB,cAAc,aAAa,IAAI;IAC/B,QAAQ,WAAW,YAAY;IAC/B,GAAI,eAAe,EAAE,QAAQ,aAAa,IAAI,CAAC;IAC/C,GAAI,QAAQ,EAAE,OAAO,aAAa,SAAS,MAAM,IAAI,CAAC;GACxD;GACA,YAAY;GACI;GACN;GACV,WAAW,SAAS;IAClB,IAAI,CAAC,UACH,WAAW,IAAI;GAEnB;GACA,OAAO;GACP,YAAY;IACV,YAAY;IACZ,qBAAqB;IACrB,2BAA2B;IAC3B,eAAe;IACf,GAAI,YAAY,WAAW;KACzB,aAAa;KACb,2BAA2B;IAC7B;GACF;EACD,CAAA;CACY,CAAA;CAGjB,OACE,qBAAC,OAAD;EACE,eAAa;EACb,WAAW,GACT,0BACA,UAAU,CAAC,cAAc,UACzB,cACE,kFACJ;EACA,OAAO,aAAa;GAAE;GAAO;EAAO,IAAI,KAAA;EAR1C,UAAA,CAUG,aACC,qBAAA,YAAA,EAAA,UAAA,CACE,oBAAC,OAAD;GAAK,WAAU;GAAY,UAAA;EAAa,CAAA,GACxC,oBAAC,OAAD;GAAK,WAAW,GAAG,UAAU,8BAA8B;GACxD,UAAA;EACE,CAAA,CACL,EAAA,CAAA,IAEF,QAED,CAAC,cACA,CAAC,eACD,cACA,eACA,kBACA,SACE,oBAAC,OAAD;GACE,cAAc,MAAM,EAAE,eAAe;GACrC,WAAU;GACV,OAAO,EAAE,QAAQ,iBAAiB;GAElC,UAAA,oBAAC,YAAD;IAAY,MAAM;IAAO,SAAQ;GAAQ,CAAA;EACtC,CAAA,CAEN;;AAET"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/components/Code/index.tsx"],"sourcesContent":["import { type ReactNode, useMemo, useState } from 'react';\n\nimport type { Extension } from '@codemirror/state';\nimport type { EditorView, ViewUpdate } from '@codemirror/view';\n\nimport { useColorScheme } from '../../hooks/useColorScheme';\nimport { cn } from '../../utils/cn';\nimport { getNonce } from '../../utils/csp-nonce';\nimport { useCodeMirror } from '../../utils/useCodeMirror';\nimport { useZIndex } from '../../utils/useZIndex';\nimport zIndices from '../../utils/zIndices';\nimport { Banner } from '../Banner';\nimport { Button } from '../Button';\nimport { CopyButton } from '../CopyButton';\nimport { ErrorBoundary } from '../ErrorBoundary';\nimport { PlainTextEditor } from '../PlainTextEditor';\nimport {\n getLanguageExtension,\n getSyntaxTheme,\n useEditorTheme,\n} from './Code.utils';\nimport { MAX_CODE_LENGTH } from './constants';\nimport { getImageReplacerExtensions } from './ImageReplacerExtension';\nimport type { CodeLanguageType } from './types';\n\nexport { CodeLanguageSelect } from './CodeLanguageSelect';\nexport type { CodeLanguageSelectProps } from './CodeLanguageSelect';\nexport { CodeToolbar } from './CodeToolbar';\nexport type { CodeToolbarProps } from './CodeToolbar';\nexport { CODE_LANGUAGES, resolveCodeLanguage } from './codeLanguages';\nexport type { CodeLanguageType } from './types';\n\n/** Props for the syntax-highlighted CodeMirror block. */\nexport interface CodeProps {\n language: CodeLanguageType;\n extensions?: Extension[];\n value: string | undefined;\n onChange?: (code: string) => void;\n readOnly?: boolean;\n autoFocus?: boolean;\n height?: string;\n maxHeight?: string;\n omitMaxHeight?: boolean;\n width?: string;\n fontSize?: string;\n placeholder?: string;\n ariaLabel?: string;\n toolbar?: ReactNode;\n /** Floating copy control when no toolbar is supplied. */\n showCopyButton?: boolean;\n showFoldGutter?: boolean;\n testId?: string;\n variant?: 'plain' | 'full';\n onCreateEditor?: (view: EditorView) => void;\n /** Receives document and selection updates, including programmatic changes. */\n onUpdate?: (update: ViewUpdate) => void;\n converterExtensions?: Extension[];\n}\n\n/**\n * Renders syntax-highlighted code with optional editing and copy support.\n *\n * Import directly from `@langchain/macaw-components/Code` so the CodeMirror\n * dependency is only loaded by surfaces that use it.\n */\nexport const Code = ({\n value,\n readOnly,\n onChange,\n autoFocus,\n placeholder,\n ariaLabel,\n language,\n extensions,\n converterExtensions,\n height,\n maxHeight,\n omitMaxHeight,\n width,\n fontSize,\n onCreateEditor,\n onUpdate,\n variant = 'full',\n testId,\n toolbar,\n showCopyButton,\n showFoldGutter = true,\n}: CodeProps) => {\n const cm = useCodeMirror();\n const { isDarkMode } = useColorScheme();\n const copyButtonZIndex = useZIndex(zIndices.floatingBar);\n\n const [ignoreWarning, setIgnoreWarning] = useState(false);\n\n const lineCount = value?.split('\\n').length ?? 0;\n\n // Stable CM-derived values — memoized so StateField/ViewPlugin instances are\n // created once and not recreated on every render (which resets editor state).\n const imageReplacerExtensions = useMemo(\n () => (cm ? getImageReplacerExtensions(cm) : null),\n [cm]\n );\n const editorTheme = useEditorTheme(cm, { variant, showFoldGutter });\n const langExt = useMemo(\n () => (cm ? getLanguageExtension(cm, language) : null),\n [cm, language]\n );\n const syntaxTheme = useMemo(\n () => (cm ? getSyntaxTheme(cm, isDarkMode) : null),\n [cm, isDarkMode]\n );\n\n const nonce = getNonce();\n\n const mExtensions = useMemo(() => {\n if (!cm || !imageReplacerExtensions || !langExt || !editorTheme) return [];\n const { keymap, defaultKeymap, EditorView } = cm;\n const { decorationStateField, imageReplacerPlugin } =\n imageReplacerExtensions;\n return [\n keymap.of([{ key: 'Mod-Enter', run: () => true }, ...defaultKeymap]),\n langExt.language,\n ...(extensions ?? []),\n // YAML folding blocks rendering for large files, so cap it at 500 lines.\n ...(lineCount <= 500\n ? (converterExtensions ?? langExt.extensions ?? [])\n : []),\n imageReplacerPlugin,\n decorationStateField,\n EditorView.lineWrapping,\n editorTheme,\n // Untagged text otherwise uses the syntax theme's dim default.\n ...(language === 'plaintext'\n ? [\n EditorView.theme({\n '.cm-content': { color: 'var(--text-primary)' },\n }),\n ]\n : []),\n ...(ariaLabel\n ? [EditorView.contentAttributes.of({ 'aria-label': ariaLabel })]\n : []),\n ...(readOnly ? [EditorView.editable.of(false)] : []),\n ...(nonce ? [EditorView.cspNonce.of(nonce)] : []),\n ];\n // extensions/converterExtensions are caller-provided arrays. Include them\n // directly so changes propagate.\n }, [\n cm,\n imageReplacerExtensions,\n langExt,\n editorTheme,\n language,\n ariaLabel,\n extensions,\n converterExtensions,\n lineCount,\n readOnly,\n nonce,\n ]);\n\n if (value == null) return null;\n\n // Avoid mounting CodeMirror by default when style recomputation could block rendering.\n const showWarning = lineCount > MAX_CODE_LENGTH && !ignoreWarning;\n const hasToolbar = Boolean(toolbar);\n const CodeMirror = cm?.CodeMirror;\n const editorHeight = hasToolbar && height ? '100%' : height;\n const editor = showWarning ? (\n <Banner\n intent=\"warning\"\n action={\n <Button\n variant=\"underlined\"\n color=\"secondary\"\n size=\"sm\"\n onClick={() => setIgnoreWarning(true)}\n >\n Open anyway\n </Button>\n }\n >\n This content might be too long to display in the editor.\n </Banner>\n ) : !CodeMirror || !syntaxTheme ? (\n <PlainTextEditor\n value={value}\n readOnly={true}\n placeholder={placeholder}\n className={cn(\n 'font-mono text-xs',\n height && 'h-full overflow-auto',\n maxHeight && !omitMaxHeight && `max-h-[${maxHeight}]`\n )}\n />\n ) : (\n <ErrorBoundary fallback={() => <div>Error showing code</div>}>\n <CodeMirror\n value={value}\n readOnly={readOnly}\n autoFocus={autoFocus}\n placeholder={placeholder}\n height={editorHeight}\n maxHeight={omitMaxHeight ? undefined : (maxHeight ?? '50vh')}\n width={hasToolbar ? '100%' : width}\n style={{\n fontSize,\n backgroundColor: 'var(--bg-surface-level-2)',\n borderRadius: hasToolbar ? 0 : 'var(--radius-lg)',\n cursor: readOnly ? 'default' : 'text',\n ...(editorHeight ? { height: editorHeight } : {}),\n ...(width ? { width: hasToolbar ? '100%' : width } : {}),\n }}\n extensions={mExtensions}\n onCreateEditor={onCreateEditor}\n onUpdate={onUpdate}\n onChange={(code) => {\n if (!readOnly) {\n onChange?.(code);\n }\n }}\n theme={syntaxTheme}\n basicSetup={{\n foldGutter: showFoldGutter,\n highlightActiveLine: false,\n highlightActiveLineGutter: false,\n defaultKeymap: false,\n ...(variant === 'plain' && {\n lineNumbers: false,\n highlightSelectionMatches: false,\n }),\n }}\n />\n </ErrorBoundary>\n );\n\n return (\n <div\n data-testid={testId}\n className={cn(\n 'group relative text-xs',\n height && !hasToolbar && 'h-full',\n hasToolbar &&\n 'flex flex-col overflow-hidden rounded-lg border border-subtle dark:border-muted bg-surface-level-2'\n )}\n style={hasToolbar ? { width, height } : undefined}\n >\n {hasToolbar ? (\n <>\n <div className=\"shrink-0\">{toolbar}</div>\n <div className={cn(height && 'min-h-0 flex-1 overflow-auto')}>\n {editor}\n </div>\n </>\n ) : (\n editor\n )}\n {!hasToolbar &&\n !showWarning &&\n CodeMirror &&\n syntaxTheme &&\n showCopyButton &&\n value && (\n <div\n onMouseDown={(e) => e.preventDefault()}\n className=\"absolute right-1 top-1 opacity-0 transition-opacity duration-300 group-hover:opacity-100\"\n style={{ zIndex: copyButtonZIndex }}\n >\n <CopyButton copy={value} variant=\"icon\" />\n </div>\n )}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAiEA,IAAa,QAAQ,EACnB,OACA,UACA,UACA,WACA,aACA,WACA,UACA,YACA,qBACA,QACA,WACA,eACA,OACA,UACA,gBACA,UACA,UAAU,QACV,QACA,SACA,gBACA,iBAAiB,WACF;CACf,MAAM,KAAK,cAAc;CACzB,MAAM,EAAE,eAAe,eAAe;CACtC,MAAM,mBAAmB,UAAU,SAAS,WAAW;CAEvD,MAAM,CAAC,eAAe,oBAAoB,SAAS,KAAK;CAExD,MAAM,YAAY,OAAO,MAAM,IAAI,CAAC,CAAC,UAAU;CAI/C,MAAM,0BAA0B,cACvB,KAAK,2BAA2B,EAAE,IAAI,MAC7C,CAAC,EAAE,CACL;CACA,MAAM,cAAc,eAAe,IAAI;EAAE;EAAS;CAAe,CAAC;CAClE,MAAM,UAAU,cACP,KAAK,qBAAqB,IAAI,QAAQ,IAAI,MACjD,CAAC,IAAI,QAAQ,CACf;CACA,MAA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BAAiB;GAElC,UAAA,oBAAC,YAAD;IAAY,MAAM;IAAO,SAAQ;GAAQ,CAAA;EACtC,CAAA,CAEN;;AAET"}
@@ -22,6 +22,14 @@ export interface MarkdownDisplayProps {
22
22
  * linkified.
23
23
  */
24
24
  containerHeight?: string;
25
+ /**
26
+ * Longest content, in characters, rendered as Markdown; longer content
27
+ * renders as plain text. Defaults to the shared text length limit. Raise it,
28
+ * or pass `Infinity`, only for content of bounded size such as chat answers:
29
+ * parsing cost grows with length, and the default keeps views of large
30
+ * untrusted content responsive.
31
+ */
32
+ maxMarkdownLength?: number;
25
33
  /** Preserve single newlines visually without changing Markdown parsing. */
26
34
  preserveNewlines?: boolean;
27
35
  /** Wrap long fenced code lines by default, or scroll them horizontally. */
@@ -53,10 +61,11 @@ export interface MarkdownDisplayProps {
53
61
  *
54
62
  * Raw HTML is never interpreted. Tags display as text by default; opt in to
55
63
  * XML sections turn custom wrappers into labels and nested blockquotes.
56
- * Content above the shared text length limit renders as plain text,
57
- * truncated behind a Show more toggle unless `fullLength` is set.
64
+ * Content above `maxMarkdownLength` (by default the shared text length limit)
65
+ * renders as plain text, truncated behind a Show more toggle unless
66
+ * `fullLength` is set.
58
67
  */
59
- export declare function MarkdownDisplay({ content, isStreaming, xmlTags, className, fullLength, containerHeight, preserveNewlines, codeOverflow, textColor, loadImages, components, trailingContent, afterContent, }: MarkdownDisplayProps): import("react").JSX.Element;
68
+ export declare function MarkdownDisplay({ content, isStreaming, xmlTags, className, fullLength, containerHeight, maxMarkdownLength, preserveNewlines, codeOverflow, textColor, loadImages, components, trailingContent, afterContent, }: MarkdownDisplayProps): import("react").JSX.Element;
60
69
  export declare namespace MarkdownDisplay {
61
70
  var displayName: string;
62
71
  }