@mieweb/ui 0.9.0-dev.0 → 0.9.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/dist/{chunk-WIAQQNFU.cjs → chunk-2A2FLQJC.cjs} +1138 -12
  2. package/dist/chunk-2A2FLQJC.cjs.map +1 -0
  3. package/dist/{chunk-5BVFVXHN.cjs → chunk-5VXRKOPR.cjs} +16 -525
  4. package/dist/chunk-5VXRKOPR.cjs.map +1 -0
  5. package/dist/{chunk-O6GJ4IYS.js → chunk-IF3X2WZP.js} +16 -521
  6. package/dist/chunk-IF3X2WZP.js.map +1 -0
  7. package/dist/{chunk-22CYDCXA.js → chunk-KATEJG2F.js} +1137 -13
  8. package/dist/chunk-KATEJG2F.js.map +1 -0
  9. package/dist/{chunk-FQBTGS3E.cjs → chunk-O425FKDI.cjs} +563 -55
  10. package/dist/chunk-O425FKDI.cjs.map +1 -0
  11. package/dist/{chunk-MXQ7J4BB.js → chunk-RPG2ZP2T.js} +557 -53
  12. package/dist/chunk-RPG2ZP2T.js.map +1 -0
  13. package/dist/components/SuperChat/index.cjs +36 -17
  14. package/dist/components/SuperChat/index.cjs.map +1 -1
  15. package/dist/components/SuperChat/index.d.cts +16 -3
  16. package/dist/components/SuperChat/index.d.ts +16 -3
  17. package/dist/components/SuperChat/index.js +31 -12
  18. package/dist/components/SuperChat/index.js.map +1 -1
  19. package/dist/components/SuperChat/plugins/index.cjs +3 -3
  20. package/dist/components/SuperChat/plugins/index.js +2 -2
  21. package/dist/index.cjs +820 -1930
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.js +663 -1780
  24. package/dist/index.js.map +1 -1
  25. package/package.json +1 -1
  26. package/dist/chunk-22CYDCXA.js.map +0 -1
  27. package/dist/chunk-5BVFVXHN.cjs.map +0 -1
  28. package/dist/chunk-FQBTGS3E.cjs.map +0 -1
  29. package/dist/chunk-MXQ7J4BB.js.map +0 -1
  30. package/dist/chunk-O6GJ4IYS.js.map +0 -1
  31. package/dist/chunk-WIAQQNFU.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/components/SuperChat/render/createMarkdownRenderer.tsx","../../../src/components/SuperChat/parts.tsx","../../../src/components/SuperChat/VirtualThread.tsx","../../../src/components/SuperChat/SuperChat.tsx","../../../src/components/SuperChat/SuperChatConversations.tsx","../../../src/components/SuperChat/SuperChatInbox.tsx"],"names":["defaultSchema","jsx","cn","remarkGfm","rehypeSanitize","defaultUrlTransform","React","MarkdownContent","TextRenderContext","Markdown","Avatar","SparklesIcon","jsxs","Fragment","Badge","React2","DropdownItem","Dropdown","MessageActionsBar","EllipsisIcon","DropdownSubmenu","MessageRow","CheckIcon","ClipboardIcon","PencilIcon","ChatBubble","MCPToolCallDisplay","AITypingIndicator","cva","React3","useVirtualizer","React4","CloseIcon","MessageComposer","React5","React6"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAS,wBAAA,GAA2B;AAClC,EAAA,MAAM,SAAA,GAAY,CAAC,IAAA,KAA0B;AAC3C,IAAA,IAAI,CAAC,KAAK,QAAA,EAAU;AACpB,IAAA,MAAM,OAAoB,EAAC;AAC3B,IAAA,KAAA,MAAW,KAAA,IAAS,KAAK,QAAA,EAAU;AACjC,MAAA,IAAI,KAAA,CAAM,SAAS,MAAA,IAAU,KAAA,CAAM,SAAS,KAAA,CAAM,KAAA,CAAM,QAAA,CAAS,IAAI,CAAA,EAAG;AACtE,QAAA,MAAM,QAAA,GAAW,KAAA,CAAM,KAAA,CAAM,KAAA,CAAM,IAAI,CAAA;AACvC,QAAA,QAAA,CAAS,OAAA,CAAQ,CAAC,OAAA,EAAS,CAAA,KAAM;AAC/B,UAAA,IAAI,IAAI,CAAA,EAAG,IAAA,CAAK,KAAK,EAAE,IAAA,EAAM,SAAS,CAAA;AACtC,UAAA,IAAI,OAAA,OAAc,IAAA,CAAK,EA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ACF;AAAA,MAEC,QAAA,EAAA;AAAA,QAAA,WAAA,oBACCD,cAAAA;AAAA,UAAC,sBAAA;AAAA,UAAA;AAAA,YACC,aAAA;AAAA,YACA,oBAAA,EAAsB,QAAA;AAAA,YACtB,oBAAA,EAAsB,UAAA;AAAA,YACtB,iBAAA;AAAA,YACA,SAAA,EAAWC,oBAAA;AAAA,cACT,gBAAA;AAAA,cACA,eAAe,MAAA,IAAU;AAAA;AAC3B;AAAA,SACF;AAAA,QAGD,yBACCD,cAAAA;AAAA,UAAC,SAAA;AAAA,UAAA;AAAA,YACC,YAAA,EAAc,MAAA;AAAA,YACd,oBAAA;AAAA,YACA,aAAA;AAAA,YACA,iBAAA;AAAA,YACA,cAAA;AAAA,YACA,QAAA;AAAA,YACA,iBAAA;AAAA,YACA,KAAA;AAAA,YACA,WAAA;AAAA,YACA,WAAA;AAAA,YACA,iBAAA;AAAA,YACA,aAAA;AAAA,YACA,eAAA;AAAA,YACA,oBAAA;AAAA,YACA,gBAAA;AAAA,YACA,MAAA,EAAQ,WAAA,GAAc,MAAM,aAAA,CAAc,MAAM,CAAA,GAAI,MAAA;AAAA,YACpD,SAAA,EAAWC,oBAAA;AAAA,cACT,WAAA,IAAe,eAAe,MAAA,IAAU;AAAA;AAC1C;AAAA,4BAGFD,cAAAA;AAAA,UAAC,SAAA;AAAA,UAAA;AAAA,YACC,WAAA,EAAU,WAAA;AAAA,YACV,SAAA,EAAWC,oBAAA;AAAA,cACT,qEAAA;AAAA,cACA,WAAA,IAAe,UAAA,KAAe,MAAA,GAAS,gBAAA,GAAmB;AAAA,aAC5D;AAAA,YACD,QAAA,EAAA;AAAA;AAAA;AAED;AAAA;AAAA,GAEJ;AAEJ","file":"index.cjs","sourcesContent":["/**\n * SuperChat Markdown render composer.\n *\n * Composes a list of {@link SuperChatRenderPlugin}s into a single\n * {@link AIRenderTextContent} implementation that plugs into the AI module's\n * `renderTextContent` seam. Ships **Markdown core** (GFM) with `rehype-sanitize`\n * applied to untrusted model/agent output. Math / code / GenUI / NITRO / mermaid\n * are added by passing the corresponding opt-in plugins.\n *\n * The host owns the trust boundary: untrusted content is always sanitized via an\n * allow-list schema, extended by each plugin's `sanitizeSchema` so token\n * classNames (syntax highlighting) and KaTeX markup survive.\n */\n\nimport * as React from 'react';\nimport Markdown, {\n defaultUrlTransform,\n type Components,\n type Options,\n} from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport rehypeSanitize, { defaultSchema } from 'rehype-sanitize';\nimport { cn } from '../../../utils/cn';\nimport { TextRenderContext } from './renderContext';\nimport type {\n AIRenderTextContent,\n AITextRenderContext,\n SuperChatRenderPlugin,\n} from '../types';\n\ntype PluggableList = NonNullable<Options['remarkPlugins']>;\ntype SanitizeSchema = Record<string, unknown>;\n\n/**\n * Minimal mdast node shape we touch when splitting soft line breaks. Kept local\n * so the renderer stays free of extra `unist`/`mdast` util dependencies.\n */\ninterface MdastNode {\n type: string;\n value?: string;\n children?: MdastNode[];\n}\n\n/**\n * A self-contained `remark-breaks` equivalent: turns soft line breaks (single\n * `\\n` inside a paragraph) into hard breaks so chat messages preserve the\n * newlines the author typed — the expected behavior for messaging UIs, where\n * Markdown's default \"collapse single newlines to spaces\" is surprising.\n *\n * Only `text` nodes are split, so fenced/inline code (which carry their value\n * on non-`text` nodes) and existing hard breaks are left untouched.\n */\nfunction remarkPreserveLineBreaks() {\n const splitNode = (node: MdastNode): void => {\n if (!node.children) return;\n const next: MdastNode[] = [];\n for (const child of node.children) {\n if (child.type === 'text' && child.value && child.value.includes('\\n')) {\n const segments = child.value.split('\\n');\n segments.forEach((segment, i) => {\n if (i > 0) next.push({ type: 'break' });\n if (segment) next.push({ type: 'text', value: segment });\n });\n } else {\n splitNode(child);\n next.push(child);\n }\n }\n node.children = next;\n };\n return (tree: MdastNode) => splitNode(tree);\n}\n\n/**\n * A sanitize schema that, on top of the library default, lets syntax-highlight\n * token classes (`hljs-*`) and `language-*` survive on `code`/`pre`/`span`.\n */\nfunction baseSanitizeSchema(): SanitizeSchema {\n const schema = JSON.parse(JSON.stringify(defaultSchema)) as SanitizeSchema;\n const attributes = (schema.attributes ?? {}) as Record<string, unknown[]>;\n\n const allowClass = (tag: string) => {\n const existing = (attributes[tag] ?? []) as unknown[];\n // Drop any prior restricted className rule, allow className broadly.\n const withoutClass = existing.filter(\n (a) => !(Array.isArray(a) && a[0] === 'className')\n );\n attributes[tag] = [...withoutClass, 'className'];\n };\n\n allowClass('code');\n allowClass('pre');\n allowClass('span');\n allowClass('div');\n\n schema.attributes = attributes;\n return schema;\n}\n\n/** Shallow-merge a plugin's sanitize contribution into the running schema. */\nfunction mergeSanitizeSchema(\n base: SanitizeSchema,\n extra?: SanitizeSchema\n): SanitizeSchema {\n if (!extra) return base;\n const out: SanitizeSchema = { ...base };\n\n // tagNames: union\n if (Array.isArray(extra.tagNames)) {\n const a = (base.tagNames as string[] | undefined) ?? [];\n out.tagNames = Array.from(new Set([...a, ...(extra.tagNames as string[])]));\n }\n\n // attributes: per-tag concat\n if (extra.attributes && typeof extra.attributes === 'object') {\n const baseAttrs = {\n ...((base.attributes as Record<string, unknown[]>) ?? {}),\n };\n for (const [tag, attrs] of Object.entries(\n extra.attributes as Record<string, unknown[]>\n )) {\n baseAttrs[tag] = [...(baseAttrs[tag] ?? []), ...attrs];\n }\n out.attributes = baseAttrs;\n }\n\n // protocols: per-attribute union (e.g. allow `data:`/`blob:` image src)\n if (extra.protocols && typeof extra.protocols === 'object') {\n const baseProtocols = {\n ...((base.protocols as Record<string, string[]>) ?? {}),\n };\n for (const [attr, protocols] of Object.entries(\n extra.protocols as Record<string, string[]>\n )) {\n baseProtocols[attr] = Array.from(\n new Set([...(baseProtocols[attr] ?? []), ...protocols])\n );\n }\n out.protocols = baseProtocols;\n }\n\n // any other keys (clobber)\n for (const [k, v] of Object.entries(extra)) {\n if (k === 'tagNames' || k === 'attributes' || k === 'protocols') continue;\n out[k] = v;\n }\n return out;\n}\n\n/** Default node components, themed with `--mieweb-*` tokens via Tailwind. */\nfunction baseComponents(): Components {\n return {\n a: ({ node: _node, children, ...props }) => (\n <a\n {...props}\n className={cn(\n 'text-primary-800 hover:text-primary-900 dark:text-primary-300 underline underline-offset-2',\n props.className\n )}\n // External model output: open links safely.\n target={props.target ?? '_blank'}\n rel={props.rel ?? 'noopener noreferrer'}\n >\n {children}\n </a>\n ),\n pre: ({ node: _node, ...props }) => (\n <pre\n {...props}\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- scrollable code blocks need keyboard focus for horizontal scrolling\n tabIndex={0}\n className={cn(\n 'overflow-x-auto rounded-lg bg-neutral-900 p-3 text-sm text-neutral-100 dark:bg-neutral-950',\n props.className\n )}\n />\n ),\n code: ({ node: _node, ...props }) => {\n const isBlock =\n typeof props.className === 'string' &&\n props.className.includes('language-');\n return (\n <code\n {...props}\n className={cn(\n !isBlock &&\n 'rounded bg-neutral-200 px-1 py-0.5 text-[0.85em] text-neutral-800 dark:bg-neutral-700 dark:text-neutral-100',\n props.className\n )}\n />\n );\n },\n input: ({ node: _node, ...props }) => {\n if (props.type === 'checkbox') {\n return (\n <input\n {...props}\n aria-label={\n props['aria-label'] ??\n (props['aria-labelledby'] ? undefined : 'Task list item')\n }\n />\n );\n }\n return <input {...props} />;\n },\n table: ({ node: _node, ...props }) => (\n <div className=\"my-2 overflow-x-auto\">\n <table\n {...props}\n className={cn(\n 'w-full border-collapse text-sm [&_td]:border [&_td]:border-neutral-200 [&_td]:px-2 [&_td]:py-1 dark:[&_td]:border-neutral-700 [&_th]:border [&_th]:border-neutral-200 [&_th]:px-2 [&_th]:py-1 [&_th]:text-start dark:[&_th]:border-neutral-700',\n props.className\n )}\n />\n </div>\n ),\n // Tailwind's preflight resets list markers/padding; restore them explicitly\n // so bullets/numbers show without depending on the typography plugin.\n ul: ({ node: _node, ...props }) => (\n <ul {...props} className={cn('list-disc ps-5', props.className)} />\n ),\n ol: ({ node: _node, ...props }) => (\n <ol {...props} className={cn('list-decimal ps-5', props.className)} />\n ),\n li: ({ node: _node, ...props }) => (\n <li {...props} className={cn('ps-1', props.className)} />\n ),\n // Preflight also flattens headings to body size/weight; restore a sensible\n // hierarchy without depending on the typography plugin.\n h1: ({ node: _node, children, ...props }) => (\n <h1\n {...props}\n className={cn('mt-3 mb-1 text-xl font-semibold', props.className)}\n >\n {children}\n </h1>\n ),\n h2: ({ node: _node, children, ...props }) => (\n <h2\n {...props}\n className={cn('mt-3 mb-1 text-lg font-semibold', props.className)}\n >\n {children}\n </h2>\n ),\n h3: ({ node: _node, children, ...props }) => (\n <h3\n {...props}\n className={cn('mt-2 mb-1 text-base font-semibold', props.className)}\n >\n {children}\n </h3>\n ),\n h4: ({ node: _node, children, ...props }) => (\n <h4\n {...props}\n className={cn('mt-2 mb-1 text-sm font-semibold', props.className)}\n >\n {children}\n </h4>\n ),\n h5: ({ node: _node, children, ...props }) => (\n <h5\n {...props}\n className={cn('mt-2 mb-1 text-sm font-semibold', props.className)}\n >\n {children}\n </h5>\n ),\n h6: ({ node: _node, children, ...props }) => (\n <h6\n {...props}\n className={cn(\n 'mt-2 mb-1 text-xs font-semibold tracking-wide uppercase',\n props.className\n )}\n >\n {children}\n </h6>\n ),\n hr: ({ node: _node, ...props }) => (\n <hr\n {...props}\n className={cn(\n 'my-2 border-neutral-300 dark:border-neutral-600',\n props.className\n )}\n />\n ),\n };\n}\n\nexport interface CreateMarkdownRendererOptions {\n /** Opt-in rich plugins (code, math, genui, nitro, mermaid, …). */\n plugins?: SuperChatRenderPlugin[];\n /**\n * Disable sanitization. **Only** set this when the content is fully trusted\n * (e.g. authored by the host, never model output). Defaults to `false`.\n */\n trusted?: boolean;\n}\n\n/**\n * Build an {@link AIRenderTextContent} from a set of render plugins.\n *\n * @example\n * const render = createMarkdownRenderer({ plugins: [createCodePlugin(), createMathPlugin()] });\n * <AIChat renderTextContent={render} … />\n */\nexport function createMarkdownRenderer(\n options: CreateMarkdownRendererOptions = {}\n): AIRenderTextContent {\n const { plugins = [], trusted = false } = options;\n\n const remarkPlugins: PluggableList = [\n remarkGfm,\n remarkPreserveLineBreaks,\n ...plugins.flatMap((p) => (p.remarkPlugins ?? []) as PluggableList),\n ];\n\n const pluginRehype: PluggableList = plugins.flatMap(\n (p) => (p.rehypePlugins ?? []) as PluggableList\n );\n\n const sanitizeSchema = plugins.reduce<SanitizeSchema>(\n (acc, p) => mergeSanitizeSchema(acc, p.sanitizeSchema),\n baseSanitizeSchema()\n );\n\n // Sanitize must run AFTER highlight/katex so their classNames are present to\n // be allow-listed, then stripped of anything not permitted.\n const rehypePlugins: PluggableList = trusted\n ? pluginRehype\n : [...pluginRehype, [rehypeSanitize, sanitizeSchema]];\n\n const components: Components = plugins.reduce<Components>(\n (acc, p) => ({ ...acc, ...(p.components as Components | undefined) }),\n baseComponents()\n );\n\n const MarkdownRenderer = (text: string, ctx: AITextRenderContext) => (\n <MarkdownContent\n key={ctx.messageId}\n text={text}\n messageId={ctx.messageId}\n streaming={ctx.streaming}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins as Options['rehypePlugins']}\n components={components}\n />\n );\n\n return MarkdownRenderer;\n}\n\n/**\n * react-markdown's default `urlTransform` drops `data:`/`blob:` URLs, which\n * would strip pasted/attached images before sanitization runs. Permit those\n * two protocols for image `src` only (sanitization still gates the final\n * markup); everything else keeps react-markdown's safe defaults.\n */\nconst transformUrl: NonNullable<Options['urlTransform']> = (url, key, node) => {\n if (\n key === 'src' &&\n node.tagName === 'img' &&\n (/^data:image\\//i.test(url) || /^blob:/i.test(url))\n ) {\n return url;\n }\n return defaultUrlTransform(url);\n};\n\ninterface MarkdownContentProps {\n text: string;\n messageId: string;\n streaming: boolean;\n remarkPlugins: Options['remarkPlugins'];\n rehypePlugins: Options['rehypePlugins'];\n components: Components;\n}\n\nconst MarkdownContent = React.memo(function MarkdownContent({\n text,\n messageId,\n streaming,\n remarkPlugins,\n rehypePlugins,\n components,\n}: MarkdownContentProps) {\n return (\n <TextRenderContext.Provider value={{ messageId, streaming }}>\n <Markdown\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n urlTransform={transformUrl}\n components={components}\n >\n {text}\n </Markdown>\n </TextRenderContext.Provider>\n );\n});\n","/**\n * SuperChat — shared internal building blocks.\n *\n * Pure helpers + presentational pieces used by the three public components\n * ({@link SuperChat}, {@link SuperChatConversations}, {@link SuperChatInbox}).\n * Not part of the public API — import the components from `index.ts` instead.\n */\n\nimport * as React from 'react';\nimport { cva } from 'class-variance-authority';\nimport {\n Check as CheckIcon,\n Clipboard as ClipboardIcon,\n Ellipsis as EllipsisIcon,\n Pencil as PencilIcon,\n} from 'lucide-react';\nimport { cn } from '../../utils/cn';\nimport { Avatar } from '../Avatar';\nimport { Badge } from '../Badge';\nimport { Dropdown, DropdownItem, DropdownSubmenu } from '../Dropdown';\nimport { MCPToolCallDisplay } from '../AI/MCPToolCall';\nimport { ChatBubble, AITypingIndicator } from '../AI/AIMessage';\nimport { SparklesIcon } from '../AI/icons';\nimport type {\n AIRenderTextContent,\n AttachmentKind,\n ComposerAttachment,\n Participant,\n SuperChatConversation,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatMessage,\n SuperChatRef,\n} from './types';\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nexport function formatTime(time: Date | string): string {\n return new Date(time).toLocaleTimeString(undefined, {\n hour: 'numeric',\n minute: '2-digit',\n });\n}\n\nexport function byTime(a: SuperChatMessage, b: SuperChatMessage): number {\n return new Date(a.time).getTime() - new Date(b.time).getTime();\n}\n\nexport function lastActivityOf(c: SuperChatConversation): number {\n if (c.lastActivity) return new Date(c.lastActivity).getTime();\n const last = lastMessageByTime(c.thread);\n return last ? new Date(last.time).getTime() : 0;\n}\n\n/** Compute mentioned participant ids from `@Name` tokens in the draft. */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function detectMentions(\n text: string,\n participants: Participant[]\n): string[] {\n const ids: string[] = [];\n for (const p of participants) {\n if (p.kind === 'system') continue;\n const token = '@' + p.name.split(' ')[0];\n // Match a whole mention token only: the `@` must not be preceded by a word\n // character or another `@`, and the token must not be followed by a word\n // character (so `@Triage` does not match `@TriageAgent`).\n const pattern = new RegExp(\n `(?<![\\\\w@])${escapeRegExp(token)}(?![\\\\w])`,\n 'i'\n );\n if (pattern.test(text)) ids.push(p.id);\n }\n return ids;\n}\n\nexport function lastMessageByTime(\n thread: SuperChatMessage[]\n): SuperChatMessage | undefined {\n let latest: SuperChatMessage | undefined;\n let latestTime = -Infinity;\n for (const message of thread) {\n const t = new Date(message.time).getTime();\n if (t >= latestTime) {\n latest = message;\n latestTime = t;\n }\n }\n return latest;\n}\n\nfunction parseHexColor(value: string): [number, number, number] | null {\n const hex = value.trim();\n if (!/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex)) return null;\n const normalized =\n hex.length === 4\n ? '#' + [...hex.slice(1)].map((char) => char + char).join('')\n : hex;\n return [1, 3, 5].map((start) =>\n parseInt(normalized.slice(start, start + 2), 16)\n ) as [number, number, number];\n}\n\nfunction relativeLuminanceChannel(channel: number): number {\n const normalized = channel / 255;\n return normalized <= 0.03928\n ? normalized / 12.92\n : ((normalized + 0.055) / 1.055) ** 2.4;\n}\n\nfunction relativeLuminance(value: string): number | null {\n const rgb = parseHexColor(value);\n if (!rgb) return null;\n const [red, green, blue] = rgb;\n return (\n 0.2126 * relativeLuminanceChannel(red) +\n 0.7152 * relativeLuminanceChannel(green) +\n 0.0722 * relativeLuminanceChannel(blue)\n );\n}\n\nfunction contrastRatio(foreground: string, background: string): number | null {\n const foregroundLuminance = relativeLuminance(foreground);\n const backgroundLuminance = relativeLuminance(background);\n if (foregroundLuminance === null || backgroundLuminance === null) return null;\n const lighter = Math.max(foregroundLuminance, backgroundLuminance);\n const darker = Math.min(foregroundLuminance, backgroundLuminance);\n return (lighter + 0.05) / (darker + 0.05);\n}\n\nfunction minimumContrastRatio(\n value: string,\n backgrounds: string[]\n): number | null {\n const contrasts = backgrounds\n .map((background) => contrastRatio(value, background))\n .filter((contrast): contrast is number => contrast !== null);\n if (contrasts.length !== backgrounds.length) return null;\n return Math.min(...contrasts);\n}\n\nfunction accessibleAccentTextColor(value?: string): string | undefined {\n if (!value) return undefined;\n const contrast = minimumContrastRatio(value, ['#f5f5f5', '#262626']);\n if (contrast === null) return value;\n return contrast < 4.5 ? undefined : value;\n}\n\n// ============================================================================\n// Avatar\n// ============================================================================\n\nexport function ParticipantAvatar({\n participant,\n}: {\n participant?: Participant;\n}) {\n const isAgent = participant?.kind === 'agent';\n const backgroundColor =\n participant?.color ??\n (isAgent ? 'var(--mieweb-primary-700, #1f2937)' : '#64748b');\n return (\n <Avatar\n size=\"xs\"\n src={participant?.avatar}\n alt=\"\"\n name={participant?.name ?? '?'}\n fallback={isAgent ? <SparklesIcon size=\"sm\" /> : undefined}\n // Per-participant color (or agent/default) disambiguates concurrent\n // speakers; overrides Avatar's default primary background.\n style={{ backgroundColor }}\n aria-hidden=\"true\"\n className=\"shrink-0\"\n />\n );\n}\n\n// ============================================================================\n// Reference chip (chat-component `ref` thread items)\n// ============================================================================\n\nexport function ReferenceChip({\n reference,\n linkBuilder,\n onReferenceClick,\n}: {\n reference: SuperChatRef;\n linkBuilder?: SuperChatLinkBuilder;\n onReferenceClick?: (ref: SuperChatRef) => void;\n}) {\n const href = linkBuilder?.(reference);\n const content = (\n <>\n <Badge\n variant=\"default\"\n size=\"sm\"\n className=\"rounded px-1.5 text-[10px] font-semibold tracking-wide uppercase\"\n >\n {reference.refType}\n </Badge>\n <span className=\"truncate\">{reference.title}</span>\n </>\n );\n const className =\n 'inline-flex max-w-full items-center gap-2 rounded-lg border border-neutral-200 bg-white px-3 py-1.5 text-sm text-neutral-700 hover:border-primary-300 dark:border-neutral-700 dark:bg-neutral-800 dark:text-neutral-200';\n if (href) {\n return (\n <a\n href={href}\n className={className}\n onClick={() => onReferenceClick?.(reference)}\n >\n {content}\n </a>\n );\n }\n return (\n <button\n type=\"button\"\n className={className}\n onClick={() => onReferenceClick?.(reference)}\n >\n {content}\n </button>\n );\n}\n\n// ============================================================================\n// Message row\n// ============================================================================\n\n/**\n * Supported attachment categories: their `<input accept>` token and a MIME\n * matcher used to filter pastes and file-picker selections.\n */\nconst ATTACHMENT_KIND_CONFIG: Record<\n AttachmentKind,\n { accept: string; match: (type: string) => boolean }\n> = {\n image: { accept: 'image/*', match: (t) => t.startsWith('image/') },\n video: { accept: 'video/*', match: (t) => t.startsWith('video/') },\n audio: { accept: 'audio/*', match: (t) => t.startsWith('audio/') },\n pdf: { accept: 'application/pdf', match: (t) => t === 'application/pdf' },\n};\n\nconst DEFAULT_ACCEPTED_FILE_TYPES: AttachmentKind[] = [\n 'image',\n 'video',\n 'audio',\n 'pdf',\n];\n\n/**\n * Map SuperChat's high-level {@link AttachmentKind} categories to the\n * `<input accept>` tokens consumed by the shared `MessageComposer`.\n */\nexport function acceptTokensFor(\n kinds: AttachmentKind[] = DEFAULT_ACCEPTED_FILE_TYPES\n): string[] {\n const source = kinds.length > 0 ? kinds : DEFAULT_ACCEPTED_FILE_TYPES;\n return Array.from(\n new Set(source.map((k) => ATTACHMENT_KIND_CONFIG[k].accept))\n );\n}\n\n/**\n * Read the `File` objects emitted by the shared `MessageComposer` into the\n * base64 `data:` URL {@link ComposerAttachment}s SuperChat hosts expect.\n */\nexport function filesToComposerAttachments(\n files: File[]\n): Promise<ComposerAttachment[]> {\n return Promise.all(\n files.map(\n (file, i) =>\n new Promise<ComposerAttachment>((resolve, reject) => {\n const reader = new window.FileReader();\n reader.onload = () => {\n const dataUrl =\n typeof reader.result === 'string' ? reader.result : '';\n resolve({\n id: `att-${Date.now()}-${i}`,\n name: file.name || `attachment-${i}`,\n type: file.type || 'application/octet-stream',\n dataUrl,\n });\n };\n reader.onerror = () => reject(reader.error);\n reader.readAsDataURL(file);\n })\n )\n );\n}\n\n// ============================================================================\n// Message actions (footer bar + sticky overflow menu)\n// ============================================================================\n\n/**\n * Reveal-on-hover/focus for message action affordances. Hover doesn't exist on\n * touch devices, so coarse pointers always show the actions.\n */\nconst actionRevealClass =\n 'opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100 [@media(pointer:coarse)]:opacity-100';\n\nconst actionButtonClass =\n 'rounded p-1 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-200';\n\ninterface MessageActionItem {\n id: string;\n label: string;\n /** Secondary line shown under the label in the overflow menu. */\n description?: string;\n onSelect: () => void;\n}\n\n/**\n * One per-message action, rendered twice from the same definition: as an icon\n * button in the footer bar and as an item in the sticky overflow (⋯) menu.\n */\ninterface MessageAction {\n id: string;\n /** Accessible name (footer button) and menu label. */\n label: string;\n icon: React.ReactNode;\n /** Footer-button tooltip — e.g. to hint modifier behavior. Defaults to `label`. */\n title?: string;\n /** Default behavior (footer click / top-level menu item). */\n onSelect: () => void;\n /** Explicit variants, rendered as a flyout submenu in the overflow menu. */\n submenu?: { label: string; items: MessageActionItem[] };\n}\n\ninterface UseMessageCopyOptions {\n /** Markdown source for this message (plain-text / Markdown copy). */\n markdown: string;\n /** Read the rendered bubble HTML at copy time (rich-text copy). */\n getHtml: () => string;\n /** Read the rendered bubble plain text at copy time. */\n getText: () => string;\n /** One-click format for the default copy action. */\n defaultFormat: SuperChatCopyFormat;\n}\n\n/**\n * Per-message clipboard writes. The **rich** format writes *both* a rich-text\n * (`text/html`) and a Markdown (`text/plain`) representation in a single\n * clipboard write, so the paste target decides: rich editors get formatting,\n * plain editors get Markdown. Explicit \"as Markdown\" / \"as plain text\"\n * variants are also exposed, and `copyDefault` honors the host-configured\n * {@link SuperChatCopyFormat}.\n */\nfunction useMessageCopy({\n markdown,\n getHtml,\n getText,\n defaultFormat,\n}: UseMessageCopyOptions) {\n const [copied, setCopied] = React.useState(false);\n const copiedTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined\n );\n\n React.useEffect(() => () => window.clearTimeout(copiedTimer.current), []);\n\n const flash = () => {\n setCopied(true);\n window.clearTimeout(copiedTimer.current);\n copiedTimer.current = setTimeout(() => setCopied(false), 1200);\n };\n\n const writeText = async (value: string) => {\n if (!navigator.clipboard?.writeText) {\n // Insecure context / unsupported browser: reject so the caller doesn't\n // flash a misleading \"Copied\" success.\n throw new Error('Clipboard API unavailable');\n }\n await navigator.clipboard.writeText(value);\n };\n\n const writeBoth = async () => {\n const html = getHtml();\n const text = markdown || getText();\n try {\n if (\n typeof window !== 'undefined' &&\n 'ClipboardItem' in window &&\n navigator.clipboard?.write\n ) {\n await navigator.clipboard.write([\n new window.ClipboardItem({\n 'text/html': new Blob([html], { type: 'text/html' }),\n 'text/plain': new Blob([text], { type: 'text/plain' }),\n }),\n ]);\n } else {\n await writeText(text);\n }\n } catch {\n await writeText(text);\n }\n };\n\n const run = (fn: () => Promise<void>) => {\n // Only flash \"Copied\" when the write actually succeeds; swallow failures\n // (insecure context / denied permission) instead of leaking an unhandled\n // rejection or showing a false success.\n void fn().then(flash, () => {});\n };\n\n const copyRich = () => run(writeBoth);\n const copyMarkdown = () => run(() => writeText(markdown || getText()));\n const copyPlain = () => run(() => writeText(getText()));\n const copyDefault =\n defaultFormat === 'markdown'\n ? copyMarkdown\n : defaultFormat === 'plain'\n ? copyPlain\n : copyRich;\n\n return { copied, copyDefault, copyRich, copyMarkdown, copyPlain };\n}\n\ninterface MessageActionsBarProps {\n actions: MessageAction[];\n isSelf: boolean;\n}\n\n/** A submenu item as a Dropdown row, with an optional secondary line. */\nfunction ActionMenuItem({\n item,\n onSelect,\n}: {\n item: MessageActionItem;\n onSelect: (fn: () => void) => void;\n}) {\n return (\n <DropdownItem onClick={() => onSelect(item.onSelect)}>\n {item.description ? (\n <span className=\"flex flex-col items-start\">\n <span>{item.label}</span>\n <span className=\"text-[10px] font-normal text-neutral-400\">\n {item.description}\n </span>\n </span>\n ) : (\n item.label\n )}\n </DropdownItem>\n );\n}\n\n/**\n * One footer-bar affordance. Plain actions run their default on click; actions\n * with variants (e.g. copy formats) open a small menu of those variants, like\n * the original per-message copy menu. Ctrl/Cmd-click skips the menu and runs\n * the action's default (e.g. the host-configured {@link SuperChatCopyFormat}).\n */\nfunction FooterActionButton({\n action,\n isSelf,\n}: {\n action: MessageAction;\n isSelf: boolean;\n}) {\n const [open, setOpen] = React.useState(false);\n\n // Capture-phase so it runs before the Dropdown's trigger onClick: a\n // modifier click fires the default action instead of opening the menu.\n const onClickCapture = action.submenu\n ? (e: React.MouseEvent) => {\n if (e.metaKey || e.ctrlKey) {\n e.preventDefault();\n e.stopPropagation();\n action.onSelect();\n }\n }\n : undefined;\n\n const button = (\n <button\n type=\"button\"\n data-slot={`superchat-action-${action.id}`}\n aria-label={action.label}\n title={action.title ?? action.label}\n onClick={action.submenu ? undefined : action.onSelect}\n onClickCapture={onClickCapture}\n className={actionButtonClass}\n >\n {action.icon}\n </button>\n );\n\n if (!action.submenu) return button;\n\n return (\n <Dropdown\n open={open}\n onOpenChange={setOpen}\n placement={isSelf ? 'top-end' : 'top-start'}\n trigger={button}\n >\n {action.submenu.items.map((item) => (\n <ActionMenuItem\n key={item.id}\n item={item}\n onSelect={(fn) => {\n setOpen(false);\n fn();\n }}\n />\n ))}\n </Dropdown>\n );\n}\n\n/**\n * The hover-revealed row of action icon buttons under a message bubble. Each\n * button runs its action's default behavior; explicit variants live in the\n * sticky overflow menu ({@link MessageOverflowMenu}).\n */\nconst MessageActionsBar = React.forwardRef<\n HTMLDivElement,\n MessageActionsBarProps\n>(function MessageActionsBar({ actions, isSelf }, ref) {\n return (\n <div\n ref={ref}\n data-slot=\"superchat-message-actions\"\n className={cn(\n 'flex items-center gap-0.5',\n isSelf && 'justify-end',\n actionRevealClass\n )}\n >\n {actions.map((action) => (\n <FooterActionButton key={action.id} action={action} isSelf={isSelf} />\n ))}\n </div>\n );\n});\n\ninterface MessageOverflowMenuProps {\n /** Aligns the popover to the outer margin (right for self, left otherwise). */\n isSelf: boolean;\n actions: MessageAction[];\n /**\n * Whether the footer action bar is currently in view. While it is, the\n * overflow trigger hides (the footer already offers the actions); it\n * reappears — floating — once the footer scrolls out of view mid-message.\n */\n footerVisible: boolean;\n}\n\n/**\n * The sticky overflow (⋯) control beside the bubble. On long messages it\n * follows the scroll (sticky within the thread) so actions stay reachable, and\n * hands off to the footer bar once the message end scrolls into view.\n */\nfunction MessageOverflowMenu({\n isSelf,\n actions,\n footerVisible,\n}: MessageOverflowMenuProps) {\n const [open, setOpen] = React.useState(false);\n\n const select = (fn: () => void) => {\n setOpen(false);\n fn();\n };\n\n return (\n <div\n // Self-align to the bottom of the (possibly tall) message row and stick\n // to the viewport bottom: on long messages the control follows the\n // scroll and settles at the message's end once it is fully in view.\n // Raise the whole (sticky) stacking context above the sibling bubble\n // while open so the menu sits over rich content like tables.\n className={cn(\n 'sticky bottom-2 shrink-0 self-end transition-opacity',\n // Rich content (e.g. NITRO tables) layers internals up to z-50, so the\n // open menu's stacking context must clear that.\n open ? 'z-[60]' : 'z-10',\n // Hand off to the footer bar when it's visible. `invisible` (not\n // just opacity) drops the hidden button from the tab order so\n // keyboard users can't focus an unseen control.\n footerVisible && !open && 'pointer-events-none invisible opacity-0'\n )}\n >\n <Dropdown\n open={open}\n onOpenChange={setOpen}\n placement={isSelf ? 'top-end' : 'top-start'}\n trigger={\n <button\n type=\"button\"\n data-slot=\"superchat-overflow-button\"\n aria-label=\"Message actions\"\n className={cn(actionButtonClass, actionRevealClass)}\n >\n <EllipsisIcon size={14} aria-hidden=\"true\" />\n </button>\n }\n >\n {actions.map((action) =>\n action.submenu ? (\n // Actions with variants collapse to just their submenu — a\n // top-level default item would duplicate the flyout's options.\n <DropdownSubmenu key={action.id} label={action.submenu.label}>\n {action.submenu.items.map((item) => (\n <ActionMenuItem key={item.id} item={item} onSelect={select} />\n ))}\n </DropdownSubmenu>\n ) : (\n <DropdownItem\n key={action.id}\n onClick={() => select(action.onSelect)}\n >\n {action.label}\n </DropdownItem>\n )\n )}\n </Dropdown>\n </div>\n );\n}\n\ninterface MessageRowProps {\n message: SuperChatMessage;\n participant?: Participant;\n isSelf: boolean;\n renderText: AIRenderTextContent;\n linkBuilder?: SuperChatLinkBuilder;\n onReferenceClick?: (ref: SuperChatRef) => void;\n /** Whether self-authored text messages expose an inline \"Edit\" affordance. */\n editable?: boolean;\n /** Save handler for an inline message edit (bound to this message's id). */\n onMessageEdited?: (messageId: string, text: string) => void;\n /** Format for the default copy action — Ctrl/Cmd-click on the footer copy\n * button (defaults to `'rich'`). */\n defaultCopyFormat?: SuperChatCopyFormat;\n}\n\n/**\n * A single thread row (message / system notice / reference chip).\n *\n * Wrapped in {@link React.memo}: in long threads the parent re-renders on every\n * new message, but each existing row's props are stable (the host owns the\n * message objects), so memoization skips re-rendering — and, crucially,\n * re-running the Markdown pipeline — for the hundreds of rows that did not\n * change. Keep the props referentially stable from the host for this to help.\n */\nexport const MessageRow = React.memo(function MessageRow({\n message,\n participant,\n isSelf,\n renderText,\n linkBuilder,\n onReferenceClick,\n editable,\n onMessageEdited,\n defaultCopyFormat = 'rich',\n}: MessageRowProps) {\n const streaming = message.status === 'streaming';\n const hasBody = !!message.text || (message.content?.length ?? 0) > 0;\n const [isEditing, setIsEditing] = React.useState(false);\n const [draft, setDraft] = React.useState(message.text ?? '');\n const editRef = React.useRef<HTMLTextAreaElement>(null);\n // The rendered bubble content, read at copy time for the rich-text payload.\n const bubbleRef = React.useRef<HTMLDivElement>(null);\n // Grow the editor to fit its content (accounts for wrapped lines, not just\n // explicit newlines), clamped by the textarea's CSS max-height.\n const autosize = React.useCallback(() => {\n const el = editRef.current;\n if (!el) return;\n el.style.height = 'auto';\n el.style.height = `${el.scrollHeight}px`;\n }, []);\n // Move focus into the editor (caret at end) and size it when editing starts.\n React.useEffect(() => {\n if (!isEditing) return;\n const el = editRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(el.value.length, el.value.length);\n autosize();\n }, [isEditing, autosize]);\n\n // --- Message actions (copy / edit) ---------------------------------------\n // Computed before the early returns below so the hooks run unconditionally\n // (system/ref rows simply never render the action surfaces).\n\n // Inline editing applies only to the local user's own plain-text messages\n // (rich content blocks / streaming messages are not inline-editable).\n const canEdit =\n !!editable &&\n isSelf &&\n !streaming &&\n typeof message.text === 'string' &&\n !message.content?.length;\n\n // The Markdown source for copying: prefer the raw `text`, otherwise assemble\n // it from the message's text/code content blocks.\n const markdownSource =\n typeof message.text === 'string' && message.text\n ? message.text\n : (message.content\n ?.map((block) => {\n if (block.type === 'code' && block.text) {\n return `\\`\\`\\`${block.language ?? ''}\\n${block.text}\\n\\`\\`\\``;\n }\n if (\n (block.type === 'text' || block.type === 'thinking') &&\n block.text\n ) {\n return block.text;\n }\n return '';\n })\n .filter(Boolean)\n .join('\\n\\n') ?? '');\n\n // A copy affordance appears on every message that has a body (not while it\n // is being edited).\n const canCopy =\n !isEditing &&\n (!!message.content?.length ||\n (typeof message.text === 'string' && message.text.length > 0));\n\n const hasActions = canCopy || (canEdit && !isEditing);\n\n const copy = useMessageCopy({\n markdown: markdownSource,\n getHtml: () => bubbleRef.current?.innerHTML ?? '',\n getText: () => bubbleRef.current?.textContent ?? '',\n defaultFormat: defaultCopyFormat,\n });\n\n // Hand-off between the footer action bar and the sticky overflow (⋯): the\n // overflow only shows while the footer bar is scrolled out of view.\n // Clipping by the scrollable thread counts as \"not intersecting\", so the\n // default viewport root is sufficient. Starts optimistic (footer assumed\n // visible) so rows freshly mounted by the virtualized thread don't flash\n // the overflow before the observer's first callback.\n const actionsBarRef = React.useRef<HTMLDivElement>(null);\n const [footerVisible, setFooterVisible] = React.useState(true);\n React.useEffect(() => {\n const el = actionsBarRef.current;\n if (!el || typeof globalThis.IntersectionObserver === 'undefined') return;\n const observer = new globalThis.IntersectionObserver(([entry]) => {\n setFooterVisible(entry?.isIntersecting ?? false);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, [hasActions]);\n\n if (message.type === 'system') {\n return (\n <div\n data-slot=\"superchat-system-message\"\n role=\"status\"\n className=\"my-1 text-center text-xs text-neutral-500 dark:text-neutral-400\"\n >\n {message.text}\n </div>\n );\n }\n\n if (message.type === 'ref' && message.ref) {\n return (\n <div\n data-slot=\"superchat-reference\"\n className={cn('flex', isSelf && 'justify-end')}\n >\n <ReferenceChip\n reference={message.ref}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n />\n </div>\n );\n }\n\n const accent = participant?.color;\n const accentTextColor = accessibleAccentTextColor(accent);\n const authorName = participant?.name ?? 'Unknown';\n\n const startEdit = () => {\n setDraft(message.text ?? '');\n setIsEditing(true);\n };\n const cancelEdit = () => setIsEditing(false);\n const saveEdit = () => {\n const next = draft.trim();\n if (next && next !== message.text) onMessageEdited?.(message.id, next);\n setIsEditing(false);\n };\n\n // Paste an image into the editor: splice its Markdown at the caret so it\n // becomes part of the message source (the bubble renders Markdown).\n const handleEditPaste = (e: React.ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(e.clipboardData.items)\n .filter((item) => item.kind === 'file' && item.type.startsWith('image/'))\n .map((item) => item.getAsFile())\n .filter((f): f is File => f !== null);\n if (files.length === 0) return;\n e.preventDefault();\n const el = e.currentTarget;\n const start = el.selectionStart ?? draft.length;\n const end = el.selectionEnd ?? draft.length;\n Promise.all(\n files.map(\n (file, i) =>\n new Promise<string>((resolve) => {\n const reader = new window.FileReader();\n reader.onload = () => {\n const dataUrl =\n typeof reader.result === 'string' ? reader.result : '';\n const name = file.name || `pasted-image-${i + 1}.png`;\n resolve(dataUrl ? `![${name}](${dataUrl})` : '');\n };\n reader.readAsDataURL(file);\n })\n )\n ).then((snippets) => {\n const insert = snippets.filter(Boolean).join('\\n');\n if (!insert) return;\n // Insert via `execCommand('insertText')` so the browser records it on its\n // native undo stack (Cmd/Ctrl+Z works) and fires a normal input event\n // that flows back through `onChange`. Fall back to a controlled-state\n // splice if the (deprecated) command is unavailable.\n el.focus();\n el.setSelectionRange(start, end);\n const text = `${insert}\\n`;\n const inserted =\n typeof document !== 'undefined' &&\n typeof document.execCommand === 'function' &&\n document.execCommand('insertText', false, text);\n if (!inserted) {\n setDraft((prev) => `${prev.slice(0, start)}${text}${prev.slice(end)}`);\n }\n requestAnimationFrame(autosize);\n });\n };\n\n // The same action definitions power both surfaces: the footer icon bar and\n // the sticky overflow menu.\n const actions: MessageAction[] = [\n ...(canCopy\n ? [\n {\n id: 'copy',\n label: 'Copy message',\n title: 'Copy message (\\u2318/Ctrl-click: default format)',\n icon: copy.copied ? (\n <CheckIcon size={14} aria-hidden=\"true\" />\n ) : (\n <ClipboardIcon size={14} aria-hidden=\"true\" />\n ),\n onSelect: copy.copyDefault,\n submenu: {\n label: 'Copy as',\n items: [\n {\n id: 'copy-rich',\n label: 'Copy as rich text',\n description: 'Rich text + Markdown',\n onSelect: copy.copyRich,\n },\n {\n id: 'copy-markdown',\n label: 'Copy as Markdown',\n onSelect: copy.copyMarkdown,\n },\n {\n id: 'copy-plain',\n label: 'Copy as plain text',\n onSelect: copy.copyPlain,\n },\n ],\n },\n } satisfies MessageAction,\n ]\n : []),\n ...(canEdit && !isEditing\n ? [\n {\n id: 'edit',\n label: 'Edit message',\n icon: <PencilIcon size={14} aria-hidden=\"true\" />,\n onSelect: startEdit,\n } satisfies MessageAction,\n ]\n : []),\n ];\n\n return (\n <div\n data-slot=\"superchat-message\"\n role=\"article\"\n aria-label={`${authorName}, ${formatTime(message.time)}`}\n className={cn(\n 'group flex gap-2',\n isSelf ? 'flex-row-reverse' : 'flex-row'\n )}\n >\n <ParticipantAvatar participant={participant} />\n <div className={cn('flex min-w-0 flex-col gap-1', isSelf && 'items-end')}>\n <div\n data-slot=\"superchat-message-meta\"\n className=\"flex items-baseline gap-2\"\n >\n <span\n className=\"text-xs font-medium\"\n style={accentTextColor ? { color: accentTextColor } : undefined}\n >\n {authorName}\n </span>\n {participant?.role && (\n <span className=\"text-[10px] text-neutral-500 dark:text-neutral-400\">\n {participant.role}\n </span>\n )}\n <span className=\"text-[10px] text-neutral-500 dark:text-neutral-400\">\n {formatTime(message.time)}\n </span>\n {message.editedAt && (\n <span\n data-slot=\"superchat-edited-indicator\"\n className=\"text-[10px] text-neutral-500 dark:text-neutral-400\"\n title={`Edited ${formatTime(message.editedAt)}`}\n >\n (edited)\n </span>\n )}\n </div>\n\n <div\n className={cn(\n 'flex items-center gap-1',\n isSelf ? 'flex-row-reverse' : 'flex-row'\n )}\n >\n {hasActions && (\n <MessageOverflowMenu\n isSelf={isSelf}\n actions={actions}\n footerVisible={footerVisible}\n />\n )}\n <ChatBubble\n ref={bubbleRef}\n data-slot=\"superchat-bubble\"\n variant={isSelf ? 'user' : 'assistant'}\n hasError={message.status === 'error'}\n className=\"text-sm has-[[data-slot=superchat-nitro-table]]:w-full has-[[data-slot=superchat-nitro-table]]:max-w-full\"\n >\n {isEditing ? (\n <div\n data-slot=\"superchat-message-editor\"\n className=\"flex w-80 max-w-full flex-col gap-2\"\n >\n <textarea\n value={draft}\n ref={editRef}\n rows={2}\n onChange={(e) => {\n setDraft(e.target.value);\n autosize();\n }}\n onPaste={handleEditPaste}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n saveEdit();\n } else if (e.key === 'Escape') {\n e.preventDefault();\n cancelEdit();\n }\n }}\n aria-label=\"Edit message\"\n className=\"focus:ring-primary-500 max-h-60 min-h-16 w-full resize-none rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 focus:ring-1 focus:outline-none dark:border-neutral-600 dark:bg-neutral-900 dark:text-white\"\n />\n <div className=\"flex justify-end gap-2\">\n <button\n type=\"button\"\n onClick={cancelEdit}\n className=\"rounded-md px-2.5 py-1 text-xs font-medium text-neutral-200 hover:bg-white/10\"\n >\n Cancel\n </button>\n <button\n type=\"button\"\n onClick={saveEdit}\n disabled={!draft.trim() || draft.trim() === message.text}\n className=\"rounded-md bg-white px-2.5 py-1 text-xs font-medium text-neutral-900 hover:bg-neutral-100 disabled:opacity-40\"\n >\n Save\n </button>\n </div>\n </div>\n ) : (\n <>\n {/* Rich content blocks (tool calls etc.) reused from the AI module. */}\n {message.content?.map((block, i) => {\n if (block.type === 'tool_use' && block.toolCall) {\n return (\n <MCPToolCallDisplay key={i} toolCall={block.toolCall} />\n );\n }\n if (\n (block.type === 'text' || block.type === 'thinking') &&\n block.text\n ) {\n return (\n <div\n key={i}\n className=\"prose prose-sm dark:prose-invert max-w-none **:wrap-break-word\"\n >\n {renderText(block.text, {\n messageId: message.id,\n streaming,\n role:\n participant?.kind === 'human'\n ? 'user'\n : 'assistant',\n })}\n </div>\n );\n }\n if (block.type === 'code' && block.text) {\n const fenced = `\\`\\`\\`${block.language ?? ''}\\n${block.text}\\n\\`\\`\\``;\n return (\n <div\n key={i}\n className=\"prose prose-sm dark:prose-invert max-w-none **:wrap-break-word\"\n >\n {renderText(fenced, {\n messageId: message.id,\n streaming,\n role:\n participant?.kind === 'human'\n ? 'user'\n : 'assistant',\n })}\n </div>\n );\n }\n return null;\n })}\n\n {/* Plain `text` body (the common case). */}\n {message.text && (\n <div className=\"prose prose-sm dark:prose-invert max-w-none **:wrap-break-word\">\n {renderText(message.text, {\n messageId: message.id,\n streaming,\n role:\n participant?.kind === 'human' ? 'user' : 'assistant',\n })}\n </div>\n )}\n\n {/* Animated typing indicator while a reply streams in with no\n body yet — matches the AI chat's streaming affordance. */}\n {streaming && !hasBody && (\n <div className=\"flex items-center justify-center\">\n <AITypingIndicator />\n </div>\n )}\n </>\n )}\n </ChatBubble>\n </div>\n {hasActions && (\n <MessageActionsBar\n ref={actionsBarRef}\n actions={actions}\n isSelf={isSelf}\n />\n )}\n </div>\n </div>\n );\n});\n\n// ============================================================================\n// Sidebar item style\n// ============================================================================\n\nexport const sidebarItem = cva(\n 'flex w-full items-center gap-2 rounded-lg px-3 py-2 text-start text-sm transition-colors',\n {\n variants: {\n active: {\n true: 'bg-primary-100 text-primary-900 dark:bg-primary-900/40 dark:text-primary-100',\n false:\n 'text-neutral-700 hover:bg-neutral-100 dark:text-neutral-200 dark:hover:bg-neutral-800',\n },\n },\n defaultVariants: { active: false },\n }\n);\n","/**\n * VirtualThread — windowed (virtualized) message list for {@link SuperChat}.\n *\n * Renders only the rows near the viewport using `@tanstack/react-virtual` with\n * dynamic measurement, so a thread of thousands of messages mounts ~20-30 DOM\n * subtrees instead of all of them. This keeps first render, memory, and the\n * Markdown parse cost bounded by what is on screen rather than by the total\n * history length.\n *\n * Opt-in via the `virtualized` prop on `SuperChat`/`SuperChatInbox`. The\n * non-virtualized path remains the default for short threads, where the extra\n * absolute-positioning machinery is unnecessary.\n */\n\nimport * as React from 'react';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport { MessageRow } from './parts';\nimport type {\n AIRenderTextContent,\n Participant,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatMessage,\n SuperChatRef,\n} from './types';\n\nexport interface VirtualThreadProps {\n /** The messages to render, already sorted in display order. */\n items: SuperChatMessage[];\n /** Lookup from participant id to participant. */\n participantById: Map<string, Participant>;\n /** The local user id (drives self-alignment). */\n currentParticipantId?: string;\n /** Text renderer (Markdown pipeline). */\n renderText: AIRenderTextContent;\n /** Build hrefs for `ref` items. */\n linkBuilder?: SuperChatLinkBuilder;\n /** Fired when a reference chip is activated. */\n onReferenceClick?: (ref: SuperChatRef) => void;\n /** Whether self-authored text messages expose an inline \"Edit\" affordance. */\n editable?: boolean;\n /** Save handler for an inline message edit (bound to the message's id). */\n onMessageEdited?: (messageId: string, text: string) => void;\n /** Format for a message's default copy action (Ctrl/Cmd-click on copy). */\n defaultCopyFormat?: SuperChatCopyFormat;\n /**\n * Thread ordering. `'asc'` anchors new messages to the bottom; `'desc'`\n * anchors them to the top (feed style).\n */\n order: 'asc' | 'desc';\n /** Conversation id — changing it re-anchors scroll to the newest message. */\n conversationId: string;\n /** Props forwarded to the scroll container (role/aria/tabIndex/className). */\n containerProps: React.HTMLAttributes<HTMLDivElement> & {\n 'data-slot'?: string;\n };\n}\n\nexport function VirtualThread({\n items,\n participantById,\n currentParticipantId,\n renderText,\n linkBuilder,\n onReferenceClick,\n editable,\n onMessageEdited,\n defaultCopyFormat,\n order,\n conversationId,\n containerProps,\n}: VirtualThreadProps) {\n const parentRef = React.useRef<HTMLDivElement>(null);\n\n const virtualizer = useVirtualizer({\n count: items.length,\n getScrollElement: () => parentRef.current,\n // Rough first guess; real heights are measured via measureElement.\n estimateSize: () => 88,\n overscan: 10,\n getItemKey: (index) => items[index]?.id ?? index,\n });\n\n // Anchor to the newest message: bottom for ascending order, top for\n // descending (feed-style) order. Runs on mount, when the conversation\n // changes, and when a message is appended.\n const count = items.length;\n React.useEffect(() => {\n if (count === 0) return;\n if (order === 'desc') {\n virtualizer.scrollToIndex(0, { align: 'start' });\n } else {\n virtualizer.scrollToIndex(count - 1, { align: 'end' });\n }\n // `virtualizer` is stable across renders for a given instance.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [count, conversationId, order]);\n\n const virtualItems = virtualizer.getVirtualItems();\n\n return (\n <div {...containerProps} ref={parentRef}>\n <div\n style={{\n height: virtualizer.getTotalSize(),\n position: 'relative',\n width: '100%',\n }}\n >\n {virtualItems.map((virtualRow) => {\n const message = items[virtualRow.index];\n if (!message) return null;\n return (\n <div\n key={virtualRow.key}\n data-index={virtualRow.index}\n ref={virtualizer.measureElement}\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n transform: `translateY(${virtualRow.start}px)`,\n }}\n >\n {/* Bottom padding stands in for the non-virtual `space-y-4` gap\n and is included in the measured height. */}\n <div className=\"pb-4\">\n <MessageRow\n message={message}\n participant={participantById.get(message.participantId)}\n isSelf={\n !!currentParticipantId &&\n message.participantId === currentParticipantId\n }\n renderText={renderText}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n editable={editable}\n onMessageEdited={onMessageEdited}\n defaultCopyFormat={defaultCopyFormat}\n />\n </div>\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n","/**\n * SuperChat — a single-conversation chat panel for `@mieweb/ui`.\n *\n * Renders one {@link SuperChatConversation}: header (title + participants +\n * optional close), a `role=\"log\"` message thread, and the compose box. Message\n * text renders through the pluggable Markdown pipeline\n * ({@link createMarkdownRenderer}); rich plugins (code/math/genui/…) are opt-in.\n *\n * For a conversation list use {@link SuperChatConversations}; for the combined\n * inbox (list + panel) use {@link SuperChatInbox}.\n */\n\nimport * as React from 'react';\nimport { cn } from '../../utils/cn';\nimport { CloseIcon } from '../AI/icons';\nimport { MessageComposer } from '../Messaging/MessageComposer';\nimport type { NewMessage } from '../Messaging/types';\nimport { createMarkdownRenderer } from './render/createMarkdownRenderer';\nimport {\n ParticipantAvatar,\n MessageRow,\n byTime,\n detectMentions,\n filesToComposerAttachments,\n acceptTokensFor,\n} from './parts';\nimport { VirtualThread } from './VirtualThread';\nimport type {\n AIRenderTextContent,\n AttachmentKind,\n ComposerAttachment,\n Participant,\n SuperChatConversation,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatRef,\n SuperChatRenderPlugin,\n} from './types';\n\n// ============================================================================\n// SuperChat (single-conversation panel)\n// ============================================================================\n\nexport interface SuperChatProps {\n /** The conversation to display (host-owned state). */\n conversation: SuperChatConversation;\n /** The participant id representing the local user (alignment + compose). */\n currentParticipantId?: string;\n /** Opt-in rich render plugins (code/math/genui/…). */\n renderPlugins?: SuperChatRenderPlugin[];\n /** Override the entire text renderer (advanced). */\n renderTextContent?: AIRenderTextContent;\n /** Treat content as trusted and skip sanitization (host-authored only). */\n trustedContent?: boolean;\n /** Disable the composer. */\n readOnly?: boolean;\n /**\n * File categories the composer accepts for paste and the paperclip picker.\n * Defaults to `['image', 'video', 'audio', 'pdf']`.\n */\n acceptedFileTypes?: AttachmentKind[];\n /**\n * Thread ordering.\n * - `'asc'` (default): oldest → newest, anchored to the bottom like a\n * classic messenger (auto-scrolls to the newest message).\n * - `'desc'`: newest → oldest, anchored to the top like a social feed\n * (auto-scrolls to the top when a new message arrives).\n */\n order?: 'asc' | 'desc';\n /**\n * Virtualize the message thread (windowed rendering). Only the rows near the\n * viewport are mounted, so very long threads (hundreds to thousands of\n * messages) stay responsive. Off by default — enable for long histories.\n */\n virtualized?: boolean;\n /** Build hrefs for `ref` thread items. */\n linkBuilder?: SuperChatLinkBuilder;\n /**\n * Format for a message's default copy action (Ctrl/Cmd-click on the footer\n * copy button). All formats stay reachable per message via the copy menus.\n * Defaults to `'rich'`.\n */\n defaultCopyFormat?: SuperChatCopyFormat;\n /** Additional class name. */\n className?: string;\n\n // --- callbacks (chat-component-compatible) ---\n onMessageSent?: (\n text: string,\n meta: {\n conversation: SuperChatConversation;\n mentions: string[];\n attachments: ComposerAttachment[];\n }\n ) => void;\n /**\n * Fired when the local user saves an edit to one of their own messages.\n * Providing this enables the inline \"Edit\" affordance on self-authored\n * messages (the host owns state, so apply the new `text` to the message and\n * typically stamp `editedAt`).\n */\n onMessageEdited?: (\n messageId: string,\n text: string,\n meta: { conversation: SuperChatConversation }\n ) => void;\n onConversationClosed?: (conversation: SuperChatConversation) => void;\n onReferenceClick?: (ref: SuperChatRef) => void;\n /**\n * Show a \"back\" affordance in the header (used by {@link SuperChatInbox} on\n * small screens to return from the chat panel to the conversation list).\n */\n onBack?: () => void;\n}\n\n/**\n * Single-conversation chat panel. See the module `MAINTAINERS.md` for the\n * participant model and render-plugin architecture.\n */\nexport function SuperChat({\n conversation,\n currentParticipantId,\n renderPlugins,\n renderTextContent,\n trustedContent,\n readOnly,\n acceptedFileTypes,\n order = 'asc',\n virtualized = false,\n linkBuilder,\n defaultCopyFormat,\n className,\n onMessageSent,\n onMessageEdited,\n onConversationClosed,\n onReferenceClick,\n onBack,\n}: SuperChatProps) {\n const headingId = React.useId();\n\n const renderText = React.useMemo<AIRenderTextContent>(\n () =>\n renderTextContent ??\n createMarkdownRenderer({\n plugins: renderPlugins,\n trusted: trustedContent,\n }),\n [renderTextContent, renderPlugins, trustedContent]\n );\n\n const threadRef = React.useRef<HTMLDivElement>(null);\n React.useEffect(() => {\n if (virtualized) return; // VirtualThread manages its own scroll anchoring.\n const el = threadRef.current;\n if (!el) return;\n // Anchor to the newest message: bottom for ascending order, top for\n // descending (feed-style) order.\n el.scrollTop = order === 'desc' ? 0 : el.scrollHeight;\n }, [conversation.thread.length, conversation.id, order, virtualized]);\n\n const participantById = React.useMemo(() => {\n const map = new Map<string, Participant>();\n conversation.participants.forEach((p) => map.set(p.id, p));\n return map;\n }, [conversation]);\n\n const orderedThread = React.useMemo(() => {\n const sorted = [...conversation.thread].sort(byTime);\n return order === 'desc' ? sorted.reverse() : sorted;\n }, [conversation, order]);\n\n // Stable edit handler so memoized rows don't re-render when the conversation\n // changes. Latest `onMessageEdited`/`conversation` are read from refs.\n const onMessageEditedRef = React.useRef(onMessageEdited);\n onMessageEditedRef.current = onMessageEdited;\n const conversationRef = React.useRef(conversation);\n conversationRef.current = conversation;\n const handleMessageEdited = React.useCallback(\n (messageId: string, text: string) => {\n onMessageEditedRef.current?.(messageId, text, {\n conversation: conversationRef.current,\n });\n },\n []\n );\n const editable = !readOnly && !!onMessageEdited;\n\n // Agents/humans addressable via `@` (exclude the system participant).\n const mentionOptions = React.useMemo(\n () =>\n conversation.participants\n .filter((p) => p.kind !== 'system')\n .map((p) => ({\n id: p.id,\n label: p.name,\n description: p.role,\n meta: p.kind,\n icon: <ParticipantAvatar participant={p} />,\n })),\n [conversation.participants]\n );\n\n const composerAccept = React.useMemo(\n () => acceptTokensFor(acceptedFileTypes),\n [acceptedFileTypes]\n );\n\n // Bridge the shared composer's `NewMessage` (File[] attachments) to\n // SuperChat's host callback (mentions + base64 `data:` URL attachments).\n const handleComposerSend = React.useCallback(\n async (message: NewMessage) => {\n const text = message.content;\n const mentions = detectMentions(text, conversation.participants);\n const attachments = await filesToComposerAttachments(\n message.attachments ?? []\n );\n onMessageSent?.(text, { conversation, mentions, attachments });\n },\n [conversation, onMessageSent]\n );\n\n return (\n <section\n data-slot=\"superchat\"\n role=\"group\"\n aria-labelledby={headingId}\n className={cn(\n 'flex min-w-0 flex-1 flex-col bg-white dark:bg-neutral-900',\n className\n )}\n >\n <header\n data-slot=\"superchat-header\"\n className=\"flex items-center justify-between gap-2 border-b border-neutral-200 p-3 dark:border-neutral-700\"\n >\n <div className=\"flex min-w-0 items-center gap-2\">\n {onBack && (\n <button\n type=\"button\"\n onClick={onBack}\n aria-label=\"Back to conversations\"\n className=\"-ms-1 shrink-0 rounded-md p-1 text-neutral-500 hover:bg-neutral-100 sm:hidden dark:text-neutral-300 dark:hover:bg-neutral-800\"\n >\n <svg\n viewBox=\"0 0 24 24\"\n width=\"20\"\n height=\"20\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"m15 18-6-6 6-6\" />\n </svg>\n </button>\n )}\n <div className=\"min-w-0\">\n <h2\n id={headingId}\n className=\"truncate text-sm font-semibold text-neutral-800 dark:text-neutral-100\"\n >\n {conversation.title}\n </h2>\n <div\n data-slot=\"superchat-participants\"\n role=\"group\"\n aria-label=\"Participants\"\n className=\"mt-0.5 flex items-center gap-1\"\n >\n {conversation.participants.slice(0, 6).map((p) => (\n <span key={p.id} role=\"img\" aria-label={p.name}>\n <ParticipantAvatar participant={p} />\n </span>\n ))}\n </div>\n </div>\n </div>\n {onConversationClosed && (\n <button\n type=\"button\"\n onClick={() => onConversationClosed(conversation)}\n aria-label=\"Close conversation\"\n className=\"rounded-md p-1 text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800\"\n >\n <CloseIcon />\n </button>\n )}\n </header>\n\n {virtualized ? (\n <VirtualThread\n items={orderedThread}\n participantById={participantById}\n currentParticipantId={currentParticipantId}\n renderText={renderText}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n editable={editable}\n onMessageEdited={handleMessageEdited}\n defaultCopyFormat={defaultCopyFormat}\n order={order}\n conversationId={conversation.id}\n containerProps={{\n 'data-slot': 'superchat-thread',\n role: 'log',\n 'aria-label': 'Messages',\n 'aria-live': 'polite',\n // Focusable so keyboard-only users can scroll the message history.\n tabIndex: 0,\n className: 'flex-1 overflow-y-auto p-4',\n }}\n />\n ) : (\n <div\n data-slot=\"superchat-thread\"\n ref={threadRef}\n role=\"log\"\n aria-label=\"Messages\"\n aria-live=\"polite\"\n // Focusable so keyboard-only users can scroll the message history.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n className=\"flex-1 space-y-4 overflow-y-auto p-4\"\n >\n {orderedThread.map((m) => (\n <MessageRow\n key={m.id}\n message={m}\n participant={participantById.get(m.participantId)}\n isSelf={\n !!currentParticipantId &&\n m.participantId === currentParticipantId\n }\n renderText={renderText}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n editable={editable}\n onMessageEdited={handleMessageEdited}\n defaultCopyFormat={defaultCopyFormat}\n />\n ))}\n </div>\n )}\n\n <MessageComposer\n onSend={handleComposerSend}\n disabled={readOnly}\n placeholder={\n readOnly\n ? 'Read-only conversation'\n : 'Type a message… use @ to address an agent'\n }\n mentionOptions={mentionOptions}\n showAttachmentPicker={!readOnly}\n showCameraButton={false}\n acceptedFileTypes={composerAccept}\n maxLength={100000}\n />\n </section>\n );\n}\n","/**\n * SuperChatConversations — the conversation list (inbox sidebar) for\n * `@mieweb/ui`.\n *\n * Renders the host-owned conversations sorted by last activity, with unread\n * badges and an optional \"new conversation\" action. Supports both controlled\n * (`activeConversationId`) and uncontrolled (`defaultActiveConversationId`)\n * selection. Pair with {@link SuperChat} for the message panel, or use\n * {@link SuperChatInbox} for the combined surface.\n */\n\nimport * as React from 'react';\nimport { cn } from '../../utils/cn';\nimport { sidebarItem, lastActivityOf, lastMessageByTime } from './parts';\nimport type { SuperChatConversation } from './types';\n\n// ============================================================================\n// SuperChatConversations (conversation list)\n// ============================================================================\n\nexport interface SuperChatConversationsProps {\n /** All conversations (host-owned state). */\n conversations: SuperChatConversation[];\n /** Controlled active conversation id. */\n activeConversationId?: string;\n /** Uncontrolled initial active conversation id. */\n defaultActiveConversationId?: string;\n /** Additional class name. */\n className?: string;\n\n // --- callbacks ---\n onConversationOpened?: (conversation: SuperChatConversation) => void;\n onNewConversation?: () => void;\n}\n\n/**\n * Conversation list. See the module `MAINTAINERS.md` for the data model.\n */\nexport function SuperChatConversations({\n conversations,\n activeConversationId,\n defaultActiveConversationId,\n className,\n onConversationOpened,\n onNewConversation,\n}: SuperChatConversationsProps) {\n const [internalActive, setInternalActive] = React.useState(\n defaultActiveConversationId ?? conversations[0]?.id\n );\n const requestedId = activeConversationId ?? internalActive;\n // Fall back to the first conversation when the requested id no longer exists\n // (e.g. the active conversation was removed) so an item stays highlighted.\n const activeId = conversations.some((c) => c.id === requestedId)\n ? requestedId\n : conversations[0]?.id;\n\n const sortedConversations = React.useMemo(\n () =>\n [...conversations].sort((a, b) => lastActivityOf(b) - lastActivityOf(a)),\n [conversations]\n );\n\n const selectConversation = (c: SuperChatConversation) => {\n if (activeConversationId === undefined) setInternalActive(c.id);\n onConversationOpened?.(c);\n };\n\n return (\n <aside\n data-slot=\"superchat-conversations\"\n aria-label=\"Conversations\"\n className={cn(\n 'flex w-64 shrink-0 flex-col border-e border-neutral-200 dark:border-neutral-700',\n className\n )}\n >\n <div className=\"flex items-center justify-between p-3\">\n <span className=\"text-sm font-semibold text-neutral-700 dark:text-neutral-200\">\n Conversations\n </span>\n {onNewConversation && (\n <button\n type=\"button\"\n onClick={onNewConversation}\n aria-label=\"New conversation\"\n className=\"rounded-md px-2 py-1 text-lg leading-none text-neutral-500 hover:bg-neutral-100 dark:hover:bg-neutral-800\"\n >\n +\n </button>\n )}\n </div>\n <div\n data-slot=\"superchat-conversation-list\"\n role=\"list\"\n className=\"flex-1 space-y-1 overflow-y-auto px-2 pb-2\"\n >\n {sortedConversations.map((c) => {\n const last = lastMessageByTime(c.thread);\n const isActive = c.id === activeId;\n return (\n <div key={c.id} role=\"listitem\">\n <button\n type=\"button\"\n aria-current={isActive ? 'true' : undefined}\n onClick={() => selectConversation(c)}\n className={sidebarItem({ active: isActive })}\n >\n <span className=\"flex-1 truncate\">\n <span className=\"block truncate font-medium\">{c.title}</span>\n {last?.text && (\n <span className=\"block truncate text-xs text-neutral-600 dark:text-neutral-400\">\n {last.text}\n </span>\n )}\n </span>\n {!!c.unread && (\n <span className=\"bg-primary-600 ms-1 inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] font-semibold text-white\">\n {c.unread}\n <span className=\"sr-only\"> unread messages</span>\n </span>\n )}\n </button>\n </div>\n );\n })}\n </div>\n </aside>\n );\n}\n","/**\n * SuperChatInbox — the combined inbox surface for `@mieweb/ui`.\n *\n * Composes {@link SuperChatConversations} (the list) and {@link SuperChat} (the\n * single-conversation panel) into one framed surface. Owns active-conversation\n * coordination and supports both controlled (`activeConversationId`) and\n * uncontrolled (`defaultActiveConversationId`) selection.\n *\n * This is the drop-in equivalent of the original monolithic `SuperChat`: it\n * accepts the same props (conversations array + callbacks).\n */\n\nimport * as React from 'react';\nimport { cn } from '../../utils/cn';\nimport { SuperChat } from './SuperChat';\nimport { SuperChatConversations } from './SuperChatConversations';\nimport type {\n AIRenderTextContent,\n AttachmentKind,\n ComposerAttachment,\n SuperChatConversation,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatRef,\n SuperChatRenderPlugin,\n} from './types';\n\n// ============================================================================\n// SuperChatInbox (list + panel)\n// ============================================================================\n\nexport interface SuperChatInboxProps {\n /** All conversations (host-owned state). */\n conversations: SuperChatConversation[];\n /** Controlled active conversation id. */\n activeConversationId?: string;\n /** Uncontrolled initial active conversation id. */\n defaultActiveConversationId?: string;\n /** The participant id representing the local user (alignment + compose). */\n currentParticipantId?: string;\n /** Opt-in rich render plugins (code/math/genui/…). */\n renderPlugins?: SuperChatRenderPlugin[];\n /** Override the entire text renderer (advanced). */\n renderTextContent?: AIRenderTextContent;\n /** Treat content as trusted and skip sanitization (host-authored only). */\n trustedContent?: boolean;\n /** Disable the composer. */\n readOnly?: boolean;\n /**\n * File categories the composer accepts for paste and the paperclip picker.\n * Defaults to `['image', 'video', 'audio', 'pdf']`.\n */\n acceptedFileTypes?: AttachmentKind[];\n /** Thread ordering: `'asc'` (oldest→newest, default) or `'desc'` (feed-style). */\n order?: 'asc' | 'desc';\n /** Virtualize the message thread (windowed rendering) for long histories. */\n virtualized?: boolean;\n /** Show the conversation sidebar. */\n showSidebar?: boolean;\n /** Build hrefs for `ref` thread items. */\n linkBuilder?: SuperChatLinkBuilder;\n /** Format for a message's default copy action (Ctrl/Cmd-click on copy). */\n defaultCopyFormat?: SuperChatCopyFormat;\n /** Additional class name. */\n className?: string;\n\n // --- callbacks (chat-component-compatible) ---\n onMessageSent?: (\n text: string,\n meta: {\n conversation: SuperChatConversation;\n mentions: string[];\n attachments: ComposerAttachment[];\n }\n ) => void;\n /** Fired when the local user saves an edit to one of their own messages. */\n onMessageEdited?: (\n messageId: string,\n text: string,\n meta: { conversation: SuperChatConversation }\n ) => void;\n onConversationOpened?: (conversation: SuperChatConversation) => void;\n onConversationClosed?: (conversation: SuperChatConversation) => void;\n onNewConversation?: () => void;\n onReferenceClick?: (ref: SuperChatRef) => void;\n}\n\n/**\n * Combined inbox surface (conversation list + active conversation panel). See\n * the module `MAINTAINERS.md` for the participant model and render-plugin\n * architecture.\n */\nexport function SuperChatInbox({\n conversations,\n activeConversationId,\n defaultActiveConversationId,\n currentParticipantId,\n renderPlugins,\n renderTextContent,\n trustedContent,\n readOnly,\n acceptedFileTypes,\n order,\n virtualized,\n showSidebar = true,\n linkBuilder,\n defaultCopyFormat,\n className,\n onMessageSent,\n onMessageEdited,\n onConversationOpened,\n onConversationClosed,\n onNewConversation,\n onReferenceClick,\n}: SuperChatInboxProps) {\n const [internalActive, setInternalActive] = React.useState(\n defaultActiveConversationId ?? conversations[0]?.id\n );\n const requestedId = activeConversationId ?? internalActive;\n const active =\n conversations.find((c) => c.id === requestedId) ?? conversations[0];\n // Resolve the active id from the conversation actually shown so the sidebar\n // highlight never disagrees with the panel when `conversations` changes.\n const activeId = active?.id;\n\n // On small screens the list and panel can't fit side by side, so we show one\n // at a time (master-detail). `mobileView` tracks which is visible; on `sm`+\n // both are always shown and this state is ignored.\n const [mobileView, setMobileView] = React.useState<'list' | 'chat'>('list');\n\n const handleOpen = (c: SuperChatConversation) => {\n if (activeConversationId === undefined) setInternalActive(c.id);\n setMobileView('chat');\n onConversationOpened?.(c);\n };\n\n return (\n <div\n data-slot=\"superchat-inbox\"\n role=\"group\"\n aria-label={active ? `Chat: ${active.title}` : 'Chat'}\n className={cn(\n 'flex h-full overflow-hidden rounded-xl border border-neutral-200 bg-white dark:border-neutral-700 dark:bg-neutral-900',\n className\n )}\n >\n {showSidebar && (\n <SuperChatConversations\n conversations={conversations}\n activeConversationId={activeId}\n onConversationOpened={handleOpen}\n onNewConversation={onNewConversation}\n className={cn(\n 'w-full sm:w-64',\n mobileView === 'chat' && 'hidden sm:flex'\n )}\n />\n )}\n\n {active ? (\n <SuperChat\n conversation={active}\n currentParticipantId={currentParticipantId}\n renderPlugins={renderPlugins}\n renderTextContent={renderTextContent}\n trustedContent={trustedContent}\n readOnly={readOnly}\n acceptedFileTypes={acceptedFileTypes}\n order={order}\n virtualized={virtualized}\n linkBuilder={linkBuilder}\n defaultCopyFormat={defaultCopyFormat}\n onMessageSent={onMessageSent}\n onMessageEdited={onMessageEdited}\n onConversationClosed={onConversationClosed}\n onReferenceClick={onReferenceClick}\n onBack={showSidebar ? () => setMobileView('list') : undefined}\n className={cn(\n showSidebar && mobileView === 'list' && 'hidden sm:flex'\n )}\n />\n ) : (\n <section\n data-slot=\"superchat\"\n className={cn(\n 'min-w-0 flex-1 items-center justify-center text-sm text-neutral-400',\n showSidebar && mobileView === 'list' ? 'hidden sm:flex' : 'flex'\n )}\n >\n No conversation selected\n </section>\n )}\n </div>\n );\n}\n"]}
1
+ {"version":3,"sources":["../../../src/components/SuperChat/render/createMarkdownRenderer.tsx","../../../src/components/SuperChat/parts.tsx","../../../src/components/SuperChat/VirtualThread.tsx","../../../src/components/SuperChat/SuperChat.tsx","../../../src/components/SuperChat/SuperChatConversations.tsx","../../../src/components/SuperChat/SuperChatInbox.tsx"],"names":["defaultSchema","jsx","cn","remarkGfm","rehypeSanitize","defaultUrlTransform","React","MarkdownContent","TextRenderContext","Markdown","Avatar","SparklesIcon","jsxs","Fragment","Badge","React2","DropdownItem","Dropdown","MessageActionsBar","EllipsisIcon","DropdownSubmenu","MessageRow","CheckIcon","ClipboardIcon","PencilIcon","ChatBubble","MCPToolCallDisplay","AITypingIndicator","cva","React3","useVirtualizer","React4","CloseIcon","ChatComposer","React5","React6"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,SAAS,wBAAA,GAA2B;AAClC,EAAA,MAAM,SAAA,GAAY,CAAC,IAAA,KAA0B;AAC3C,IAAA,IAAI,CAAC,KAAK,QAAA,EAAU;AACpB,IAAA,MAAM,OAAoB,EAAC;AAC3B,IAAA,KAAA,MAAW,KAAA,IAAS,KAAK,QAAA,EAAU;AACjC,MAAA,IAAI,KAAA,CAAM,SAAS,MAAA,IAAU,KAAA,CAAM,SAAS,KAAA,CAAM,KAAA,CAAM,QAAA,CAAS,IAAI,CAAA,EAAG;AACtE,QAAA,MAAM,QAAA,GAAW,KAAA,CAAM,KAAA,CAAM,KAAA,CAAM,IAAI,CAAA;AACvC,QAAA,QAAA,CAAS,OAAA,CAAQ,CAAC,OAAA,EAAS,CAAA,KAAM;AAC/B,UAAA,IAAI,IAAI,CAAA,EAAG,IAAA,CAAK,KAAK,EAAE,IAAA,EAAM,SAAS,CAAA;AACtC,UAAA,IAAI,OAAA,OAAc,IAAA,CAAK,EAAE,MAAM,MAAA,EAAQ,KAAA,EAAO,SAAS,CAAA;AAAA,QACzD,CAAC,CAAA;AAAA,MACH,CAAA,MAAO;AACL,QAAA,SAAA,CAAU,KAAK,CAAA;AACf,QAAA,IAAA,CAAK,KAAK,KAAK,CAAA;AAAA,MACjB;AAAA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AA,IAAe,eAAe,MAAA,IAAU;AAAA;AAC1C;AAAA,4BAGFD,cAAAA;AAAA,UAAC,SAAA;AAAA,UAAA;AAAA,YACC,WAAA,EAAU,WAAA;AAAA,YACV,SAAA,EAAWC,oBAAA;AAAA,cACT,qEAAA;AAAA,cACA,WAAA,IAAe,UAAA,KAAe,MAAA,GAAS,gBAAA,GAAmB;AAAA,aAC5D;AAAA,YACD,QAAA,EAAA;AAAA;AAAA;AAED;AAAA;AAAA,GAEJ;AAEJ","file":"index.cjs","sourcesContent":["/**\n * SuperChat Markdown render composer.\n *\n * Composes a list of {@link SuperChatRenderPlugin}s into a single\n * {@link AIRenderTextContent} implementation that plugs into the AI module's\n * `renderTextContent` seam. Ships **Markdown core** (GFM) with `rehype-sanitize`\n * applied to untrusted model/agent output. Math / code / GenUI / NITRO / mermaid\n * are added by passing the corresponding opt-in plugins.\n *\n * The host owns the trust boundary: untrusted content is always sanitized via an\n * allow-list schema, extended by each plugin's `sanitizeSchema` so token\n * classNames (syntax highlighting) and KaTeX markup survive.\n */\n\nimport * as React from 'react';\nimport Markdown, {\n defaultUrlTransform,\n type Components,\n type Options,\n} from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport rehypeSanitize, { defaultSchema } from 'rehype-sanitize';\nimport { cn } from '../../../utils/cn';\nimport { TextRenderContext } from './renderContext';\nimport type {\n AIRenderTextContent,\n AITextRenderContext,\n SuperChatRenderPlugin,\n} from '../types';\n\ntype PluggableList = NonNullable<Options['remarkPlugins']>;\ntype SanitizeSchema = Record<string, unknown>;\n\n/**\n * Minimal mdast node shape we touch when splitting soft line breaks. Kept local\n * so the renderer stays free of extra `unist`/`mdast` util dependencies.\n */\ninterface MdastNode {\n type: string;\n value?: string;\n children?: MdastNode[];\n}\n\n/**\n * A self-contained `remark-breaks` equivalent: turns soft line breaks (single\n * `\\n` inside a paragraph) into hard breaks so chat messages preserve the\n * newlines the author typed — the expected behavior for messaging UIs, where\n * Markdown's default \"collapse single newlines to spaces\" is surprising.\n *\n * Only `text` nodes are split, so fenced/inline code (which carry their value\n * on non-`text` nodes) and existing hard breaks are left untouched.\n */\nfunction remarkPreserveLineBreaks() {\n const splitNode = (node: MdastNode): void => {\n if (!node.children) return;\n const next: MdastNode[] = [];\n for (const child of node.children) {\n if (child.type === 'text' && child.value && child.value.includes('\\n')) {\n const segments = child.value.split('\\n');\n segments.forEach((segment, i) => {\n if (i > 0) next.push({ type: 'break' });\n if (segment) next.push({ type: 'text', value: segment });\n });\n } else {\n splitNode(child);\n next.push(child);\n }\n }\n node.children = next;\n };\n return (tree: MdastNode) => splitNode(tree);\n}\n\n/**\n * A sanitize schema that, on top of the library default, lets syntax-highlight\n * token classes (`hljs-*`) and `language-*` survive on `code`/`pre`/`span`.\n */\nfunction baseSanitizeSchema(): SanitizeSchema {\n const schema = JSON.parse(JSON.stringify(defaultSchema)) as SanitizeSchema;\n const attributes = (schema.attributes ?? {}) as Record<string, unknown[]>;\n\n const allowClass = (tag: string) => {\n const existing = (attributes[tag] ?? []) as unknown[];\n // Drop any prior restricted className rule, allow className broadly.\n const withoutClass = existing.filter(\n (a) => !(Array.isArray(a) && a[0] === 'className')\n );\n attributes[tag] = [...withoutClass, 'className'];\n };\n\n allowClass('code');\n allowClass('pre');\n allowClass('span');\n allowClass('div');\n\n schema.attributes = attributes;\n return schema;\n}\n\n/** Shallow-merge a plugin's sanitize contribution into the running schema. */\nfunction mergeSanitizeSchema(\n base: SanitizeSchema,\n extra?: SanitizeSchema\n): SanitizeSchema {\n if (!extra) return base;\n const out: SanitizeSchema = { ...base };\n\n // tagNames: union\n if (Array.isArray(extra.tagNames)) {\n const a = (base.tagNames as string[] | undefined) ?? [];\n out.tagNames = Array.from(new Set([...a, ...(extra.tagNames as string[])]));\n }\n\n // attributes: per-tag concat\n if (extra.attributes && typeof extra.attributes === 'object') {\n const baseAttrs = {\n ...((base.attributes as Record<string, unknown[]>) ?? {}),\n };\n for (const [tag, attrs] of Object.entries(\n extra.attributes as Record<string, unknown[]>\n )) {\n baseAttrs[tag] = [...(baseAttrs[tag] ?? []), ...attrs];\n }\n out.attributes = baseAttrs;\n }\n\n // protocols: per-attribute union (e.g. allow `data:`/`blob:` image src)\n if (extra.protocols && typeof extra.protocols === 'object') {\n const baseProtocols = {\n ...((base.protocols as Record<string, string[]>) ?? {}),\n };\n for (const [attr, protocols] of Object.entries(\n extra.protocols as Record<string, string[]>\n )) {\n baseProtocols[attr] = Array.from(\n new Set([...(baseProtocols[attr] ?? []), ...protocols])\n );\n }\n out.protocols = baseProtocols;\n }\n\n // any other keys (clobber)\n for (const [k, v] of Object.entries(extra)) {\n if (k === 'tagNames' || k === 'attributes' || k === 'protocols') continue;\n out[k] = v;\n }\n return out;\n}\n\n/** Default node components, themed with `--mieweb-*` tokens via Tailwind. */\nfunction baseComponents(): Components {\n return {\n a: ({ node: _node, children, ...props }) => (\n <a\n {...props}\n className={cn(\n 'text-primary-800 hover:text-primary-900 dark:text-primary-300 underline underline-offset-2',\n props.className\n )}\n // External model output: open links safely.\n target={props.target ?? '_blank'}\n rel={props.rel ?? 'noopener noreferrer'}\n >\n {children}\n </a>\n ),\n pre: ({ node: _node, ...props }) => (\n <pre\n {...props}\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- scrollable code blocks need keyboard focus for horizontal scrolling\n tabIndex={0}\n className={cn(\n 'overflow-x-auto rounded-lg bg-neutral-900 p-3 text-sm text-neutral-100 dark:bg-neutral-950',\n props.className\n )}\n />\n ),\n code: ({ node: _node, ...props }) => {\n const isBlock =\n typeof props.className === 'string' &&\n props.className.includes('language-');\n return (\n <code\n {...props}\n className={cn(\n !isBlock &&\n 'rounded bg-neutral-200 px-1 py-0.5 text-[0.85em] text-neutral-800 dark:bg-neutral-700 dark:text-neutral-100',\n props.className\n )}\n />\n );\n },\n input: ({ node: _node, ...props }) => {\n if (props.type === 'checkbox') {\n return (\n <input\n {...props}\n aria-label={\n props['aria-label'] ??\n (props['aria-labelledby'] ? undefined : 'Task list item')\n }\n />\n );\n }\n return <input {...props} />;\n },\n table: ({ node: _node, ...props }) => (\n <div className=\"my-2 overflow-x-auto\">\n <table\n {...props}\n className={cn(\n 'w-full border-collapse text-sm [&_td]:border [&_td]:border-neutral-200 [&_td]:px-2 [&_td]:py-1 dark:[&_td]:border-neutral-700 [&_th]:border [&_th]:border-neutral-200 [&_th]:px-2 [&_th]:py-1 [&_th]:text-start dark:[&_th]:border-neutral-700',\n props.className\n )}\n />\n </div>\n ),\n // Tailwind's preflight resets list markers/padding; restore them explicitly\n // so bullets/numbers show without depending on the typography plugin.\n ul: ({ node: _node, ...props }) => (\n <ul {...props} className={cn('list-disc ps-5', props.className)} />\n ),\n ol: ({ node: _node, ...props }) => (\n <ol {...props} className={cn('list-decimal ps-5', props.className)} />\n ),\n li: ({ node: _node, ...props }) => (\n <li {...props} className={cn('ps-1', props.className)} />\n ),\n // Preflight also flattens headings to body size/weight; restore a sensible\n // hierarchy without depending on the typography plugin.\n h1: ({ node: _node, children, ...props }) => (\n <h1\n {...props}\n className={cn('mt-3 mb-1 text-xl font-semibold', props.className)}\n >\n {children}\n </h1>\n ),\n h2: ({ node: _node, children, ...props }) => (\n <h2\n {...props}\n className={cn('mt-3 mb-1 text-lg font-semibold', props.className)}\n >\n {children}\n </h2>\n ),\n h3: ({ node: _node, children, ...props }) => (\n <h3\n {...props}\n className={cn('mt-2 mb-1 text-base font-semibold', props.className)}\n >\n {children}\n </h3>\n ),\n h4: ({ node: _node, children, ...props }) => (\n <h4\n {...props}\n className={cn('mt-2 mb-1 text-sm font-semibold', props.className)}\n >\n {children}\n </h4>\n ),\n h5: ({ node: _node, children, ...props }) => (\n <h5\n {...props}\n className={cn('mt-2 mb-1 text-sm font-semibold', props.className)}\n >\n {children}\n </h5>\n ),\n h6: ({ node: _node, children, ...props }) => (\n <h6\n {...props}\n className={cn(\n 'mt-2 mb-1 text-xs font-semibold tracking-wide uppercase',\n props.className\n )}\n >\n {children}\n </h6>\n ),\n hr: ({ node: _node, ...props }) => (\n <hr\n {...props}\n className={cn(\n 'my-2 border-neutral-300 dark:border-neutral-600',\n props.className\n )}\n />\n ),\n };\n}\n\nexport interface CreateMarkdownRendererOptions {\n /** Opt-in rich plugins (code, math, genui, nitro, mermaid, …). */\n plugins?: SuperChatRenderPlugin[];\n /**\n * Disable sanitization. **Only** set this when the content is fully trusted\n * (e.g. authored by the host, never model output). Defaults to `false`.\n */\n trusted?: boolean;\n}\n\n/**\n * Build an {@link AIRenderTextContent} from a set of render plugins.\n *\n * @example\n * const render = createMarkdownRenderer({ plugins: [createCodePlugin(), createMathPlugin()] });\n * <AIChat renderTextContent={render} … />\n */\nexport function createMarkdownRenderer(\n options: CreateMarkdownRendererOptions = {}\n): AIRenderTextContent {\n const { plugins = [], trusted = false } = options;\n\n const remarkPlugins: PluggableList = [\n remarkGfm,\n remarkPreserveLineBreaks,\n ...plugins.flatMap((p) => (p.remarkPlugins ?? []) as PluggableList),\n ];\n\n const pluginRehype: PluggableList = plugins.flatMap(\n (p) => (p.rehypePlugins ?? []) as PluggableList\n );\n\n const sanitizeSchema = plugins.reduce<SanitizeSchema>(\n (acc, p) => mergeSanitizeSchema(acc, p.sanitizeSchema),\n baseSanitizeSchema()\n );\n\n // Sanitize must run AFTER highlight/katex so their classNames are present to\n // be allow-listed, then stripped of anything not permitted.\n const rehypePlugins: PluggableList = trusted\n ? pluginRehype\n : [...pluginRehype, [rehypeSanitize, sanitizeSchema]];\n\n const components: Components = plugins.reduce<Components>(\n (acc, p) => ({ ...acc, ...(p.components as Components | undefined) }),\n baseComponents()\n );\n\n const MarkdownRenderer = (text: string, ctx: AITextRenderContext) => (\n <MarkdownContent\n key={ctx.messageId}\n text={text}\n messageId={ctx.messageId}\n streaming={ctx.streaming}\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins as Options['rehypePlugins']}\n components={components}\n />\n );\n\n return MarkdownRenderer;\n}\n\n/**\n * react-markdown's default `urlTransform` drops `data:`/`blob:` URLs, which\n * would strip pasted/attached images before sanitization runs. Permit those\n * two protocols for image `src` only (sanitization still gates the final\n * markup); everything else keeps react-markdown's safe defaults.\n */\nconst transformUrl: NonNullable<Options['urlTransform']> = (url, key, node) => {\n if (\n key === 'src' &&\n node.tagName === 'img' &&\n (/^data:image\\//i.test(url) || /^blob:/i.test(url))\n ) {\n return url;\n }\n return defaultUrlTransform(url);\n};\n\ninterface MarkdownContentProps {\n text: string;\n messageId: string;\n streaming: boolean;\n remarkPlugins: Options['remarkPlugins'];\n rehypePlugins: Options['rehypePlugins'];\n components: Components;\n}\n\nconst MarkdownContent = React.memo(function MarkdownContent({\n text,\n messageId,\n streaming,\n remarkPlugins,\n rehypePlugins,\n components,\n}: MarkdownContentProps) {\n return (\n <TextRenderContext.Provider value={{ messageId, streaming }}>\n <Markdown\n remarkPlugins={remarkPlugins}\n rehypePlugins={rehypePlugins}\n urlTransform={transformUrl}\n components={components}\n >\n {text}\n </Markdown>\n </TextRenderContext.Provider>\n );\n});\n","/**\n * SuperChat — shared internal building blocks.\n *\n * Pure helpers + presentational pieces used by the three public components\n * ({@link SuperChat}, {@link SuperChatConversations}, {@link SuperChatInbox}).\n * Not part of the public API — import the components from `index.ts` instead.\n */\n\nimport * as React from 'react';\nimport { cva } from 'class-variance-authority';\nimport {\n Check as CheckIcon,\n Clipboard as ClipboardIcon,\n Ellipsis as EllipsisIcon,\n Pencil as PencilIcon,\n} from 'lucide-react';\nimport { cn } from '../../utils/cn';\nimport { Avatar } from '../Avatar';\nimport { Badge } from '../Badge';\nimport { Dropdown, DropdownItem, DropdownSubmenu } from '../Dropdown';\nimport { MCPToolCallDisplay } from '../AI/MCPToolCall';\nimport { ChatBubble, AITypingIndicator } from '../AI/AIMessage';\nimport { SparklesIcon } from '../AI/icons';\nimport type {\n AIRenderTextContent,\n AttachmentKind,\n ComposerAttachment,\n Participant,\n SuperChatConversation,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatMessage,\n SuperChatRef,\n} from './types';\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nexport function formatTime(time: Date | string): string {\n return new Date(time).toLocaleTimeString(undefined, {\n hour: 'numeric',\n minute: '2-digit',\n });\n}\n\nexport function byTime(a: SuperChatMessage, b: SuperChatMessage): number {\n return new Date(a.time).getTime() - new Date(b.time).getTime();\n}\n\nexport function lastActivityOf(c: SuperChatConversation): number {\n if (c.lastActivity) return new Date(c.lastActivity).getTime();\n const last = lastMessageByTime(c.thread);\n return last ? new Date(last.time).getTime() : 0;\n}\n\n/** Compute mentioned participant ids from `@Name` tokens in the draft. */\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function detectMentions(\n text: string,\n participants: Participant[]\n): string[] {\n const ids: string[] = [];\n for (const p of participants) {\n if (p.kind === 'system') continue;\n const token = '@' + p.name.split(' ')[0];\n // Match a whole mention token only: the `@` must not be preceded by a word\n // character or another `@`, and the token must not be followed by a word\n // character (so `@Triage` does not match `@TriageAgent`).\n const pattern = new RegExp(\n `(?<![\\\\w@])${escapeRegExp(token)}(?![\\\\w])`,\n 'i'\n );\n if (pattern.test(text)) ids.push(p.id);\n }\n return ids;\n}\n\nexport function lastMessageByTime(\n thread: SuperChatMessage[]\n): SuperChatMessage | undefined {\n let latest: SuperChatMessage | undefined;\n let latestTime = -Infinity;\n for (const message of thread) {\n const t = new Date(message.time).getTime();\n if (t >= latestTime) {\n latest = message;\n latestTime = t;\n }\n }\n return latest;\n}\n\nfunction parseHexColor(value: string): [number, number, number] | null {\n const hex = value.trim();\n if (!/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex)) return null;\n const normalized =\n hex.length === 4\n ? '#' + [...hex.slice(1)].map((char) => char + char).join('')\n : hex;\n return [1, 3, 5].map((start) =>\n parseInt(normalized.slice(start, start + 2), 16)\n ) as [number, number, number];\n}\n\nfunction relativeLuminanceChannel(channel: number): number {\n const normalized = channel / 255;\n return normalized <= 0.03928\n ? normalized / 12.92\n : ((normalized + 0.055) / 1.055) ** 2.4;\n}\n\nfunction relativeLuminance(value: string): number | null {\n const rgb = parseHexColor(value);\n if (!rgb) return null;\n const [red, green, blue] = rgb;\n return (\n 0.2126 * relativeLuminanceChannel(red) +\n 0.7152 * relativeLuminanceChannel(green) +\n 0.0722 * relativeLuminanceChannel(blue)\n );\n}\n\nfunction contrastRatio(foreground: string, background: string): number | null {\n const foregroundLuminance = relativeLuminance(foreground);\n const backgroundLuminance = relativeLuminance(background);\n if (foregroundLuminance === null || backgroundLuminance === null) return null;\n const lighter = Math.max(foregroundLuminance, backgroundLuminance);\n const darker = Math.min(foregroundLuminance, backgroundLuminance);\n return (lighter + 0.05) / (darker + 0.05);\n}\n\nfunction minimumContrastRatio(\n value: string,\n backgrounds: string[]\n): number | null {\n const contrasts = backgrounds\n .map((background) => contrastRatio(value, background))\n .filter((contrast): contrast is number => contrast !== null);\n if (contrasts.length !== backgrounds.length) return null;\n return Math.min(...contrasts);\n}\n\nfunction accessibleAccentTextColor(value?: string): string | undefined {\n if (!value) return undefined;\n const contrast = minimumContrastRatio(value, ['#f5f5f5', '#262626']);\n if (contrast === null) return value;\n return contrast < 4.5 ? undefined : value;\n}\n\n// ============================================================================\n// Avatar\n// ============================================================================\n\nexport function ParticipantAvatar({\n participant,\n}: {\n participant?: Participant;\n}) {\n const isAgent = participant?.kind === 'agent';\n const backgroundColor =\n participant?.color ??\n (isAgent ? 'var(--mieweb-primary-700, #1f2937)' : '#64748b');\n return (\n <Avatar\n size=\"xs\"\n src={participant?.avatar}\n alt=\"\"\n name={participant?.name ?? '?'}\n fallback={isAgent ? <SparklesIcon size=\"sm\" /> : undefined}\n // Per-participant color (or agent/default) disambiguates concurrent\n // speakers; overrides Avatar's default primary background.\n style={{ backgroundColor }}\n aria-hidden=\"true\"\n className=\"shrink-0\"\n />\n );\n}\n\n// ============================================================================\n// Reference chip (chat-component `ref` thread items)\n// ============================================================================\n\nexport function ReferenceChip({\n reference,\n linkBuilder,\n onReferenceClick,\n}: {\n reference: SuperChatRef;\n linkBuilder?: SuperChatLinkBuilder;\n onReferenceClick?: (ref: SuperChatRef) => void;\n}) {\n const href = linkBuilder?.(reference);\n const content = (\n <>\n <Badge\n variant=\"default\"\n size=\"sm\"\n className=\"rounded px-1.5 text-[10px] font-semibold tracking-wide uppercase\"\n >\n {reference.refType}\n </Badge>\n <span className=\"truncate\">{reference.title}</span>\n </>\n );\n const className =\n 'inline-flex max-w-full items-center gap-2 rounded-lg border border-neutral-200 bg-white px-3 py-1.5 text-sm text-neutral-700 hover:border-primary-300 dark:border-neutral-700 dark:bg-neutral-800 dark:text-neutral-200';\n if (href) {\n return (\n <a\n href={href}\n className={className}\n onClick={() => onReferenceClick?.(reference)}\n >\n {content}\n </a>\n );\n }\n return (\n <button\n type=\"button\"\n className={className}\n onClick={() => onReferenceClick?.(reference)}\n >\n {content}\n </button>\n );\n}\n\n// ============================================================================\n// Message row\n// ============================================================================\n\n/**\n * Supported attachment categories: their `<input accept>` token and a MIME\n * matcher used to filter pastes and file-picker selections.\n */\nconst ATTACHMENT_KIND_CONFIG: Record<\n AttachmentKind,\n { accept: string; match: (type: string) => boolean }\n> = {\n image: { accept: 'image/*', match: (t) => t.startsWith('image/') },\n video: { accept: 'video/*', match: (t) => t.startsWith('video/') },\n audio: { accept: 'audio/*', match: (t) => t.startsWith('audio/') },\n pdf: { accept: 'application/pdf', match: (t) => t === 'application/pdf' },\n};\n\nconst DEFAULT_ACCEPTED_FILE_TYPES: AttachmentKind[] = [\n 'image',\n 'video',\n 'audio',\n 'pdf',\n];\n\n/**\n * Map SuperChat's high-level {@link AttachmentKind} categories to the\n * `<input accept>` tokens consumed by the shared `MessageComposer`.\n */\nexport function acceptTokensFor(\n kinds: AttachmentKind[] = DEFAULT_ACCEPTED_FILE_TYPES\n): string[] {\n const source = kinds.length > 0 ? kinds : DEFAULT_ACCEPTED_FILE_TYPES;\n return Array.from(\n new Set(source.map((k) => ATTACHMENT_KIND_CONFIG[k].accept))\n );\n}\n\n/**\n * Read the `File` objects emitted by the shared `MessageComposer` into the\n * base64 `data:` URL {@link ComposerAttachment}s SuperChat hosts expect.\n */\nexport function filesToComposerAttachments(\n files: File[]\n): Promise<ComposerAttachment[]> {\n return Promise.all(\n files.map(\n (file, i) =>\n new Promise<ComposerAttachment>((resolve, reject) => {\n const reader = new window.FileReader();\n reader.onload = () => {\n const dataUrl =\n typeof reader.result === 'string' ? reader.result : '';\n resolve({\n id: `att-${Date.now()}-${i}`,\n name: file.name || `attachment-${i}`,\n type: file.type || 'application/octet-stream',\n dataUrl,\n });\n };\n reader.onerror = () => reject(reader.error);\n reader.readAsDataURL(file);\n })\n )\n );\n}\n\n// ============================================================================\n// Message actions (footer bar + sticky overflow menu)\n// ============================================================================\n\n/**\n * Reveal-on-hover/focus for message action affordances. Hover doesn't exist on\n * touch devices, so coarse pointers always show the actions.\n */\nconst actionRevealClass =\n 'opacity-0 transition-opacity group-focus-within:opacity-100 group-hover:opacity-100 focus-visible:opacity-100 [@media(pointer:coarse)]:opacity-100';\n\nconst actionButtonClass =\n 'rounded p-1 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-200';\n\ninterface MessageActionItem {\n id: string;\n label: string;\n /** Secondary line shown under the label in the overflow menu. */\n description?: string;\n onSelect: () => void;\n}\n\n/**\n * One per-message action, rendered twice from the same definition: as an icon\n * button in the footer bar and as an item in the sticky overflow (⋯) menu.\n */\ninterface MessageAction {\n id: string;\n /** Accessible name (footer button) and menu label. */\n label: string;\n icon: React.ReactNode;\n /** Footer-button tooltip — e.g. to hint modifier behavior. Defaults to `label`. */\n title?: string;\n /** Default behavior (footer click / top-level menu item). */\n onSelect: () => void;\n /** Explicit variants, rendered as a flyout submenu in the overflow menu. */\n submenu?: { label: string; items: MessageActionItem[] };\n}\n\ninterface UseMessageCopyOptions {\n /** Markdown source for this message (plain-text / Markdown copy). */\n markdown: string;\n /** Read the rendered bubble HTML at copy time (rich-text copy). */\n getHtml: () => string;\n /** Read the rendered bubble plain text at copy time. */\n getText: () => string;\n /** One-click format for the default copy action. */\n defaultFormat: SuperChatCopyFormat;\n}\n\n/**\n * Per-message clipboard writes. The **rich** format writes *both* a rich-text\n * (`text/html`) and a Markdown (`text/plain`) representation in a single\n * clipboard write, so the paste target decides: rich editors get formatting,\n * plain editors get Markdown. Explicit \"as Markdown\" / \"as plain text\"\n * variants are also exposed, and `copyDefault` honors the host-configured\n * {@link SuperChatCopyFormat}.\n */\nfunction useMessageCopy({\n markdown,\n getHtml,\n getText,\n defaultFormat,\n}: UseMessageCopyOptions) {\n const [copied, setCopied] = React.useState(false);\n const copiedTimer = React.useRef<ReturnType<typeof setTimeout> | undefined>(\n undefined\n );\n\n React.useEffect(() => () => window.clearTimeout(copiedTimer.current), []);\n\n const flash = () => {\n setCopied(true);\n window.clearTimeout(copiedTimer.current);\n copiedTimer.current = setTimeout(() => setCopied(false), 1200);\n };\n\n const writeText = async (value: string) => {\n if (!navigator.clipboard?.writeText) {\n // Insecure context / unsupported browser: reject so the caller doesn't\n // flash a misleading \"Copied\" success.\n throw new Error('Clipboard API unavailable');\n }\n await navigator.clipboard.writeText(value);\n };\n\n const writeBoth = async () => {\n const html = getHtml();\n const text = markdown || getText();\n try {\n if (\n typeof window !== 'undefined' &&\n 'ClipboardItem' in window &&\n navigator.clipboard?.write\n ) {\n await navigator.clipboard.write([\n new window.ClipboardItem({\n 'text/html': new Blob([html], { type: 'text/html' }),\n 'text/plain': new Blob([text], { type: 'text/plain' }),\n }),\n ]);\n } else {\n await writeText(text);\n }\n } catch {\n await writeText(text);\n }\n };\n\n const run = (fn: () => Promise<void>) => {\n // Only flash \"Copied\" when the write actually succeeds; swallow failures\n // (insecure context / denied permission) instead of leaking an unhandled\n // rejection or showing a false success.\n void fn().then(flash, () => {});\n };\n\n const copyRich = () => run(writeBoth);\n const copyMarkdown = () => run(() => writeText(markdown || getText()));\n const copyPlain = () => run(() => writeText(getText()));\n const copyDefault =\n defaultFormat === 'markdown'\n ? copyMarkdown\n : defaultFormat === 'plain'\n ? copyPlain\n : copyRich;\n\n return { copied, copyDefault, copyRich, copyMarkdown, copyPlain };\n}\n\ninterface MessageActionsBarProps {\n actions: MessageAction[];\n isSelf: boolean;\n}\n\n/** A submenu item as a Dropdown row, with an optional secondary line. */\nfunction ActionMenuItem({\n item,\n onSelect,\n}: {\n item: MessageActionItem;\n onSelect: (fn: () => void) => void;\n}) {\n return (\n <DropdownItem onClick={() => onSelect(item.onSelect)}>\n {item.description ? (\n <span className=\"flex flex-col items-start\">\n <span>{item.label}</span>\n <span className=\"text-[10px] font-normal text-neutral-400\">\n {item.description}\n </span>\n </span>\n ) : (\n item.label\n )}\n </DropdownItem>\n );\n}\n\n/**\n * One footer-bar affordance. Plain actions run their default on click; actions\n * with variants (e.g. copy formats) open a small menu of those variants, like\n * the original per-message copy menu. Ctrl/Cmd-click skips the menu and runs\n * the action's default (e.g. the host-configured {@link SuperChatCopyFormat}).\n */\nfunction FooterActionButton({\n action,\n isSelf,\n}: {\n action: MessageAction;\n isSelf: boolean;\n}) {\n const [open, setOpen] = React.useState(false);\n\n // Capture-phase so it runs before the Dropdown's trigger onClick: a\n // modifier click fires the default action instead of opening the menu.\n const onClickCapture = action.submenu\n ? (e: React.MouseEvent) => {\n if (e.metaKey || e.ctrlKey) {\n e.preventDefault();\n e.stopPropagation();\n action.onSelect();\n }\n }\n : undefined;\n\n const button = (\n <button\n type=\"button\"\n data-slot={`superchat-action-${action.id}`}\n aria-label={action.label}\n title={action.title ?? action.label}\n onClick={action.submenu ? undefined : action.onSelect}\n onClickCapture={onClickCapture}\n className={actionButtonClass}\n >\n {action.icon}\n </button>\n );\n\n if (!action.submenu) return button;\n\n return (\n <Dropdown\n open={open}\n onOpenChange={setOpen}\n placement={isSelf ? 'top-end' : 'top-start'}\n trigger={button}\n >\n {action.submenu.items.map((item) => (\n <ActionMenuItem\n key={item.id}\n item={item}\n onSelect={(fn) => {\n setOpen(false);\n fn();\n }}\n />\n ))}\n </Dropdown>\n );\n}\n\n/**\n * The hover-revealed row of action icon buttons under a message bubble. Each\n * button runs its action's default behavior; explicit variants live in the\n * sticky overflow menu ({@link MessageOverflowMenu}).\n */\nconst MessageActionsBar = React.forwardRef<\n HTMLDivElement,\n MessageActionsBarProps\n>(function MessageActionsBar({ actions, isSelf }, ref) {\n return (\n <div\n ref={ref}\n data-slot=\"superchat-message-actions\"\n className={cn(\n 'flex items-center gap-0.5',\n isSelf && 'justify-end',\n actionRevealClass\n )}\n >\n {actions.map((action) => (\n <FooterActionButton key={action.id} action={action} isSelf={isSelf} />\n ))}\n </div>\n );\n});\n\ninterface MessageOverflowMenuProps {\n /** Aligns the popover to the outer margin (right for self, left otherwise). */\n isSelf: boolean;\n actions: MessageAction[];\n /**\n * Whether the footer action bar is currently in view. While it is, the\n * overflow trigger hides (the footer already offers the actions); it\n * reappears — floating — once the footer scrolls out of view mid-message.\n */\n footerVisible: boolean;\n}\n\n/**\n * The sticky overflow (⋯) control beside the bubble. On long messages it\n * follows the scroll (sticky within the thread) so actions stay reachable, and\n * hands off to the footer bar once the message end scrolls into view.\n */\nfunction MessageOverflowMenu({\n isSelf,\n actions,\n footerVisible,\n}: MessageOverflowMenuProps) {\n const [open, setOpen] = React.useState(false);\n\n const select = (fn: () => void) => {\n setOpen(false);\n fn();\n };\n\n return (\n <div\n // Self-align to the bottom of the (possibly tall) message row and stick\n // to the viewport bottom: on long messages the control follows the\n // scroll and settles at the message's end once it is fully in view.\n // Raise the whole (sticky) stacking context above the sibling bubble\n // while open so the menu sits over rich content like tables.\n className={cn(\n 'sticky bottom-2 shrink-0 self-end transition-opacity',\n // Rich content (e.g. NITRO tables) layers internals up to z-50, so the\n // open menu's stacking context must clear that.\n open ? 'z-[60]' : 'z-10',\n // Hand off to the footer bar when it's visible. `invisible` (not\n // just opacity) drops the hidden button from the tab order so\n // keyboard users can't focus an unseen control.\n footerVisible && !open && 'pointer-events-none invisible opacity-0'\n )}\n >\n <Dropdown\n open={open}\n onOpenChange={setOpen}\n placement={isSelf ? 'top-end' : 'top-start'}\n trigger={\n <button\n type=\"button\"\n data-slot=\"superchat-overflow-button\"\n aria-label=\"Message actions\"\n className={cn(actionButtonClass, actionRevealClass)}\n >\n <EllipsisIcon size={14} aria-hidden=\"true\" />\n </button>\n }\n >\n {actions.map((action) =>\n action.submenu ? (\n // Actions with variants collapse to just their submenu — a\n // top-level default item would duplicate the flyout's options.\n <DropdownSubmenu key={action.id} label={action.submenu.label}>\n {action.submenu.items.map((item) => (\n <ActionMenuItem key={item.id} item={item} onSelect={select} />\n ))}\n </DropdownSubmenu>\n ) : (\n <DropdownItem\n key={action.id}\n onClick={() => select(action.onSelect)}\n >\n {action.label}\n </DropdownItem>\n )\n )}\n </Dropdown>\n </div>\n );\n}\n\ninterface MessageRowProps {\n message: SuperChatMessage;\n participant?: Participant;\n isSelf: boolean;\n renderText: AIRenderTextContent;\n linkBuilder?: SuperChatLinkBuilder;\n onReferenceClick?: (ref: SuperChatRef) => void;\n /** Whether self-authored text messages expose an inline \"Edit\" affordance. */\n editable?: boolean;\n /** Save handler for an inline message edit (bound to this message's id). */\n onMessageEdited?: (messageId: string, text: string) => void;\n /** Format for the default copy action — Ctrl/Cmd-click on the footer copy\n * button (defaults to `'rich'`). */\n defaultCopyFormat?: SuperChatCopyFormat;\n}\n\n/**\n * A single thread row (message / system notice / reference chip).\n *\n * Wrapped in {@link React.memo}: in long threads the parent re-renders on every\n * new message, but each existing row's props are stable (the host owns the\n * message objects), so memoization skips re-rendering — and, crucially,\n * re-running the Markdown pipeline — for the hundreds of rows that did not\n * change. Keep the props referentially stable from the host for this to help.\n */\nexport const MessageRow = React.memo(function MessageRow({\n message,\n participant,\n isSelf,\n renderText,\n linkBuilder,\n onReferenceClick,\n editable,\n onMessageEdited,\n defaultCopyFormat = 'rich',\n}: MessageRowProps) {\n const streaming = message.status === 'streaming';\n const hasBody = !!message.text || (message.content?.length ?? 0) > 0;\n const [isEditing, setIsEditing] = React.useState(false);\n const [draft, setDraft] = React.useState(message.text ?? '');\n const editRef = React.useRef<HTMLTextAreaElement>(null);\n // The rendered bubble content, read at copy time for the rich-text payload.\n const bubbleRef = React.useRef<HTMLDivElement>(null);\n // Grow the editor to fit its content (accounts for wrapped lines, not just\n // explicit newlines), clamped by the textarea's CSS max-height.\n const autosize = React.useCallback(() => {\n const el = editRef.current;\n if (!el) return;\n el.style.height = 'auto';\n el.style.height = `${el.scrollHeight}px`;\n }, []);\n // Move focus into the editor (caret at end) and size it when editing starts.\n React.useEffect(() => {\n if (!isEditing) return;\n const el = editRef.current;\n if (!el) return;\n el.focus();\n el.setSelectionRange(el.value.length, el.value.length);\n autosize();\n }, [isEditing, autosize]);\n\n // --- Message actions (copy / edit) ---------------------------------------\n // Computed before the early returns below so the hooks run unconditionally\n // (system/ref rows simply never render the action surfaces).\n\n // Inline editing applies only to the local user's own plain-text messages\n // (rich content blocks / streaming messages are not inline-editable).\n const canEdit =\n !!editable &&\n isSelf &&\n !streaming &&\n typeof message.text === 'string' &&\n !message.content?.length;\n\n // The Markdown source for copying: prefer the raw `text`, otherwise assemble\n // it from the message's text/code content blocks.\n const markdownSource =\n typeof message.text === 'string' && message.text\n ? message.text\n : (message.content\n ?.map((block) => {\n if (block.type === 'code' && block.text) {\n return `\\`\\`\\`${block.language ?? ''}\\n${block.text}\\n\\`\\`\\``;\n }\n if (\n (block.type === 'text' || block.type === 'thinking') &&\n block.text\n ) {\n return block.text;\n }\n return '';\n })\n .filter(Boolean)\n .join('\\n\\n') ?? '');\n\n // A copy affordance appears on every message that has a body (not while it\n // is being edited).\n const canCopy =\n !isEditing &&\n (!!message.content?.length ||\n (typeof message.text === 'string' && message.text.length > 0));\n\n const hasActions = canCopy || (canEdit && !isEditing);\n\n const copy = useMessageCopy({\n markdown: markdownSource,\n getHtml: () => bubbleRef.current?.innerHTML ?? '',\n getText: () => bubbleRef.current?.textContent ?? '',\n defaultFormat: defaultCopyFormat,\n });\n\n // Hand-off between the footer action bar and the sticky overflow (⋯): the\n // overflow only shows while the footer bar is scrolled out of view.\n // Clipping by the scrollable thread counts as \"not intersecting\", so the\n // default viewport root is sufficient. Starts optimistic (footer assumed\n // visible) so rows freshly mounted by the virtualized thread don't flash\n // the overflow before the observer's first callback.\n const actionsBarRef = React.useRef<HTMLDivElement>(null);\n const [footerVisible, setFooterVisible] = React.useState(true);\n React.useEffect(() => {\n const el = actionsBarRef.current;\n if (!el || typeof globalThis.IntersectionObserver === 'undefined') return;\n const observer = new globalThis.IntersectionObserver(([entry]) => {\n setFooterVisible(entry?.isIntersecting ?? false);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, [hasActions]);\n\n if (message.type === 'system') {\n return (\n <div\n data-slot=\"superchat-system-message\"\n role=\"status\"\n className=\"my-1 text-center text-xs text-neutral-500 dark:text-neutral-400\"\n >\n {message.text}\n </div>\n );\n }\n\n if (message.type === 'ref' && message.ref) {\n return (\n <div\n data-slot=\"superchat-reference\"\n className={cn('flex', isSelf && 'justify-end')}\n >\n <ReferenceChip\n reference={message.ref}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n />\n </div>\n );\n }\n\n const accent = participant?.color;\n const accentTextColor = accessibleAccentTextColor(accent);\n const authorName = participant?.name ?? 'Unknown';\n\n const startEdit = () => {\n setDraft(message.text ?? '');\n setIsEditing(true);\n };\n const cancelEdit = () => setIsEditing(false);\n const saveEdit = () => {\n const next = draft.trim();\n if (next && next !== message.text) onMessageEdited?.(message.id, next);\n setIsEditing(false);\n };\n\n // Paste an image into the editor: splice its Markdown at the caret so it\n // becomes part of the message source (the bubble renders Markdown).\n const handleEditPaste = (e: React.ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(e.clipboardData.items)\n .filter((item) => item.kind === 'file' && item.type.startsWith('image/'))\n .map((item) => item.getAsFile())\n .filter((f): f is File => f !== null);\n if (files.length === 0) return;\n e.preventDefault();\n const el = e.currentTarget;\n const start = el.selectionStart ?? draft.length;\n const end = el.selectionEnd ?? draft.length;\n Promise.all(\n files.map(\n (file, i) =>\n new Promise<string>((resolve) => {\n const reader = new window.FileReader();\n reader.onload = () => {\n const dataUrl =\n typeof reader.result === 'string' ? reader.result : '';\n const name = file.name || `pasted-image-${i + 1}.png`;\n resolve(dataUrl ? `![${name}](${dataUrl})` : '');\n };\n reader.readAsDataURL(file);\n })\n )\n ).then((snippets) => {\n const insert = snippets.filter(Boolean).join('\\n');\n if (!insert) return;\n // Insert via `execCommand('insertText')` so the browser records it on its\n // native undo stack (Cmd/Ctrl+Z works) and fires a normal input event\n // that flows back through `onChange`. Fall back to a controlled-state\n // splice if the (deprecated) command is unavailable.\n el.focus();\n el.setSelectionRange(start, end);\n const text = `${insert}\\n`;\n const inserted =\n typeof document !== 'undefined' &&\n typeof document.execCommand === 'function' &&\n document.execCommand('insertText', false, text);\n if (!inserted) {\n setDraft((prev) => `${prev.slice(0, start)}${text}${prev.slice(end)}`);\n }\n requestAnimationFrame(autosize);\n });\n };\n\n // The same action definitions power both surfaces: the footer icon bar and\n // the sticky overflow menu.\n const actions: MessageAction[] = [\n ...(canCopy\n ? [\n {\n id: 'copy',\n label: 'Copy message',\n title: 'Copy message (\\u2318/Ctrl-click: default format)',\n icon: copy.copied ? (\n <CheckIcon size={14} aria-hidden=\"true\" />\n ) : (\n <ClipboardIcon size={14} aria-hidden=\"true\" />\n ),\n onSelect: copy.copyDefault,\n submenu: {\n label: 'Copy as',\n items: [\n {\n id: 'copy-rich',\n label: 'Copy as rich text',\n description: 'Rich text + Markdown',\n onSelect: copy.copyRich,\n },\n {\n id: 'copy-markdown',\n label: 'Copy as Markdown',\n onSelect: copy.copyMarkdown,\n },\n {\n id: 'copy-plain',\n label: 'Copy as plain text',\n onSelect: copy.copyPlain,\n },\n ],\n },\n } satisfies MessageAction,\n ]\n : []),\n ...(canEdit && !isEditing\n ? [\n {\n id: 'edit',\n label: 'Edit message',\n icon: <PencilIcon size={14} aria-hidden=\"true\" />,\n onSelect: startEdit,\n } satisfies MessageAction,\n ]\n : []),\n ];\n\n return (\n <div\n data-slot=\"superchat-message\"\n role=\"article\"\n aria-label={`${authorName}, ${formatTime(message.time)}`}\n className={cn(\n 'group flex gap-2',\n isSelf ? 'flex-row-reverse' : 'flex-row'\n )}\n >\n <ParticipantAvatar participant={participant} />\n <div className={cn('flex min-w-0 flex-col gap-1', isSelf && 'items-end')}>\n <div\n data-slot=\"superchat-message-meta\"\n className=\"flex items-baseline gap-2\"\n >\n <span\n className=\"text-xs font-medium\"\n style={accentTextColor ? { color: accentTextColor } : undefined}\n >\n {authorName}\n </span>\n {participant?.role && (\n <span className=\"text-[10px] text-neutral-500 dark:text-neutral-400\">\n {participant.role}\n </span>\n )}\n <span className=\"text-[10px] text-neutral-500 dark:text-neutral-400\">\n {formatTime(message.time)}\n </span>\n {message.editedAt && (\n <span\n data-slot=\"superchat-edited-indicator\"\n className=\"text-[10px] text-neutral-500 dark:text-neutral-400\"\n title={`Edited ${formatTime(message.editedAt)}`}\n >\n (edited)\n </span>\n )}\n </div>\n\n <div\n className={cn(\n 'flex items-center gap-1',\n isSelf ? 'flex-row-reverse' : 'flex-row'\n )}\n >\n {hasActions && (\n <MessageOverflowMenu\n isSelf={isSelf}\n actions={actions}\n footerVisible={footerVisible}\n />\n )}\n <ChatBubble\n ref={bubbleRef}\n data-slot=\"superchat-bubble\"\n variant={isSelf ? 'user' : 'assistant'}\n hasError={message.status === 'error'}\n className=\"text-sm has-[[data-slot=superchat-nitro-table]]:w-full has-[[data-slot=superchat-nitro-table]]:max-w-full\"\n >\n {isEditing ? (\n <div\n data-slot=\"superchat-message-editor\"\n className=\"flex w-80 max-w-full flex-col gap-2\"\n >\n <textarea\n value={draft}\n ref={editRef}\n rows={2}\n onChange={(e) => {\n setDraft(e.target.value);\n autosize();\n }}\n onPaste={handleEditPaste}\n onKeyDown={(e) => {\n if (e.key === 'Enter' && !e.shiftKey) {\n e.preventDefault();\n saveEdit();\n } else if (e.key === 'Escape') {\n e.preventDefault();\n cancelEdit();\n }\n }}\n aria-label=\"Edit message\"\n className=\"focus:ring-primary-500 max-h-60 min-h-16 w-full resize-none rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 focus:ring-1 focus:outline-none dark:border-neutral-600 dark:bg-neutral-900 dark:text-white\"\n />\n <div className=\"flex justify-end gap-2\">\n <button\n type=\"button\"\n onClick={cancelEdit}\n className=\"rounded-md px-2.5 py-1 text-xs font-medium text-neutral-200 hover:bg-white/10\"\n >\n Cancel\n </button>\n <button\n type=\"button\"\n onClick={saveEdit}\n disabled={!draft.trim() || draft.trim() === message.text}\n className=\"rounded-md bg-white px-2.5 py-1 text-xs font-medium text-neutral-900 hover:bg-neutral-100 disabled:opacity-40\"\n >\n Save\n </button>\n </div>\n </div>\n ) : (\n <>\n {/* Rich content blocks (tool calls etc.) reused from the AI module. */}\n {message.content?.map((block, i) => {\n if (block.type === 'tool_use' && block.toolCall) {\n return (\n <MCPToolCallDisplay key={i} toolCall={block.toolCall} />\n );\n }\n if (\n (block.type === 'text' || block.type === 'thinking') &&\n block.text\n ) {\n return (\n <div\n key={i}\n className=\"prose prose-sm dark:prose-invert max-w-none **:wrap-break-word\"\n >\n {renderText(block.text, {\n messageId: message.id,\n streaming,\n role:\n participant?.kind === 'human'\n ? 'user'\n : 'assistant',\n })}\n </div>\n );\n }\n if (block.type === 'code' && block.text) {\n const fenced = `\\`\\`\\`${block.language ?? ''}\\n${block.text}\\n\\`\\`\\``;\n return (\n <div\n key={i}\n className=\"prose prose-sm dark:prose-invert max-w-none **:wrap-break-word\"\n >\n {renderText(fenced, {\n messageId: message.id,\n streaming,\n role:\n participant?.kind === 'human'\n ? 'user'\n : 'assistant',\n })}\n </div>\n );\n }\n return null;\n })}\n\n {/* Plain `text` body (the common case). */}\n {message.text && (\n <div className=\"prose prose-sm dark:prose-invert max-w-none **:wrap-break-word\">\n {renderText(message.text, {\n messageId: message.id,\n streaming,\n role:\n participant?.kind === 'human' ? 'user' : 'assistant',\n })}\n </div>\n )}\n\n {/* Animated typing indicator while a reply streams in with no\n body yet — matches the AI chat's streaming affordance. */}\n {streaming && !hasBody && (\n <div className=\"flex items-center justify-center\">\n <AITypingIndicator />\n </div>\n )}\n </>\n )}\n </ChatBubble>\n </div>\n {hasActions && (\n <MessageActionsBar\n ref={actionsBarRef}\n actions={actions}\n isSelf={isSelf}\n />\n )}\n </div>\n </div>\n );\n});\n\n// ============================================================================\n// Sidebar item style\n// ============================================================================\n\nexport const sidebarItem = cva(\n 'flex w-full items-center gap-2 rounded-lg px-3 py-2 text-start text-sm transition-colors',\n {\n variants: {\n active: {\n true: 'bg-primary-100 text-primary-900 dark:bg-primary-900/40 dark:text-primary-100',\n false:\n 'text-neutral-700 hover:bg-neutral-100 dark:text-neutral-200 dark:hover:bg-neutral-800',\n },\n },\n defaultVariants: { active: false },\n }\n);\n","/**\n * VirtualThread — windowed (virtualized) message list for {@link SuperChat}.\n *\n * Renders only the rows near the viewport using `@tanstack/react-virtual` with\n * dynamic measurement, so a thread of thousands of messages mounts ~20-30 DOM\n * subtrees instead of all of them. This keeps first render, memory, and the\n * Markdown parse cost bounded by what is on screen rather than by the total\n * history length.\n *\n * Opt-in via the `virtualized` prop on `SuperChat`/`SuperChatInbox`. The\n * non-virtualized path remains the default for short threads, where the extra\n * absolute-positioning machinery is unnecessary.\n */\n\nimport * as React from 'react';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport { MessageRow } from './parts';\nimport type {\n AIRenderTextContent,\n Participant,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatMessage,\n SuperChatRef,\n} from './types';\n\nexport interface VirtualThreadProps {\n /** The messages to render, already sorted in display order. */\n items: SuperChatMessage[];\n /** Lookup from participant id to participant. */\n participantById: Map<string, Participant>;\n /** The local user id (drives self-alignment). */\n currentParticipantId?: string;\n /** Text renderer (Markdown pipeline). */\n renderText: AIRenderTextContent;\n /** Build hrefs for `ref` items. */\n linkBuilder?: SuperChatLinkBuilder;\n /** Fired when a reference chip is activated. */\n onReferenceClick?: (ref: SuperChatRef) => void;\n /** Whether self-authored text messages expose an inline \"Edit\" affordance. */\n editable?: boolean;\n /** Save handler for an inline message edit (bound to the message's id). */\n onMessageEdited?: (messageId: string, text: string) => void;\n /** Format for a message's default copy action (Ctrl/Cmd-click on copy). */\n defaultCopyFormat?: SuperChatCopyFormat;\n /**\n * Thread ordering. `'asc'` anchors new messages to the bottom; `'desc'`\n * anchors them to the top (feed style).\n */\n order: 'asc' | 'desc';\n /** Conversation id — changing it re-anchors scroll to the newest message. */\n conversationId: string;\n /** Props forwarded to the scroll container (role/aria/tabIndex/className). */\n containerProps: React.HTMLAttributes<HTMLDivElement> & {\n 'data-slot'?: string;\n };\n}\n\nexport function VirtualThread({\n items,\n participantById,\n currentParticipantId,\n renderText,\n linkBuilder,\n onReferenceClick,\n editable,\n onMessageEdited,\n defaultCopyFormat,\n order,\n conversationId,\n containerProps,\n}: VirtualThreadProps) {\n const parentRef = React.useRef<HTMLDivElement>(null);\n\n const virtualizer = useVirtualizer({\n count: items.length,\n getScrollElement: () => parentRef.current,\n // Rough first guess; real heights are measured via measureElement.\n estimateSize: () => 88,\n overscan: 10,\n getItemKey: (index) => items[index]?.id ?? index,\n });\n\n // Anchor to the newest message: bottom for ascending order, top for\n // descending (feed-style) order. Runs on mount, when the conversation\n // changes, and when a message is appended.\n const count = items.length;\n React.useEffect(() => {\n if (count === 0) return;\n if (order === 'desc') {\n virtualizer.scrollToIndex(0, { align: 'start' });\n } else {\n virtualizer.scrollToIndex(count - 1, { align: 'end' });\n }\n // `virtualizer` is stable across renders for a given instance.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [count, conversationId, order]);\n\n const virtualItems = virtualizer.getVirtualItems();\n\n return (\n <div {...containerProps} ref={parentRef}>\n <div\n style={{\n height: virtualizer.getTotalSize(),\n position: 'relative',\n width: '100%',\n }}\n >\n {virtualItems.map((virtualRow) => {\n const message = items[virtualRow.index];\n if (!message) return null;\n return (\n <div\n key={virtualRow.key}\n data-index={virtualRow.index}\n ref={virtualizer.measureElement}\n style={{\n position: 'absolute',\n top: 0,\n left: 0,\n width: '100%',\n transform: `translateY(${virtualRow.start}px)`,\n }}\n >\n {/* Bottom padding stands in for the non-virtual `space-y-4` gap\n and is included in the measured height. */}\n <div className=\"pb-4\">\n <MessageRow\n message={message}\n participant={participantById.get(message.participantId)}\n isSelf={\n !!currentParticipantId &&\n message.participantId === currentParticipantId\n }\n renderText={renderText}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n editable={editable}\n onMessageEdited={onMessageEdited}\n defaultCopyFormat={defaultCopyFormat}\n />\n </div>\n </div>\n );\n })}\n </div>\n </div>\n );\n}\n","/**\n * SuperChat — a single-conversation chat panel for `@mieweb/ui`.\n *\n * Renders one {@link SuperChatConversation}: header (title + participants +\n * optional close), a `role=\"log\"` message thread, and the compose box. Message\n * text renders through the pluggable Markdown pipeline\n * ({@link createMarkdownRenderer}); rich plugins (code/math/genui/…) are opt-in.\n *\n * For a conversation list use {@link SuperChatConversations}; for the combined\n * inbox (list + panel) use {@link SuperChatInbox}.\n */\n\nimport * as React from 'react';\nimport { cn } from '../../utils/cn';\nimport { CloseIcon } from '../AI/icons';\nimport { ChatComposer } from '../ChatComposer/ChatComposer';\nimport type { NewMessage } from '../Messaging/types';\nimport { createMarkdownRenderer } from './render/createMarkdownRenderer';\nimport {\n ParticipantAvatar,\n MessageRow,\n byTime,\n detectMentions,\n filesToComposerAttachments,\n acceptTokensFor,\n} from './parts';\nimport { VirtualThread } from './VirtualThread';\nimport type {\n AIRenderTextContent,\n AttachmentKind,\n ComposerAttachment,\n Participant,\n SuperChatConversation,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatRef,\n SuperChatRenderPlugin,\n} from './types';\n\n// ============================================================================\n// SuperChat (single-conversation panel)\n// ============================================================================\n\nexport interface SuperChatProps {\n /** The conversation to display (host-owned state). */\n conversation: SuperChatConversation;\n /** The participant id representing the local user (alignment + compose). */\n currentParticipantId?: string;\n /** Opt-in rich render plugins (code/math/genui/…). */\n renderPlugins?: SuperChatRenderPlugin[];\n /** Override the entire text renderer (advanced). */\n renderTextContent?: AIRenderTextContent;\n /** Treat content as trusted and skip sanitization (host-authored only). */\n trustedContent?: boolean;\n /** Disable the composer. */\n readOnly?: boolean;\n /**\n * File categories the composer accepts for paste, drag-and-drop, and the\n * file picker in the `+` → “Attach files” menu.\n * Defaults to `['image', 'video', 'audio', 'pdf']`.\n */\n acceptedFileTypes?: AttachmentKind[];\n /**\n * Thread ordering.\n * - `'asc'` (default): oldest → newest, anchored to the bottom like a\n * classic messenger (auto-scrolls to the newest message).\n * - `'desc'`: newest → oldest, anchored to the top like a social feed\n * (auto-scrolls to the top when a new message arrives).\n */\n order?: 'asc' | 'desc';\n /**\n * Virtualize the message thread (windowed rendering). Only the rows near the\n * viewport are mounted, so very long threads (hundreds to thousands of\n * messages) stay responsive. Off by default — enable for long histories.\n */\n virtualized?: boolean;\n /** Build hrefs for `ref` thread items. */\n linkBuilder?: SuperChatLinkBuilder;\n /**\n * Format for a message's default copy action (Ctrl/Cmd-click on the footer\n * copy button). All formats stay reachable per message via the copy menus.\n * Defaults to `'rich'`.\n */\n defaultCopyFormat?: SuperChatCopyFormat;\n /** Additional class name. */\n className?: string;\n\n // --- callbacks (chat-component-compatible) ---\n /**\n * Fired when the local user sends a message. If the callback returns a\n * promise it is awaited, and a rejected send restores the typed text into\n * the composer (the declared `void` return keeps every previously valid\n * callback assignable).\n */\n onMessageSent?: (\n text: string,\n meta: {\n conversation: SuperChatConversation;\n mentions: string[];\n attachments: ComposerAttachment[];\n }\n ) => void | Promise<void>;\n /**\n * Fired when the local user saves an edit to one of their own messages.\n * Providing this enables the inline \"Edit\" affordance on self-authored\n * messages (the host owns state, so apply the new `text` to the message and\n * typically stamp `editedAt`).\n */\n onMessageEdited?: (\n messageId: string,\n text: string,\n meta: { conversation: SuperChatConversation }\n ) => void;\n onConversationClosed?: (conversation: SuperChatConversation) => void;\n onReferenceClick?: (ref: SuperChatRef) => void;\n /**\n * Show a \"back\" affordance in the header (used by {@link SuperChatInbox} on\n * small screens to return from the chat panel to the conversation list).\n */\n onBack?: () => void;\n}\n\n/**\n * Single-conversation chat panel. See the module `MAINTAINERS.md` for the\n * participant model and render-plugin architecture.\n */\nexport function SuperChat({\n conversation,\n currentParticipantId,\n renderPlugins,\n renderTextContent,\n trustedContent,\n readOnly,\n acceptedFileTypes,\n order = 'asc',\n virtualized = false,\n linkBuilder,\n defaultCopyFormat,\n className,\n onMessageSent,\n onMessageEdited,\n onConversationClosed,\n onReferenceClick,\n onBack,\n}: SuperChatProps) {\n const headingId = React.useId();\n\n const renderText = React.useMemo<AIRenderTextContent>(\n () =>\n renderTextContent ??\n createMarkdownRenderer({\n plugins: renderPlugins,\n trusted: trustedContent,\n }),\n [renderTextContent, renderPlugins, trustedContent]\n );\n\n const threadRef = React.useRef<HTMLDivElement>(null);\n React.useEffect(() => {\n if (virtualized) return; // VirtualThread manages its own scroll anchoring.\n const el = threadRef.current;\n if (!el) return;\n // Anchor to the newest message: bottom for ascending order, top for\n // descending (feed-style) order.\n el.scrollTop = order === 'desc' ? 0 : el.scrollHeight;\n }, [conversation.thread.length, conversation.id, order, virtualized]);\n\n const participantById = React.useMemo(() => {\n const map = new Map<string, Participant>();\n conversation.participants.forEach((p) => map.set(p.id, p));\n return map;\n }, [conversation]);\n\n const orderedThread = React.useMemo(() => {\n const sorted = [...conversation.thread].sort(byTime);\n return order === 'desc' ? sorted.reverse() : sorted;\n }, [conversation, order]);\n\n // Stable edit handler so memoized rows don't re-render when the conversation\n // changes. Latest `onMessageEdited`/`conversation` are read from refs.\n const onMessageEditedRef = React.useRef(onMessageEdited);\n onMessageEditedRef.current = onMessageEdited;\n const conversationRef = React.useRef(conversation);\n conversationRef.current = conversation;\n const handleMessageEdited = React.useCallback(\n (messageId: string, text: string) => {\n onMessageEditedRef.current?.(messageId, text, {\n conversation: conversationRef.current,\n });\n },\n []\n );\n const editable = !readOnly && !!onMessageEdited;\n\n // Agents/humans addressable via `@` (exclude the system participant).\n const mentionOptions = React.useMemo(\n () =>\n conversation.participants\n .filter((p) => p.kind !== 'system')\n .map((p) => ({\n id: p.id,\n label: p.name,\n description: p.role,\n meta: p.kind,\n icon: <ParticipantAvatar participant={p} />,\n })),\n [conversation.participants]\n );\n\n const composerAccept = React.useMemo(\n () => acceptTokensFor(acceptedFileTypes),\n [acceptedFileTypes]\n );\n\n // Controlled composer draft so a failed send can restore the typed text\n // (ChatComposer clears optimistically and delegates restore to the host).\n const [draft, setDraft] = React.useState('');\n // Bumped on every user edit (including the optimistic clear that precedes\n // a send), so a stale failed send never overwrites newer typed input.\n const draftEpochRef = React.useRef(0);\n const handleDraftChange = React.useCallback((value: string) => {\n draftEpochRef.current += 1;\n setDraft(value);\n }, []);\n\n // Bridge the shared composer's `NewMessage` (File[] attachments) to\n // SuperChat's host callback (mentions + base64 `data:` URL attachments).\n const handleComposerSend = React.useCallback(\n async (message: NewMessage) => {\n const epoch = draftEpochRef.current;\n try {\n const text = message.content;\n const mentions = detectMentions(text, conversation.participants);\n const attachments = await filesToComposerAttachments(\n message.attachments ?? []\n );\n // The declared type is `void` for backward compatibility, but a\n // returned promise (e.g. an async host callback) is awaited so its\n // rejection follows the same restore path as a synchronous throw.\n await Promise.resolve(\n onMessageSent?.(text, { conversation, mentions, attachments })\n );\n } catch {\n // Parity with the previous MessageComposer: restore the text when\n // file conversion or the host callback fails (attachments are not\n // restaged, matching the old behavior) — unless the user has typed\n // a newer draft while this send was pending.\n if (draftEpochRef.current === epoch) {\n setDraft(message.content);\n }\n }\n },\n [conversation, onMessageSent]\n );\n\n return (\n <section\n data-slot=\"superchat\"\n role=\"group\"\n aria-labelledby={headingId}\n className={cn(\n 'flex min-w-0 flex-1 flex-col bg-white dark:bg-neutral-900',\n className\n )}\n >\n <header\n data-slot=\"superchat-header\"\n className=\"flex items-center justify-between gap-2 border-b border-neutral-200 p-3 dark:border-neutral-700\"\n >\n <div className=\"flex min-w-0 items-center gap-2\">\n {onBack && (\n <button\n type=\"button\"\n onClick={onBack}\n aria-label=\"Back to conversations\"\n className=\"-ms-1 shrink-0 rounded-md p-1 text-neutral-500 hover:bg-neutral-100 sm:hidden dark:text-neutral-300 dark:hover:bg-neutral-800\"\n >\n <svg\n viewBox=\"0 0 24 24\"\n width=\"20\"\n height=\"20\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"m15 18-6-6 6-6\" />\n </svg>\n </button>\n )}\n <div className=\"min-w-0\">\n <h2\n id={headingId}\n className=\"truncate text-sm font-semibold text-neutral-800 dark:text-neutral-100\"\n >\n {conversation.title}\n </h2>\n <div\n data-slot=\"superchat-participants\"\n role=\"group\"\n aria-label=\"Participants\"\n className=\"mt-0.5 flex items-center gap-1\"\n >\n {conversation.participants.slice(0, 6).map((p) => (\n <span key={p.id} role=\"img\" aria-label={p.name}>\n <ParticipantAvatar participant={p} />\n </span>\n ))}\n </div>\n </div>\n </div>\n {onConversationClosed && (\n <button\n type=\"button\"\n onClick={() => onConversationClosed(conversation)}\n aria-label=\"Close conversation\"\n className=\"rounded-md p-1 text-neutral-400 hover:bg-neutral-100 dark:hover:bg-neutral-800\"\n >\n <CloseIcon />\n </button>\n )}\n </header>\n\n {virtualized ? (\n <VirtualThread\n items={orderedThread}\n participantById={participantById}\n currentParticipantId={currentParticipantId}\n renderText={renderText}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n editable={editable}\n onMessageEdited={handleMessageEdited}\n defaultCopyFormat={defaultCopyFormat}\n order={order}\n conversationId={conversation.id}\n containerProps={{\n 'data-slot': 'superchat-thread',\n role: 'log',\n 'aria-label': 'Messages',\n 'aria-live': 'polite',\n // Focusable so keyboard-only users can scroll the message history.\n tabIndex: 0,\n className: 'flex-1 overflow-y-auto p-4',\n }}\n />\n ) : (\n <div\n data-slot=\"superchat-thread\"\n ref={threadRef}\n role=\"log\"\n aria-label=\"Messages\"\n aria-live=\"polite\"\n // Focusable so keyboard-only users can scroll the message history.\n // eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex\n tabIndex={0}\n className=\"flex-1 space-y-4 overflow-y-auto p-4\"\n >\n {orderedThread.map((m) => (\n <MessageRow\n key={m.id}\n message={m}\n participant={participantById.get(m.participantId)}\n isSelf={\n !!currentParticipantId &&\n m.participantId === currentParticipantId\n }\n renderText={renderText}\n linkBuilder={linkBuilder}\n onReferenceClick={onReferenceClick}\n editable={editable}\n onMessageEdited={handleMessageEdited}\n defaultCopyFormat={defaultCopyFormat}\n />\n ))}\n </div>\n )}\n\n <ChatComposer\n value={draft}\n onValueChange={handleDraftChange}\n onSend={handleComposerSend}\n disabled={readOnly}\n placeholder={\n readOnly\n ? 'Read-only conversation'\n : 'Type a message… use @ to address an agent'\n }\n mentionOptions={mentionOptions}\n allowAttachments={!readOnly}\n acceptedFileTypes={composerAccept}\n // Same cap MessageComposer applied by default.\n maxFileSize={25 * 1024 * 1024}\n maxLength={100000}\n inputLabel=\"Message\"\n />\n </section>\n );\n}\n","/**\n * SuperChatConversations — the conversation list (inbox sidebar) for\n * `@mieweb/ui`.\n *\n * Renders the host-owned conversations sorted by last activity, with unread\n * badges and an optional \"new conversation\" action. Supports both controlled\n * (`activeConversationId`) and uncontrolled (`defaultActiveConversationId`)\n * selection. Pair with {@link SuperChat} for the message panel, or use\n * {@link SuperChatInbox} for the combined surface.\n */\n\nimport * as React from 'react';\nimport { cn } from '../../utils/cn';\nimport { sidebarItem, lastActivityOf, lastMessageByTime } from './parts';\nimport type { SuperChatConversation } from './types';\n\n// ============================================================================\n// SuperChatConversations (conversation list)\n// ============================================================================\n\nexport interface SuperChatConversationsProps {\n /** All conversations (host-owned state). */\n conversations: SuperChatConversation[];\n /** Controlled active conversation id. */\n activeConversationId?: string;\n /** Uncontrolled initial active conversation id. */\n defaultActiveConversationId?: string;\n /** Additional class name. */\n className?: string;\n\n // --- callbacks ---\n onConversationOpened?: (conversation: SuperChatConversation) => void;\n onNewConversation?: () => void;\n}\n\n/**\n * Conversation list. See the module `MAINTAINERS.md` for the data model.\n */\nexport function SuperChatConversations({\n conversations,\n activeConversationId,\n defaultActiveConversationId,\n className,\n onConversationOpened,\n onNewConversation,\n}: SuperChatConversationsProps) {\n const [internalActive, setInternalActive] = React.useState(\n defaultActiveConversationId ?? conversations[0]?.id\n );\n const requestedId = activeConversationId ?? internalActive;\n // Fall back to the first conversation when the requested id no longer exists\n // (e.g. the active conversation was removed) so an item stays highlighted.\n const activeId = conversations.some((c) => c.id === requestedId)\n ? requestedId\n : conversations[0]?.id;\n\n const sortedConversations = React.useMemo(\n () =>\n [...conversations].sort((a, b) => lastActivityOf(b) - lastActivityOf(a)),\n [conversations]\n );\n\n const selectConversation = (c: SuperChatConversation) => {\n if (activeConversationId === undefined) setInternalActive(c.id);\n onConversationOpened?.(c);\n };\n\n return (\n <aside\n data-slot=\"superchat-conversations\"\n aria-label=\"Conversations\"\n className={cn(\n 'flex w-64 shrink-0 flex-col border-e border-neutral-200 dark:border-neutral-700',\n className\n )}\n >\n <div className=\"flex items-center justify-between p-3\">\n <span className=\"text-sm font-semibold text-neutral-700 dark:text-neutral-200\">\n Conversations\n </span>\n {onNewConversation && (\n <button\n type=\"button\"\n onClick={onNewConversation}\n aria-label=\"New conversation\"\n className=\"rounded-md px-2 py-1 text-lg leading-none text-neutral-500 hover:bg-neutral-100 dark:hover:bg-neutral-800\"\n >\n +\n </button>\n )}\n </div>\n <div\n data-slot=\"superchat-conversation-list\"\n role=\"list\"\n className=\"flex-1 space-y-1 overflow-y-auto px-2 pb-2\"\n >\n {sortedConversations.map((c) => {\n const last = lastMessageByTime(c.thread);\n const isActive = c.id === activeId;\n return (\n <div key={c.id} role=\"listitem\">\n <button\n type=\"button\"\n aria-current={isActive ? 'true' : undefined}\n onClick={() => selectConversation(c)}\n className={sidebarItem({ active: isActive })}\n >\n <span className=\"flex-1 truncate\">\n <span className=\"block truncate font-medium\">{c.title}</span>\n {last?.text && (\n <span className=\"block truncate text-xs text-neutral-600 dark:text-neutral-400\">\n {last.text}\n </span>\n )}\n </span>\n {!!c.unread && (\n <span className=\"bg-primary-600 ms-1 inline-flex h-5 min-w-5 items-center justify-center rounded-full px-1.5 text-[10px] font-semibold text-white\">\n {c.unread}\n <span className=\"sr-only\"> unread messages</span>\n </span>\n )}\n </button>\n </div>\n );\n })}\n </div>\n </aside>\n );\n}\n","/**\n * SuperChatInbox — the combined inbox surface for `@mieweb/ui`.\n *\n * Composes {@link SuperChatConversations} (the list) and {@link SuperChat} (the\n * single-conversation panel) into one framed surface. Owns active-conversation\n * coordination and supports both controlled (`activeConversationId`) and\n * uncontrolled (`defaultActiveConversationId`) selection.\n *\n * This is the drop-in equivalent of the original monolithic `SuperChat`: it\n * accepts the same props (conversations array + callbacks).\n */\n\nimport * as React from 'react';\nimport { cn } from '../../utils/cn';\nimport { SuperChat } from './SuperChat';\nimport { SuperChatConversations } from './SuperChatConversations';\nimport type {\n AIRenderTextContent,\n AttachmentKind,\n ComposerAttachment,\n SuperChatConversation,\n SuperChatCopyFormat,\n SuperChatLinkBuilder,\n SuperChatRef,\n SuperChatRenderPlugin,\n} from './types';\n\n// ============================================================================\n// SuperChatInbox (list + panel)\n// ============================================================================\n\nexport interface SuperChatInboxProps {\n /** All conversations (host-owned state). */\n conversations: SuperChatConversation[];\n /** Controlled active conversation id. */\n activeConversationId?: string;\n /** Uncontrolled initial active conversation id. */\n defaultActiveConversationId?: string;\n /** The participant id representing the local user (alignment + compose). */\n currentParticipantId?: string;\n /** Opt-in rich render plugins (code/math/genui/…). */\n renderPlugins?: SuperChatRenderPlugin[];\n /** Override the entire text renderer (advanced). */\n renderTextContent?: AIRenderTextContent;\n /** Treat content as trusted and skip sanitization (host-authored only). */\n trustedContent?: boolean;\n /** Disable the composer. */\n readOnly?: boolean;\n /**\n * File categories the composer accepts for paste, drag-and-drop, and the\n * file picker in the `+` → “Attach files” menu.\n * Defaults to `['image', 'video', 'audio', 'pdf']`.\n */\n acceptedFileTypes?: AttachmentKind[];\n /** Thread ordering: `'asc'` (oldest→newest, default) or `'desc'` (feed-style). */\n order?: 'asc' | 'desc';\n /** Virtualize the message thread (windowed rendering) for long histories. */\n virtualized?: boolean;\n /** Show the conversation sidebar. */\n showSidebar?: boolean;\n /** Build hrefs for `ref` thread items. */\n linkBuilder?: SuperChatLinkBuilder;\n /** Format for a message's default copy action (Ctrl/Cmd-click on copy). */\n defaultCopyFormat?: SuperChatCopyFormat;\n /** Additional class name. */\n className?: string;\n\n // --- callbacks (chat-component-compatible) ---\n /**\n * Fired when the local user sends a message. If the callback returns a\n * promise it is awaited, and a rejected send restores the typed text into\n * the composer (same contract as {@link SuperChatProps.onMessageSent}).\n */\n onMessageSent?: (\n text: string,\n meta: {\n conversation: SuperChatConversation;\n mentions: string[];\n attachments: ComposerAttachment[];\n }\n ) => void;\n /** Fired when the local user saves an edit to one of their own messages. */\n onMessageEdited?: (\n messageId: string,\n text: string,\n meta: { conversation: SuperChatConversation }\n ) => void;\n onConversationOpened?: (conversation: SuperChatConversation) => void;\n onConversationClosed?: (conversation: SuperChatConversation) => void;\n onNewConversation?: () => void;\n onReferenceClick?: (ref: SuperChatRef) => void;\n}\n\n/**\n * Combined inbox surface (conversation list + active conversation panel). See\n * the module `MAINTAINERS.md` for the participant model and render-plugin\n * architecture.\n */\nexport function SuperChatInbox({\n conversations,\n activeConversationId,\n defaultActiveConversationId,\n currentParticipantId,\n renderPlugins,\n renderTextContent,\n trustedContent,\n readOnly,\n acceptedFileTypes,\n order,\n virtualized,\n showSidebar = true,\n linkBuilder,\n defaultCopyFormat,\n className,\n onMessageSent,\n onMessageEdited,\n onConversationOpened,\n onConversationClosed,\n onNewConversation,\n onReferenceClick,\n}: SuperChatInboxProps) {\n const [internalActive, setInternalActive] = React.useState(\n defaultActiveConversationId ?? conversations[0]?.id\n );\n const requestedId = activeConversationId ?? internalActive;\n const active =\n conversations.find((c) => c.id === requestedId) ?? conversations[0];\n // Resolve the active id from the conversation actually shown so the sidebar\n // highlight never disagrees with the panel when `conversations` changes.\n const activeId = active?.id;\n\n // On small screens the list and panel can't fit side by side, so we show one\n // at a time (master-detail). `mobileView` tracks which is visible; on `sm`+\n // both are always shown and this state is ignored.\n const [mobileView, setMobileView] = React.useState<'list' | 'chat'>('list');\n\n const handleOpen = (c: SuperChatConversation) => {\n if (activeConversationId === undefined) setInternalActive(c.id);\n setMobileView('chat');\n onConversationOpened?.(c);\n };\n\n return (\n <div\n data-slot=\"superchat-inbox\"\n role=\"group\"\n aria-label={active ? `Chat: ${active.title}` : 'Chat'}\n className={cn(\n 'flex h-full overflow-hidden rounded-xl border border-neutral-200 bg-white dark:border-neutral-700 dark:bg-neutral-900',\n className\n )}\n >\n {showSidebar && (\n <SuperChatConversations\n conversations={conversations}\n activeConversationId={activeId}\n onConversationOpened={handleOpen}\n onNewConversation={onNewConversation}\n className={cn(\n 'w-full sm:w-64',\n mobileView === 'chat' && 'hidden sm:flex'\n )}\n />\n )}\n\n {active ? (\n <SuperChat\n conversation={active}\n currentParticipantId={currentParticipantId}\n renderPlugins={renderPlugins}\n renderTextContent={renderTextContent}\n trustedContent={trustedContent}\n readOnly={readOnly}\n acceptedFileTypes={acceptedFileTypes}\n order={order}\n virtualized={virtualized}\n linkBuilder={linkBuilder}\n defaultCopyFormat={defaultCopyFormat}\n onMessageSent={onMessageSent}\n onMessageEdited={onMessageEdited}\n onConversationClosed={onConversationClosed}\n onReferenceClick={onReferenceClick}\n onBack={showSidebar ? () => setMobileView('list') : undefined}\n className={cn(\n showSidebar && mobileView === 'list' && 'hidden sm:flex'\n )}\n />\n ) : (\n <section\n data-slot=\"superchat\"\n className={cn(\n 'min-w-0 flex-1 items-center justify-center text-sm text-neutral-400',\n showSidebar && mobileView === 'list' ? 'hidden sm:flex' : 'flex'\n )}\n >\n No conversation selected\n </section>\n )}\n </div>\n );\n}\n"]}