composeai 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +168 -262
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +168 -262
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/composer.css +1163 -9
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/insertText.ts","../src/internal/cn.ts","../src/internal/color.ts","../src/internal/sx.ts","../src/internal/icons.tsx","../src/core/ComposerProvider.tsx","../src/core/EditorShell.tsx","../src/core/theme.ts","../src/core/nodes/MentionNode.tsx","../src/core/nodes/MarkdownTokenNode.ts","../src/core/nodes/BlockParagraphNode.ts","../src/core/nodes/LinkTextNode.ts","../src/plugins/markdown-blocks.ts","../src/core/serializer.ts","../src/plugins/KeyboardPlugin.tsx","../src/internal/focusEditor.ts","../src/plugins/AutoFocusPlugin.tsx","../src/plugins/PasteDropPlugin.tsx","../src/plugins/markdown-tokenizer.ts","../src/plugins/MarkdownPlugin.tsx","../src/internal/Portal.tsx","../src/ui/ImageLightbox.tsx","../src/plugins/MermaidPlugin.tsx","../src/ui/SlashMenu.tsx","../src/ui/SmartPopover.tsx","../src/hooks/useOutsideClickDismiss.ts","../src/plugins/SlashCommandPlugin.tsx","../src/internal/Avatar.tsx","../src/ui/MentionMenu.tsx","../src/plugins/MentionPlugin.tsx","../src/plugins/GhostedAutoCompletePlugin.tsx","../src/ui/AttachmentChip.tsx","../src/plugins/AttachmentTray.tsx","../src/internal/Tooltip.tsx","../src/plugins/VoicePlugin.tsx","../src/ui/AttachmentTypePicker.tsx","../src/ui/Toolbar.tsx","../src/ui/SendButton.tsx","../src/ui/HintBar.tsx","../src/ui/QuickPrompts.tsx","../src/hooks/useComposerHandle.ts","../src/internal/shortcut.ts","../src/Composer.tsx","../src/ui/SuggestionRow.tsx"],"names":["$getSelection","$isRangeSelection","$getRoot","$createParagraphNode","$createTextNode","jsx","jsxs","Fragment","createContext","useMemo","useState","useRef","useCallback","useContext","ContentEditable","RichTextPlugin","LexicalErrorBoundary","PlainTextPlugin","HistoryPlugin","ElementNode","$applyNodeReplacement","TextNode","addClassNamesToElement","ParagraphNode","$isParagraphNode","$isElementNode","$isLineBreakNode","$isTextNode","offset","useLexicalComposerContext","useEffect","KEY_ENTER_COMMAND","COMMAND_PRIORITY_HIGH","PASTE_COMMAND","KEY_BACKSPACE_COMMAND","COMMAND_PRIORITY_LOW","createPortal","useLayoutEffect","KEY_ESCAPE_COMMAND","MenuOption","useBasicTypeaheadTriggerMatch","LexicalTypeaheadMenuPlugin","isSyncItems","KEY_TAB_COMMAND","chip","useId","isValidElement","cloneElement","forwardRef","Composer","LexicalComposer"],"mappings":";;;;;;;;;;;;;;;;AAgCA,SAAS,UAAU,IAAA,EAAsB;AACvC,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,QAAA,EAAU,IAAI,CAAA;AACpC;AASO,SAAS,+BAA+B,IAAA,EAAoB;AACjE,EAAA,MAAM,KAAA,GAAQ,SAAA,CAAU,IAAI,CAAA,CAAE,MAAM,IAAI,CAAA;AAExC,EAAA,MAAM,UAAU,MAA6B;AAC3C,IAAA,MAAM,IAAIA,qBAAA,EAAc;AACxB,IAAA,OAAOC,yBAAA,CAAkB,CAAC,CAAA,GAAI,CAAA,GAAI,IAAA;AAAA,EACpC,CAAA;AAEA,EAAA,IAAI,MAAM,OAAA,EAAQ;AAClB,EAAA,IAAI,CAAC,GAAA,EAAK;AAKR,IAAA,MAAM,OAAOC,gBAAA,EAAS;AACtB,IAAA,MAAM,IAAA,GAAO,KAAK,YAAA,EAAa;AAC/B,IAAA,IAAI,QAAQ,WAAA,IAAe,IAAA,IAAQ,OAAO,IAAA,CAAK,cAAc,UAAA,EAAY;AACvE,MAAC,KAAmC,SAAA,EAAU;AAAA,IAChD,CAAA,MAAO;AACL,MAAA,IAAA,CAAK,SAAA,EAAU;A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EAAQ,SAAS,QAAA,EAAU,CAAA;AAAA,IAC/D,SAAS,mBAAA,oBACRA,eAAC,yBAAA,EAAA,EAA0B,MAAA,EAAQ,SAAS,mBAAA,EAAqB;AAAA,GAAA,EAErE,CAAA;AAEJ;AAEA,SAAS,WAAA,GAAc;AACrB,EAAA,MAAM,EAAE,QAAA,EAAU,IAAA,EAAK,GAAI,kBAAA,EAAmB;AAC9C,EAAA,IAAI,IAAA,KAAS,UAAA,IAAc,CAAC,QAAA,CAAS,SAAS,OAAO,IAAA;AACrD,EAAA,uBAAOA,eAAC,aAAA,EAAA,EAAc,CAAA;AACxB;AC/fO,SAAS,aAAA,CAAc,EAAE,KAAA,EAAO,QAAA,EAAU,WAAU,EAAuB;AAChF,EAAA,MAAM,EAAE,KAAA,EAAM,GAAI,kBAAA,EAAmB;AACrC,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAY,GAAI,KAAA;AACjC,EAAA,uBACEA,cAAAA,CAAC,KAAA,EAAA,EAAI,SAAA,EAAW,EAAA,CAAG,qCAAA,EAAuC,SAAS,CAAA,EAChE,QAAA,EAAA,KAAA,CAAM,GAAA,CAAI,CAAC,CAAA,qBACVC,eAAAA;AAAA,IAAC,QAAA;AAAA,IAAA;AAAA,MAEC,IAAA,EAAK,QAAA;AAAA,MACL,OAAA,EAAS,MAAM,QAAA,CAAS,CAAC,CAAA;AAAA,MACzB,SAAA,EAAU,gQAAA;AAAA,MAEV,QAAA,EAAA;AAAA,wBAAAD,cAAAA,CAAC,WAAA,EAAA,EAAY,SAAA,EAAU,yDAAA,EAA0D,CAAA;AAAA,QAChF;AAAA;AAAA,KAAA;AAAA,IANI;AAAA,GAQR,CAAA,EACH,CAAA;AAEJ","file":"index.cjs","sourcesContent":["/**\n * Helpers for inserting/seeding multi-line text into the editor.\n *\n * Why this exists:\n * The Slack-style markdown detector in `markdown-blocks.ts` operates on a\n * per-paragraph basis (each `ParagraphNode` IS one block: heading, quote,\n * code-line, etc.) and uses regexes anchored to the start AND end of the\n * paragraph's text. So multi-line text needs to live as multiple sibling\n * paragraphs for fence detection (and headings, lists, etc.) to work.\n *\n * By default, Lexical's text-paste / `selection.insertText` / our previous\n * `initialValue` seeding all stuffed multi-line content into a single\n * paragraph (with `LineBreakNode` children, or with embedded `\\n` chars).\n * That meant pasting or seeding a ```mermaid block silently produced no\n * diagram, because the fence never matched.\n *\n * These helpers convert each `\\n` into a real paragraph break so the\n * detector sees what it needs to see.\n *\n * All `$`-prefixed functions MUST be called inside an `editor.update(...)`\n * (or `getEditorState().read(...)` where noted) scope.\n */\nimport {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n type RangeSelection,\n} from \"lexical\";\n\n/** Normalize CRLF / CR to LF so we never end up with stray `\\r` in nodes. */\nfunction normalize(text: string): string {\n return text.replace(/\\r\\n?/g, \"\\n\");\n}\n\n/**\n * Insert `text` at the current selection. Each `\\n` becomes a paragraph\n * break (via `selection.insertParagraph()`). Single-line input is a plain\n * `insertText` — no extra paragraph splitting.\n *\n * The caller must be inside an `editor.update(...)` scope.\n */\nexport function $insertTextWithParagraphBreaks(text: string): void {\n const lines = normalize(text).split(\"\\n\");\n\n const current = (): RangeSelection | null => {\n const s = $getSelection();\n return $isRangeSelection(s) ? s : null;\n };\n\n let sel = current();\n if (!sel) {\n // No live selection — typically because the editor has never been\n // focused (auto-demos, scripted ref.insert() calls, restoring drafts\n // before mount, etc.). Drop a caret at the end of the document so the\n // text actually lands somewhere instead of being silently swallowed.\n const root = $getRoot();\n const last = root.getLastChild();\n if (last && \"selectEnd\" in last && typeof last.selectEnd === \"function\") {\n (last as { selectEnd: () => void }).selectEnd();\n } else {\n root.selectEnd();\n }\n sel = current();\n if (!sel) return;\n }\n\n // Replace any currently-selected range before inserting.\n if (!sel.isCollapsed()) {\n sel.removeText();\n sel = current();\n if (!sel) return;\n }\n\n for (let i = 0; i < lines.length; i++) {\n if (i > 0) {\n sel.insertParagraph();\n sel = current();\n if (!sel) return;\n }\n if (lines[i].length > 0) {\n sel.insertText(lines[i]);\n sel = current();\n if (!sel) return;\n }\n }\n}\n\n/**\n * Seed the editor root with `text`, one `ParagraphNode` per `\\n`-delimited\n * line. Clears any existing content first. Used by `<Composer initialValue>`.\n *\n * Leaves the caret at the end of the seeded content so that subsequent\n * imperative `insert()` calls (which delegate to\n * `$insertTextWithParagraphBreaks`) land where the user / script expects.\n * Without this, a never-focused editor would silently swallow follow-up\n * inserts because `$getSelection()` returns null.\n *\n * The caller must be inside an `editor.update(...)` scope.\n */\nexport function $seedInitialValue(text: string): void {\n const root = $getRoot();\n root.clear();\n const lines = normalize(text).split(\"\\n\");\n if (lines.length === 0) {\n const para = $createParagraphNode();\n root.append(para);\n para.selectEnd();\n return;\n }\n let last: ReturnType<typeof $createParagraphNode> | null = null;\n for (const line of lines) {\n const para = $createParagraphNode();\n if (line.length > 0) para.append($createTextNode(line));\n root.append(para);\n last = para;\n }\n last?.selectEnd();\n}","/**\n * Tiny class-name combiner used internally by the composer.\n *\n * Replacement for `clsx` + `tailwind-merge`. We don't need full Tailwind\n * conflict-resolution because the composer ships plain CSS — utility-class\n * collisions are vanishingly rare inside the library. Last-wins via natural\n * CSS cascade order is sufficient.\n *\n * Accepts the same loose shapes `clsx` did:\n * - string → included if truthy\n * - number → converted to string\n * - false / null / undefined / 0 → dropped\n * - array → flattened recursively\n * - object → keys whose values are truthy are included\n */\nexport type ClassValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ClassValue[]\n | { [key: string]: unknown };\n\nexport function cn(...inputs: ClassValue[]): string {\n const out: string[] = [];\n walk(inputs, out);\n return out.join(\" \");\n}\n\nfunction walk(value: ClassValue, out: string[]): void {\n if (!value) return;\n if (typeof value === \"string\") {\n if (value.length > 0) out.push(value);\n return;\n }\n if (typeof value === \"number\") {\n out.push(String(value));\n return;\n }\n if (Array.isArray(value)) {\n for (const v of value) walk(v, out);\n return;\n }\n if (typeof value === \"object\") {\n for (const key in value) {\n if (value[key]) out.push(key);\n }\n }\n}","/**\n * Tiny color parser used by the `<Composer color=\"…\" />` shorthand.\n *\n * The composer's CSS variables store HSL components without the `hsl(...)`\n * wrapper — e.g. `--primary: 258 90% 62%` — so opacity composition like\n * `hsl(var(--primary) / 0.1)` keeps working. This helper accepts whatever\n * the consumer hands us (hex, rgb, hsl, or already-formatted components)\n * and normalises it to that shape.\n *\n * Returns `null` for inputs we can't parse — the caller silently falls\n * back to the default theme rather than throwing on a typo.\n */\nexport interface HslTriple {\n h: number;\n s: number;\n l: number;\n}\n\nconst COMPONENT_RE =\n /^\\s*(\\d+(?:\\.\\d+)?)\\s+(\\d+(?:\\.\\d+)?)%\\s+(\\d+(?:\\.\\d+)?)%\\s*$/;\nconst HSL_FN_RE =\n /^\\s*hsla?\\(\\s*(\\d+(?:\\.\\d+)?)(?:deg)?\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)%\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)%/i;\nconst HEX_RE = /^\\s*#([0-9a-f]{3}|[0-9a-f]{6})\\s*$/i;\nconst RGB_FN_RE =\n /^\\s*rgba?\\(\\s*(\\d+(?:\\.\\d+)?)\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)/i;\n\nexport function parseToHsl(value: string): HslTriple | null {\n if (typeof value !== \"string\") return null;\n\n const components = value.match(COMPONENT_RE);\n if (components) {\n return {\n h: parseFloat(components[1]),\n s: parseFloat(components[2]),\n l: parseFloat(components[3]),\n };\n }\n\n const hslFn = value.match(HSL_FN_RE);\n if (hslFn) {\n return {\n h: parseFloat(hslFn[1]),\n s: parseFloat(hslFn[2]),\n l: parseFloat(hslFn[3]),\n };\n }\n\n const hex = value.match(HEX_RE);\n if (hex) {\n let h = hex[1];\n if (h.length === 3) {\n h = h\n .split(\"\")\n .map((c) => c + c)\n .join(\"\");\n }\n const r = parseInt(h.slice(0, 2), 16) / 255;\n const g = parseInt(h.slice(2, 4), 16) / 255;\n const b = parseInt(h.slice(4, 6), 16) / 255;\n return rgbToHsl(r, g, b);\n }\n\n const rgbFn = value.match(RGB_FN_RE);\n if (rgbFn) {\n return rgbToHsl(\n clamp01(parseFloat(rgbFn[1]) / 255),\n clamp01(parseFloat(rgbFn[2]) / 255),\n clamp01(parseFloat(rgbFn[3]) / 255),\n );\n }\n\n return null;\n}\n\nfunction clamp01(n: number): number {\n return Math.min(1, Math.max(0, n));\n}\n\nfunction clampPct(n: number): number {\n return Math.min(100, Math.max(0, n));\n}\n\nfunction rgbToHsl(r: number, g: number, b: number): HslTriple {\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n let h = 0;\n let s = 0;\n if (max !== min) {\n const d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n return {\n h: Math.round(h * 360),\n s: Math.round(s * 100),\n l: Math.round(l * 100),\n };\n}\n\n/** Format an HslTriple as the components-only string the composer's CSS expects. */\nexport function formatHslComponents(triple: HslTriple): string {\n return `${triple.h} ${triple.s}% ${triple.l}%`;\n}\n\n/**\n * Derive the full set of brand-coloured tokens from a single base color.\n *\n * Mapping rules — chosen so the brand color tints every \"live\" surface\n * without making text unreadable:\n *\n * --primary = base (web pill, mention chip, focus ring, mention avatar text)\n * --primary-foreground = base with very high/low L (text painted on top of --primary fills)\n * --accent = base hue, soft saturation, very light L (hover bg, selected menu row bg)\n * --accent-foreground = base hue, normal saturation, dark L (text on --accent surfaces)\n * --ring = base\n *\n * Other tokens (`--card`, `--background`, `--border`, …) are deliberately\n * left alone so the composer keeps its neutral chrome and only the hot\n * colour-bearing surfaces light up.\n */\nexport interface DerivedColorTokens {\n primary: string;\n primaryForeground: string;\n accent: string;\n accentForeground: string;\n ring: string;\n}\n\nexport function deriveColorTokens(value: string): DerivedColorTokens | null {\n const base = parseToHsl(value);\n if (!base) return null;\n\n const isLightBase = base.l >= 50;\n\n const primary = formatHslComponents(base);\n\n // Foreground sitting on top of `--primary`: pick the opposite end of the\n // lightness scale so contrast stays high regardless of where the brand\n // sits on the spectrum.\n const primaryForeground = formatHslComponents({\n h: base.h,\n s: Math.min(base.s, 30),\n l: isLightBase ? 10 : 98,\n });\n\n // Hover/selected backgrounds want a soft tint of the brand colour. Drop\n // saturation a touch so it doesn't fight the editor text.\n const accent = formatHslComponents({\n h: base.h,\n s: clampPct(Math.min(base.s, 70)),\n l: 95,\n });\n\n // Text on `--accent`: same hue, full saturation, sit it deep enough that\n // it reads cleanly on the soft tinted bg above.\n const accentForeground = formatHslComponents({\n h: base.h,\n s: clampPct(Math.max(base.s, 40)),\n l: 30,\n });\n\n return {\n primary,\n primaryForeground,\n accent,\n accentForeground,\n ring: primary,\n };\n}","/**\n * Lightweight `sx` engine for `<Composer />`.\n *\n * Goals:\n * - Zero dependencies. No emotion, no runtime CSS-in-JS.\n * - Predictable: an `sx` object is just a `React.CSSProperties` with a\n * handful of token-aware shortcuts. Anything we don't recognise is\n * passed through verbatim.\n *\n * We deliberately do NOT support:\n * - Pseudo selectors (`&:hover`, `&:focus-within`).\n * - Media queries.\n * - Responsive arrays (`[1, 2, 3]`).\n *\n * Consumers reach for {@link ComposerSlotClassNames} when those are\n * needed — that keeps the package's bundle small and the inline-style\n * surface area small enough to reason about.\n */\nimport type { CSSProperties } from \"react\";\nimport { cn, type ClassValue } from \"./cn\";\nimport type {\n ComposerSlot,\n ComposerSlotClassNames,\n ComposerSxMap,\n ComposerSxValue,\n ComposerTokens,\n} from \"../types\";\n\n/**\n * Token names recognised by the sx engine for color-bearing keys. They\n * mirror the CSS variables defined by the consumer's theme (and shipped in\n * `package/src/composer.css`).\n */\nconst COLOR_TOKENS: Readonly<Record<string, string>> = {\n primary: \"var(--primary)\",\n \"primary-foreground\": \"var(--primary-foreground)\",\n primaryForeground: \"var(--primary-foreground)\",\n accent: \"var(--accent)\",\n \"accent-foreground\": \"var(--accent-foreground)\",\n accentForeground: \"var(--accent-foreground)\",\n background: \"var(--background)\",\n foreground: \"var(--foreground)\",\n card: \"var(--card)\",\n \"card-foreground\": \"var(--card-foreground)\",\n cardForeground: \"var(--card-foreground)\",\n popover: \"var(--popover)\",\n \"popover-foreground\": \"var(--popover-foreground)\",\n popoverForeground: \"var(--popover-foreground)\",\n muted: \"var(--muted)\",\n \"muted-foreground\": \"var(--muted-foreground)\",\n mutedForeground: \"var(--muted-foreground)\",\n border: \"var(--border)\",\n ring: \"var(--ring)\",\n input: \"var(--input)\",\n destructive: \"var(--destructive)\",\n \"destructive-foreground\": \"var(--destructive-foreground)\",\n destructiveForeground: \"var(--destructive-foreground)\",\n success: \"var(--success)\",\n \"success-foreground\": \"var(--success-foreground)\",\n successForeground: \"var(--success-foreground)\",\n warning: \"var(--warning)\",\n \"warning-foreground\": \"var(--warning-foreground)\",\n warningForeground: \"var(--warning-foreground)\",\n};\n\n/** CSS keys we treat as color-bearing — token names expand to `hsl(var(--x))`. */\nconst COLOR_KEYS = new Set<string>([\n \"color\",\n \"backgroundColor\",\n \"borderColor\",\n \"borderTopColor\",\n \"borderRightColor\",\n \"borderBottomColor\",\n \"borderLeftColor\",\n \"outlineColor\",\n \"fill\",\n \"stroke\",\n \"caretColor\",\n \"textDecorationColor\",\n]);\n\nfunction expandColor(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n // Anything that already looks like a CSS color (`#`, `rgb`, `hsl`,\n // `var(`, `transparent`, `currentColor`, etc.) passes straight through.\n const tokenVar = COLOR_TOKENS[trimmed];\n if (!tokenVar) return value;\n return `hsl(${tokenVar})`;\n}\n\n/**\n * Convert an {@link ComposerSxValue} to a plain {@link CSSProperties}\n * object. Returns `undefined` when the input is empty so callers can\n * cheaply skip merging.\n */\nexport function resolveSx(value?: ComposerSxValue): CSSProperties | undefined {\n if (!value) return undefined;\n const out: Record<string, unknown> = {};\n for (const key in value) {\n const raw = (value as Record<string, unknown>)[key];\n if (raw === undefined) continue;\n\n // `bg` shorthand → backgroundColor.\n if (key === \"bg\") {\n out.backgroundColor = expandColor(raw);\n continue;\n }\n\n if (COLOR_KEYS.has(key)) {\n out[key] = expandColor(raw);\n continue;\n }\n\n out[key] = raw;\n }\n return out as CSSProperties;\n}\n\ninterface SlotProps {\n className: string;\n style?: CSSProperties;\n}\n\n/**\n * Build the `{ className, style }` overlay for a given slot, given the\n * consumer-supplied per-slot maps. The `base` argument is whatever the\n * package itself wants to apply (utility classes, internal styles); both\n * the consumer's class and resolved sx are layered on top.\n */\nexport function slotProps(\n slot: ComposerSlot,\n base: ClassValue,\n classNames?: ComposerSlotClassNames,\n sx?: ComposerSxMap,\n baseStyle?: CSSProperties,\n): SlotProps {\n const className = cn(base, classNames?.[slot]);\n const resolved = resolveSx(sx?.[slot]);\n if (!resolved && !baseStyle) {\n return { className };\n }\n return {\n className,\n style: { ...baseStyle, ...resolved },\n };\n}\n\nconst COLOR_TOKEN_KEYS: ReadonlyArray<keyof ComposerTokens> = [\n \"primary\",\n \"primaryForeground\",\n \"accent\",\n \"accentForeground\",\n \"background\",\n \"foreground\",\n \"card\",\n \"cardForeground\",\n \"popover\",\n \"popoverForeground\",\n \"muted\",\n \"mutedForeground\",\n \"border\",\n \"ring\",\n \"input\",\n \"destructive\",\n \"destructiveForeground\",\n \"success\",\n \"successForeground\",\n \"warning\",\n \"warningForeground\",\n];\n\nconst COLOR_TOKEN_VAR: Record<string, string> = {\n primary: \"--primary\",\n primaryForeground: \"--primary-foreground\",\n accent: \"--accent\",\n accentForeground: \"--accent-foreground\",\n background: \"--background\",\n foreground: \"--foreground\",\n card: \"--card\",\n cardForeground: \"--card-foreground\",\n popover: \"--popover\",\n popoverForeground: \"--popover-foreground\",\n muted: \"--muted\",\n mutedForeground: \"--muted-foreground\",\n border: \"--border\",\n ring: \"--ring\",\n input: \"--input\",\n destructive: \"--destructive\",\n destructiveForeground: \"--destructive-foreground\",\n success: \"--success\",\n successForeground: \"--success-foreground\",\n warning: \"--warning\",\n warningForeground: \"--warning-foreground\",\n};\n\nfunction asLength(value: number | string): string {\n return typeof value === \"number\" ? `${value}px` : value;\n}\n\n/**\n * Convert a {@link ComposerTokens} map into a `style` object of CSS\n * custom properties suitable for inlining on the composer root. Every\n * `--*` here is read either by the package's CSS or by Tailwind utilities\n * the package uses (`bg-primary`, `text-muted-foreground`, etc.).\n */\nexport function tokensToStyle(tokens?: ComposerTokens): CSSProperties | undefined {\n if (!tokens) return undefined;\n const out: Record<string, string> = {};\n for (const key of COLOR_TOKEN_KEYS) {\n const v = tokens[key];\n if (typeof v === \"string\" && v.length > 0) {\n out[COLOR_TOKEN_VAR[key]] = v;\n }\n }\n if (tokens.radius !== undefined) out[\"--composer-radius\"] = asLength(tokens.radius);\n if (tokens.fontSize !== undefined) out[\"--composer-font-size\"] = asLength(tokens.fontSize);\n if (tokens.fontFamily !== undefined) out[\"--composer-font-family\"] = tokens.fontFamily;\n return Object.keys(out).length ? (out as CSSProperties) : undefined;\n}","/**\n * Built-in icon set for the composer.\n *\n * Why inline instead of `lucide-react`?\n * - Removes the runtime dependency entirely.\n * - Lets consumers override any icon with their own component via the\n * `icons` prop on `<Composer />` — useful for matching a brand kit\n * (Heroicons, Phosphor, Material, etc).\n *\n * The defaults below are 24x24 stroke SVGs drawn in the same visual idiom as\n * lucide so the out-of-the-box composer looks the same as before. Each icon\n * forwards arbitrary SVGProps so callers can pass `className`, `style`,\n * `aria-*`, etc.\n */\nimport type { ComponentType, ReactNode, SVGProps } from \"react\";\n\nexport type IconProps = SVGProps<SVGSVGElement>;\nexport type IconComponent = ComponentType<IconProps>;\n\nfunction makeIcon(displayName: string, paths: ReactNode): IconComponent {\n const Icon: IconComponent = (props) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...props}\n >\n {paths}\n </svg>\n );\n Icon.displayName = displayName;\n return Icon;\n}\n\nexport const IconSend = makeIcon(\n \"IconSend\",\n <>\n <path d=\"M12 5v14\" />\n <path d=\"m19 12-7-7-7 7\" />\n </>,\n);\n\nexport const IconStop = makeIcon(\n \"IconStop\",\n <rect width=\"14\" height=\"14\" x=\"5\" y=\"5\" rx=\"2\" />,\n);\n\nexport const IconAttach = makeIcon(\n \"IconAttach\",\n <>\n <path d=\"M13.234 20.252 21 12.3\" />\n <path d=\"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486\" />\n </>,\n);\n\nexport const IconImage = makeIcon(\n \"IconImage\",\n <>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" ry=\"2\" />\n <circle cx=\"9\" cy=\"9\" r=\"2\" />\n <path d=\"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21\" />\n </>,\n);\n\nexport const IconVoice = makeIcon(\n \"IconVoice\",\n <>\n <path d=\"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z\" />\n <path d=\"M19 10v2a7 7 0 0 1-14 0v-2\" />\n <line x1=\"12\" x2=\"12\" y1=\"19\" y2=\"22\" />\n </>,\n);\n\nexport const IconVoiceRecording = makeIcon(\n \"IconVoiceRecording\",\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />,\n);\n\nexport const IconWeb = makeIcon(\n \"IconWeb\",\n <>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\" />\n <path d=\"M2 12h20\" />\n </>,\n);\n\nexport const IconClose = makeIcon(\n \"IconClose\",\n <>\n <path d=\"M18 6 6 18\" />\n <path d=\"m6 6 12 12\" />\n </>,\n);\n\nexport const IconZoom = makeIcon(\n \"IconZoom\",\n <>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <line x1=\"21\" x2=\"16.65\" y1=\"21\" y2=\"16.65\" />\n <line x1=\"11\" x2=\"11\" y1=\"8\" y2=\"14\" />\n <line x1=\"8\" x2=\"14\" y1=\"11\" y2=\"11\" />\n </>,\n);\n\nexport const IconFile = makeIcon(\n \"IconFile\",\n <>\n <path d=\"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n <line x1=\"16\" x2=\"8\" y1=\"13\" y2=\"13\" />\n <line x1=\"16\" x2=\"8\" y1=\"17\" y2=\"17\" />\n <line x1=\"10\" x2=\"8\" y1=\"9\" y2=\"9\" />\n </>,\n);\n\nexport const IconAudio = makeIcon(\n \"IconAudio\",\n <>\n <path d=\"M9 18V5l12-2v13\" />\n <circle cx=\"6\" cy=\"18\" r=\"3\" />\n <circle cx=\"18\" cy=\"16\" r=\"3\" />\n </>,\n);\n\nexport const IconSparkle = makeIcon(\n \"IconSparkle\",\n <>\n <path d=\"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275Z\" />\n <path d=\"M5 3v4\" />\n <path d=\"M19 17v4\" />\n <path d=\"M3 5h4\" />\n <path d=\"M17 19h4\" />\n </>,\n);\n\nexport const IconSpinner = makeIcon(\n \"IconSpinner\",\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />,\n);\n\nexport const IconWarning = makeIcon(\n \"IconWarning\",\n <>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </>,\n);\n\n/**\n * Public icon slot map. Consumers can override any of these via the\n * `icons` prop on `<Composer />`. Anything left unspecified falls back to\n * the built-in lucide-style default above.\n */\nexport interface ComposerIcons {\n /** Submit / send the message. */\n send: IconComponent;\n /** Stop an in-flight streaming response. */\n stop: IconComponent;\n /** Toolbar: attach any file. */\n attach: IconComponent;\n /** Toolbar: pick an image. */\n image: IconComponent;\n /** Voice plugin: start recording. */\n voice: IconComponent;\n /** Voice plugin: transcription in progress. */\n voiceRecording: IconComponent;\n /** Toolbar: enable web search. */\n web: IconComponent;\n /** Close / dismiss (e.g. lightbox, chip remove). */\n close: IconComponent;\n /** Zoom into an attachment / diagram. */\n zoom: IconComponent;\n /** Generic file (PDF, doc, etc) attachment. */\n file: IconComponent;\n /** Audio attachment. */\n audio: IconComponent;\n /** Decorative sparkle (suggestions, diagram preview header). */\n sparkle: IconComponent;\n /** Generic loading spinner (used on attachment chips during upload). */\n spinner: IconComponent;\n /** Generic warning / failure badge (used on failed-upload chips). */\n warning: IconComponent;\n}\n\nexport const DEFAULT_ICONS: ComposerIcons = {\n send: IconSend,\n stop: IconStop,\n attach: IconAttach,\n image: IconImage,\n voice: IconVoice,\n voiceRecording: IconVoiceRecording,\n web: IconWeb,\n close: IconClose,\n zoom: IconZoom,\n file: IconFile,\n audio: IconAudio,\n sparkle: IconSparkle,\n spinner: IconSpinner,\n warning: IconWarning,\n};\n\n/** Merge consumer-provided overrides with the built-in defaults. */\nexport function resolveIcons(\n overrides?: Partial<ComposerIcons>,\n): ComposerIcons {\n if (!overrides) return DEFAULT_ICONS;\n return { ...DEFAULT_ICONS, ...overrides };\n}","import {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n} from \"react\";\nimport type {\n Attachment,\n AttachmentOptions,\n AttachmentsConfig,\n ComposerFeatures,\n ComposerPromptBehavior,\n ComposerProps,\n ComposerSlotClassNames,\n ComposerSlots,\n ComposerSxMap,\n DiagramRenderer,\n MarkdownMode,\n} from \"../types\";\nimport { resolveIcons, type ComposerIcons } from \"../internal/icons\";\n\ntype ComposerMode = NonNullable<ComposerProps[\"mode\"]>;\n\ntype SubmitCallback = () => void;\ntype AddFilesCallback = (files: File[]) => void;\ntype RunPromptCallback = (\n prompt: string,\n behavior: ComposerPromptBehavior,\n) => void;\n\ninterface ComposerContextValue {\n features: Required<ComposerFeatures>;\n attachmentsConfig: AttachmentsConfig;\n attachments: Attachment[];\n addFiles: AddFilesCallback;\n removeAttachment: (id: string) => void;\n clearAttachments: () => void;\n registerAddFiles: (cb: AddFilesCallback) => () => void;\n /** Stream of submit requests; plugins can subscribe (e.g. SlashMenu intercepts Enter). */\n registerSubmit: (cb: SubmitCallback) => () => void;\n triggerSubmit: () => void;\n /**\n * Quick-prompts channel. The chip-row UI calls `runPrompt(text, behavior)`;\n * the inner editor (which owns the editor state and the submit function)\n * subscribes via `registerRunPrompt` and performs the actual insert /\n * insert-and-submit.\n */\n registerRunPrompt: (cb: RunPromptCallback) => () => void;\n runPrompt: RunPromptCallback;\n webEnabled: boolean;\n toggleWeb: () => void;\n isStreaming: boolean;\n isDraggingFiles: boolean;\n setIsDraggingFiles: (v: boolean) => void;\n closeMenusOnOutsideClick: boolean;\n /** See {@link AttachmentOptions}. Normalized so all sub-flags have defaults. */\n attachmentOptions: AttachmentOptions;\n /**\n * Resolved markdown rendering mode. Derived from `features.markdown`:\n * - `markdown: true` / `markdown: undefined` → `\"hybrid\"`\n * - `markdown: false` → `\"hybrid\"` (unused — plugin off)\n * - `markdown: { mode }` → that mode\n *\n * Read by MarkdownPlugin to decide whether to emit visible token spans\n * (`hybrid`) or to consume markers in place once they match (`live`).\n * Read by the serializer to know whether the document text IS the\n * markdown source (`hybrid`) or needs reconstructing from format flags\n * (`live`).\n */\n markdownMode: MarkdownMode;\n mode: ComposerMode;\n /** See `ComposerProps.multiline`. */\n multiline: boolean;\n /** See `ComposerProps.submitOnEnter`. */\n submitOnEnter: boolean;\n /** See `ComposerProps.smartNewline`. Only meaningful when `multiline` is true. */\n smartNewline: boolean;\n /** See `ComposerProps.focusShortcut`. `null` when the consumer disabled it\n * so HintBar / docs can skip rendering the shortcut. */\n focusShortcut: string | null;\n /** Resolved icon set (consumer overrides merged with the built-in defaults). */\n icons: ComposerIcons;\n /** Component-level slot overrides (currently sendButton / stopButton).\n * Internal components check this before rendering their default chrome. */\n slots: ComposerSlots;\n /** Consumer-supplied diagram renderer for ```mermaid (or any other) fences. */\n renderDiagram?: DiagramRenderer;\n /**\n * Writing direction explicitly set by the consumer (see\n * `ComposerProps.dir`). Plugins / popovers that escape the composer's\n * subtree (e.g. portaled menus) read this so they can mirror their layout\n * even when their portal target has a different direction than the\n * composer root.\n */\n dir?: \"ltr\" | \"rtl\" | \"auto\";\n /** Per-slot className overrides forwarded to every internal component. */\n classNames?: ComposerSlotClassNames;\n /** Per-slot `sx` overrides forwarded to every internal component. */\n sx?: ComposerSxMap;\n /**\n * Resolved token CSS custom properties (e.g. `{ \"--primary\": \"270 91% 65%\" }`)\n * that we re-apply on every portaled popover / overlay so the brand colour\n * cascades into UI that escapes `[data-composer-root]`. Computed once in\n * `<Composer />` and forwarded here so popups don't need to re-resolve it.\n */\n tokenStyle?: CSSProperties;\n}\n\nconst ComposerContext = createContext<ComposerContextValue | null>(null);\n\nconst DEFAULT_FEATURES: Required<ComposerFeatures> = {\n markdown: true,\n attachments: true,\n mentions: false,\n slashCommands: false,\n voice: true,\n mermaid: true,\n web: true,\n // Off by default — ghost autocomplete is an opt-in input affordance that\n // only makes sense when the consumer has a curated list of completions.\n ghostedAutoComplete: false,\n};\n\nconst DEFAULT_ATTACHMENTS: Required<AttachmentsConfig> = {\n // Show only the generic paperclip by default — its `accept` string already\n // includes images, so users can still attach photos via the OS dialog.\n // The dedicated image button is opt-in (`attachments: { image: true }`),\n // primarily for chat-heavy apps where jumping straight to the mobile\n // camera-roll picker is a UX win worth the second button.\n file: true,\n image: false,\n accept: \"image/*,application/pdf,text/*,audio/*,video/*\",\n // No type-picker popover by default — the paperclip opens the OS file\n // picker directly. When the consumer supplies a non-empty `types` list,\n // the paperclip flips into a small dropdown that lets the user pick a\n // category first, scoping the OS dialog to that type's `accept`.\n types: [],\n maxSize: 25 * 1024 * 1024,\n maxCount: 10,\n};\n\nfunction normalizeFeatures(features?: ComposerFeatures): Required<ComposerFeatures> {\n if (!features) return DEFAULT_FEATURES;\n return {\n markdown: features.markdown ?? DEFAULT_FEATURES.markdown,\n attachments: features.attachments ?? DEFAULT_FEATURES.attachments,\n mentions: features.mentions ?? DEFAULT_FEATURES.mentions,\n slashCommands: features.slashCommands ?? DEFAULT_FEATURES.slashCommands,\n voice: features.voice ?? DEFAULT_FEATURES.voice,\n mermaid: features.mermaid ?? DEFAULT_FEATURES.mermaid,\n web: features.web ?? DEFAULT_FEATURES.web,\n ghostedAutoComplete:\n features.ghostedAutoComplete ?? DEFAULT_FEATURES.ghostedAutoComplete,\n };\n}\n\nfunction detectKind(file: File): Attachment[\"kind\"] {\n if (file.type.startsWith(\"image/\")) return \"image\";\n if (file.type.startsWith(\"audio/\")) return \"audio\";\n return \"file\";\n}\n\n// Stable reference for the default (empty) slots object — using a fresh `{}`\n// on every render would invalidate the context memo and force every consumer\n// to re-render even when no slots are configured.\nconst EMPTY_SLOTS: ComposerSlots = Object.freeze({});\n\ninterface ProviderProps {\n features?: ComposerFeatures;\n isStreaming?: boolean;\n closeMenusOnOutsideClick?: boolean;\n attachmentOptions?: AttachmentOptions;\n mode?: ComposerMode;\n multiline?: boolean;\n submitOnEnter?: boolean;\n smartNewline?: boolean;\n focusShortcut?: string | false | null;\n icons?: Partial<ComposerIcons>;\n slots?: ComposerSlots;\n renderDiagram?: DiagramRenderer;\n dir?: \"ltr\" | \"rtl\" | \"auto\";\n classNames?: ComposerSlotClassNames;\n sx?: ComposerSxMap;\n tokenStyle?: CSSProperties;\n children: ReactNode;\n}\n\nexport function ComposerProvider({\n features,\n isStreaming,\n closeMenusOnOutsideClick = true,\n attachmentOptions,\n mode = \"markdown\",\n multiline = true,\n submitOnEnter = true,\n smartNewline = true,\n focusShortcut = \"mod+/\",\n icons,\n slots,\n renderDiagram,\n dir,\n classNames,\n sx,\n tokenStyle,\n children,\n}: ProviderProps) {\n const resolvedIcons = useMemo(() => resolveIcons(icons), [icons]);\n const normalizedFeatures = useMemo(() => normalizeFeatures(features), [features]);\n // Resolve markdown sub-config exactly once. We pre-collapse all the\n // shorthand cases (`true`, `false`, `{ mode }`) here so every consumer\n // (plugin, serializer, downstream UI) can just read `markdownMode`\n // without re-doing the boolean/object dance.\n const markdownMode = useMemo<MarkdownMode>(() => {\n const md = normalizedFeatures.markdown;\n if (typeof md === \"object\" && md.mode) return md.mode;\n return \"hybrid\";\n }, [normalizedFeatures.markdown]);\n const attachmentsConfig: AttachmentsConfig = useMemo(() => {\n if (typeof normalizedFeatures.attachments === \"object\") {\n return { ...DEFAULT_ATTACHMENTS, ...normalizedFeatures.attachments };\n }\n return DEFAULT_ATTACHMENTS;\n }, [normalizedFeatures.attachments]);\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n const [webEnabled, setWebEnabled] = useState(false);\n const [isDraggingFiles, setIsDraggingFiles] = useState(false);\n\n const submitSubsRef = useRef(new Set<SubmitCallback>());\n const addFilesSubsRef = useRef(new Set<AddFilesCallback>());\n const runPromptSubsRef = useRef(new Set<RunPromptCallback>());\n\n // Normalize attachment-options with defaults. We expose this through the\n // context value, but the actual `addFiles` reads the upload handler via a\n // ref so we don't have to rebuild it (and tear down every paste/drop\n // subscriber) every time the consumer's callback identity changes.\n const normalizedAttachmentOptions = useMemo<AttachmentOptions>(\n () => ({\n uploadFirst: !!attachmentOptions?.uploadFirst,\n onUpload: attachmentOptions?.onUpload,\n canSendOnlyAttachment: attachmentOptions?.canSendOnlyAttachment ?? true,\n }),\n [\n attachmentOptions?.uploadFirst,\n attachmentOptions?.onUpload,\n attachmentOptions?.canSendOnlyAttachment,\n ],\n );\n const uploadHandlerRef = useRef<AttachmentOptions[\"onUpload\"]>(\n attachmentOptions?.onUpload,\n );\n uploadHandlerRef.current = attachmentOptions?.onUpload;\n const uploadFirstRef = useRef<boolean>(\n !!attachmentOptions?.uploadFirst,\n );\n uploadFirstRef.current = !!attachmentOptions?.uploadFirst;\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => {\n const next = prev.filter((a) => a.id !== id);\n const removed = prev.find((a) => a.id === id);\n if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);\n return next;\n });\n }, []);\n\n const clearAttachments = useCallback(() => {\n setAttachments((prev) => {\n prev.forEach((a) => a.previewUrl && URL.revokeObjectURL(a.previewUrl));\n return [];\n });\n }, []);\n\n // We read the latest `attachments.length` via a ref so this callback can\n // enforce `maxCount` correctly without re-creating itself on every list\n // change (which would invalidate every paste/drop subscriber that captured\n // it). The functional setAttachments below is the source of truth — the\n // ref-based count is just used to short-circuit before building objects.\n const attachmentsCountRef = useRef(0);\n attachmentsCountRef.current = attachments.length;\n\n const addFiles = useCallback<AddFilesCallback>(\n (files) => {\n if (files.length === 0) return;\n const enabled = !!normalizedFeatures.attachments;\n if (!enabled) return;\n\n // Build the accepted list out here so we know exactly which\n // attachments to start uploads for (we can't easily recover that\n // from inside the functional setter).\n const accepted: Attachment[] = [];\n let remaining =\n (attachmentsConfig.maxCount ?? Infinity) - attachmentsCountRef.current;\n const shouldUpload = uploadFirstRef.current && !!uploadHandlerRef.current;\n for (const file of files) {\n if (remaining <= 0) break;\n if (file.size > (attachmentsConfig.maxSize ?? Infinity)) continue;\n const kind = detectKind(file);\n accepted.push({\n id: `att-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n kind,\n name: file.name || `attachment.${kind}`,\n mimeType: file.type,\n size: file.size,\n file,\n previewUrl:\n kind === \"image\" || kind === \"audio\"\n ? URL.createObjectURL(file)\n : undefined,\n status: shouldUpload ? \"uploading\" : undefined,\n });\n remaining -= 1;\n }\n if (accepted.length === 0) return;\n\n setAttachments((prev) => [...prev, ...accepted]);\n addFilesSubsRef.current.forEach((cb) => cb(files));\n\n // Kick off uploads in parallel. Results land via setAttachments\n // updaters keyed on the attachment id, so a chip the user has already\n // removed simply gets skipped (the .map produces an unchanged array).\n if (shouldUpload) {\n const handler = uploadHandlerRef.current!;\n for (const att of accepted) {\n Promise.resolve()\n .then(() => handler(att.file))\n .then((ok) => {\n setAttachments((prev) =>\n prev.map((a) =>\n a.id === att.id\n ? {\n ...a,\n status: ok ? \"uploaded\" : \"failed\",\n error: ok ? undefined : \"Upload failed\",\n }\n : a,\n ),\n );\n })\n .catch((err: unknown) => {\n const message =\n err instanceof Error ? err.message : String(err ?? \"Upload failed\");\n setAttachments((prev) =>\n prev.map((a) =>\n a.id === att.id\n ? { ...a, status: \"failed\", error: message }\n : a,\n ),\n );\n });\n }\n }\n },\n [\n attachmentsConfig.maxCount,\n attachmentsConfig.maxSize,\n normalizedFeatures.attachments,\n ],\n );\n\n const registerAddFiles = useCallback<ComposerContextValue[\"registerAddFiles\"]>(\n (cb) => {\n addFilesSubsRef.current.add(cb);\n return () => {\n addFilesSubsRef.current.delete(cb);\n };\n },\n [],\n );\n\n const registerSubmit = useCallback<ComposerContextValue[\"registerSubmit\"]>(\n (cb) => {\n submitSubsRef.current.add(cb);\n return () => {\n submitSubsRef.current.delete(cb);\n };\n },\n [],\n );\n\n const triggerSubmit = useCallback(() => {\n submitSubsRef.current.forEach((cb) => cb());\n }, []);\n\n const registerRunPrompt = useCallback<\n ComposerContextValue[\"registerRunPrompt\"]\n >((cb) => {\n runPromptSubsRef.current.add(cb);\n return () => {\n runPromptSubsRef.current.delete(cb);\n };\n }, []);\n\n const runPrompt = useCallback<RunPromptCallback>((prompt, behavior) => {\n runPromptSubsRef.current.forEach((cb) => cb(prompt, behavior));\n }, []);\n\n const toggleWeb = useCallback(() => setWebEnabled((w) => !w), []);\n\n const value = useMemo<ComposerContextValue>(\n () => ({\n features: normalizedFeatures,\n attachmentsConfig,\n attachments,\n addFiles,\n removeAttachment,\n clearAttachments,\n registerAddFiles,\n registerSubmit,\n triggerSubmit,\n registerRunPrompt,\n runPrompt,\n webEnabled,\n toggleWeb,\n isStreaming: !!isStreaming,\n isDraggingFiles,\n setIsDraggingFiles,\n closeMenusOnOutsideClick,\n attachmentOptions: normalizedAttachmentOptions,\n markdownMode,\n mode,\n multiline,\n submitOnEnter,\n smartNewline,\n focusShortcut: focusShortcut || null,\n icons: resolvedIcons,\n slots: slots ?? EMPTY_SLOTS,\n renderDiagram,\n dir,\n classNames,\n sx,\n tokenStyle,\n }),\n [\n normalizedFeatures,\n attachmentsConfig,\n attachments,\n addFiles,\n removeAttachment,\n clearAttachments,\n registerAddFiles,\n registerSubmit,\n triggerSubmit,\n registerRunPrompt,\n runPrompt,\n webEnabled,\n toggleWeb,\n isStreaming,\n isDraggingFiles,\n closeMenusOnOutsideClick,\n normalizedAttachmentOptions,\n markdownMode,\n mode,\n multiline,\n submitOnEnter,\n smartNewline,\n focusShortcut,\n resolvedIcons,\n slots,\n renderDiagram,\n dir,\n classNames,\n sx,\n tokenStyle,\n ],\n );\n\n return <ComposerContext.Provider value={value}>{children}</ComposerContext.Provider>;\n}\n\nexport function useComposerContext(): ComposerContextValue {\n const ctx = useContext(ComposerContext);\n if (!ctx) {\n throw new Error(\"useComposerContext must be used inside <ComposerProvider>\");\n }\n return ctx;\n}","/**\n * EditorShell — slot-based layout for the composer card.\n *\n * The Lexical `<LexicalComposer>` lives one level up (in `ComposerCard`)\n * so that every consumer of editor state — including the toolbar / send\n * button — can sit as a sibling of the editor itself. That lets the\n * `multiline === false` (\"inline\") variant collapse toolbar, editor and\n * send into a single horizontal row without the toolbar/send having to\n * portal in from a deeper subtree.\n *\n * Two layouts are supported, picked via `multiline`:\n *\n * ┌───────────────────────── multiline (default) ─────────────────────────┐\n * │ header (attachment tray) │\n * │ editor (multi-line, max-h, vertical scroll) │\n * │ toolbar ─────────────────────────────────────────────────── send btn │\n * │ footer (mermaid preview) │\n * └───────────────────────────────────────────────────────────────────────┘\n *\n * ┌─────────────────────── multiline === false (inline) ──────────────────┐\n * │ header (attachment tray) │\n * │ toolbar │ editor (single-line, horizontal scroll) │ send btn │\n * │ footer (NOT rendered — mermaid can't form without newlines anyway) │\n * └───────────────────────────────────────────────────────────────────────┘\n */\nimport { RichTextPlugin } from \"@lexical/react/LexicalRichTextPlugin\";\nimport { PlainTextPlugin } from \"@lexical/react/LexicalPlainTextPlugin\";\nimport { ContentEditable } from \"@lexical/react/LexicalContentEditable\";\nimport { LexicalErrorBoundary } from \"@lexical/react/LexicalErrorBoundary\";\nimport { HistoryPlugin } from \"@lexical/react/LexicalHistoryPlugin\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { useComposerContext } from \"./ComposerProvider\";\nimport { resolveSx, slotProps } from \"../internal/sx\";\nimport type { ComposerProps } from \"../types\";\n\ntype Mode = NonNullable<ComposerProps[\"mode\"]>;\n\ninterface EditorShellProps {\n placeholder: string;\n mode: Mode;\n /**\n * `false` switches the shell into the inline / single-line layout\n * described above. Mirrors `ComposerProps.multiline`.\n */\n multiline: boolean;\n /** Rendered above the editor (attachment tray). */\n header?: ReactNode;\n /** Toolbar contents — rendered below the editor (multiline) or to its\n * start (inline). Toolbar omits a wrapping div so we can position it\n * via grid placement in either layout. */\n toolbar?: ReactNode;\n /** Send button — rendered to the right of the toolbar (multiline) or to\n * the end of the editor row (inline). */\n sendButton?: ReactNode;\n /** Rendered below the toolbar row (mermaid preview). Skipped in inline\n * mode by the caller — single-line input can't form a mermaid fence. */\n footer?: ReactNode;\n}\n\nexport function EditorShell({\n placeholder,\n mode,\n multiline,\n header,\n toolbar,\n sendButton,\n footer,\n}: EditorShellProps) {\n const { classNames, sx, dir } = useComposerContext();\n const isMarkdown = mode === \"markdown\";\n\n // Editor padding differs per layout:\n // multiline: roomy vertical padding for multi-line writing.\n // inline: no vertical padding (height drives the size); horizontal\n // padding hugs the editor between toolbar and send so the\n // caret never bumps into them.\n const editorClass = multiline\n ? \"composer-editor min-h-[44px] max-h-56 scrollbar-thin overflow-y-auto px-5 py-3.5\"\n : \"composer-editor composer-editor--inline h-9 overflow-x-auto overflow-y-hidden whitespace-nowrap px-2 leading-9\";\n\n const editor = slotProps(\"editor\", editorClass, classNames, sx);\n\n // Placeholder mirrors editor padding/typography so the placeholder text\n // sits exactly where the caret will land. In inline mode the placeholder\n // also gets `leading-9` (1.75rem) to vertically center within the 36px row.\n const editorResolved = resolveSx(sx?.editor);\n const placeholderBase = mirrorEditorPadding(editorResolved);\n const placeholderClass = multiline\n ? \"composer-placeholder pointer-events-none absolute inset-x-0 top-0 select-none px-5 py-3.5 text-[15px] leading-relaxed text-muted-foreground\"\n : \"composer-placeholder pointer-events-none absolute inset-y-0 inset-x-0 select-none px-2 text-[15px] leading-9 text-muted-foreground truncate\";\n const placeholderProps = slotProps(\n \"placeholder\",\n placeholderClass,\n classNames,\n sx,\n placeholderBase,\n );\n\n const contentEditable = (\n <ContentEditable {...editor} aria-label=\"Message\" spellCheck dir={dir} />\n );\n const placeholderEl = (\n <div {...placeholderProps} dir={dir}>\n {placeholder}\n </div>\n );\n\n const editorBlock = (\n <div\n className={cn(\n \"composer-editor-block relative min-w-0\",\n // Inline: the editor block is the flex child that fills the row.\n !multiline && \"flex-1\",\n )}\n >\n {isMarkdown ? (\n <RichTextPlugin\n contentEditable={contentEditable}\n placeholder={placeholderEl}\n ErrorBoundary={LexicalErrorBoundary}\n />\n ) : (\n <PlainTextPlugin\n contentEditable={contentEditable}\n placeholder={placeholderEl}\n ErrorBoundary={LexicalErrorBoundary}\n />\n )}\n </div>\n );\n\n if (!multiline) {\n // Inline layout — header above, then a single horizontal row of\n // [toolbar | editor | send]. We don't render `footer` here because the\n // caller already opts out of <MermaidSlot /> when multiline is false\n // (no newlines means no fences can ever form).\n return (\n <>\n {header}\n <div className=\"composer-inline-row flex items-center gap-1 px-2 py-1.5\">\n {toolbar && (\n <div className=\"composer-inline-toolbar flex shrink-0 items-center\">\n {toolbar}\n </div>\n )}\n {editorBlock}\n {sendButton && (\n <div className=\"composer-inline-send flex shrink-0 items-center\">\n {sendButton}\n </div>\n )}\n </div>\n <HistoryPlugin />\n </>\n );\n }\n\n // Multi-line layout — header, editor, toolbar+send row (justify-between),\n // footer. Matches the historical structure exactly.\n return (\n <>\n {header}\n {editorBlock}\n {(toolbar || sendButton) && (\n <div className=\"flex items-center justify-between px-3 pb-2.5\">\n {toolbar ?? <span />}\n {sendButton}\n </div>\n )}\n <HistoryPlugin />\n {footer}\n </>\n );\n}\n\n// Keys we copy from `sx.editor` onto the placeholder so the placeholder text\n// stays aligned with the editor's caret/text origin when the consumer\n// customises the editor's padding or typography.\nconst PLACEHOLDER_MIRROR_KEYS: ReadonlyArray<keyof CSSProperties> = [\n \"padding\",\n \"paddingInline\",\n \"paddingInlineStart\",\n \"paddingInlineEnd\",\n \"paddingBlock\",\n \"paddingBlockStart\",\n \"paddingTop\",\n \"paddingLeft\",\n \"paddingRight\",\n \"fontSize\",\n \"fontFamily\",\n \"lineHeight\",\n \"letterSpacing\",\n];\n\nfunction mirrorEditorPadding(\n editorStyle: CSSProperties | undefined,\n): CSSProperties | undefined {\n if (!editorStyle) return undefined;\n const out: Record<string, unknown> = {};\n for (const key of PLACEHOLDER_MIRROR_KEYS) {\n const v = (editorStyle as Record<string, unknown>)[key as string];\n if (v !== undefined) out[key as string] = v;\n }\n return Object.keys(out).length ? (out as CSSProperties) : undefined;\n}","import type { EditorThemeClasses } from \"lexical\";\n\nexport const composerTheme: EditorThemeClasses = {\n paragraph: \"composer-paragraph\",\n quote: \"composer-quote\",\n heading: {\n h1: \"composer-h1\",\n h2: \"composer-h2\",\n h3: \"composer-h3\",\n h4: \"composer-h4\",\n h5: \"composer-h5\",\n h6: \"composer-h6\",\n },\n list: {\n ul: \"composer-ul\",\n ol: \"composer-ol\",\n listitem: \"composer-li\",\n nested: {\n listitem: \"composer-li-nested\",\n },\n },\n text: {\n bold: \"composer-bold\",\n italic: \"composer-italic\",\n underline: \"composer-underline\",\n strikethrough: \"composer-strike\",\n underlineStrikethrough: \"composer-underline composer-strike\",\n code: \"composer-code\",\n },\n code: \"composer-code-block\",\n codeHighlight: {\n atrule: \"composer-token-attr\",\n attr: \"composer-token-attr\",\n boolean: \"composer-token-property\",\n builtin: \"composer-token-selector\",\n cdata: \"composer-token-comment\",\n char: \"composer-token-selector\",\n class: \"composer-token-function\",\n \"class-name\": \"composer-token-function\",\n comment: \"composer-token-comment\",\n constant: \"composer-token-property\",\n deleted: \"composer-token-property\",\n doctype: \"composer-token-comment\",\n entity: \"composer-token-operator\",\n function: \"composer-token-function\",\n important: \"composer-token-variable\",\n inserted: \"composer-token-selector\",\n keyword: \"composer-token-attr\",\n namespace: \"composer-token-variable\",\n number: \"composer-token-property\",\n operator: \"composer-token-operator\",\n prolog: \"composer-token-comment\",\n property: \"composer-token-property\",\n punctuation: \"composer-token-punctuation\",\n regex: \"composer-token-variable\",\n selector: \"composer-token-selector\",\n string: \"composer-token-selector\",\n symbol: \"composer-token-property\",\n tag: \"composer-token-property\",\n url: \"composer-token-operator\",\n variable: \"composer-token-variable\",\n },\n link: \"composer-link\",\n};","/**\n * MentionNode — an inline ElementNode that wraps an editable `TextNode`\n * containing the mention's label. The chip carries the mention's stable\n * `id` and its trigger character (`@`, `#`, …) on the wrapping element so\n * the user can backspace through the label one character at a time and\n * the ID stays glued to whatever is left.\n *\n * Why ElementNode (not DecoratorNode)?\n * - The old DecoratorNode chip was atomic: one backspace removed the\n * entire mention, even when the label was \"First Last\" with a space.\n * - As an ElementNode the chip's children are real TextNodes, so the\n * caret traverses them naturally; backspace, selection, IME, and\n * paste all \"just work\".\n *\n * The trigger character (`@`/`#`/…) is rendered via a CSS `::before`\n * pseudo-element keyed off `data-mention-prefix`, so it's visible but\n * NOT part of the editable text content. That guarantees the user can\n * never backspace the prefix away — they can only shorten the label\n * itself. When the label becomes empty the entire chip is removed by\n * Lexical (`canBeEmpty() = false`).\n */\nimport {\n $applyNodeReplacement,\n $createTextNode,\n ElementNode,\n type DOMConversionMap,\n type DOMExportOutput,\n type EditorConfig,\n type LexicalNode,\n type NodeKey,\n type SerializedElementNode,\n type Spread,\n} from \"lexical\";\n\nexport type SerializedMentionNode = Spread<\n {\n mentionId: string;\n mentionPrefix: string;\n },\n SerializedElementNode\n>;\n\nexport class MentionNode extends ElementNode {\n /** Stable identifier supplied by the consumer's MentionItem. */\n __id: string;\n /** Trigger character shown via CSS `::before` (e.g. \"@\" or \"#\"). */\n __prefix: string;\n\n static getType(): string {\n return \"composeai-mention\";\n }\n\n static clone(node: MentionNode): MentionNode {\n return new MentionNode(node.__id, node.__prefix, node.__key);\n }\n\n constructor(id: string, prefix: string = \"@\", key?: NodeKey) {\n super(key);\n this.__id = id;\n this.__prefix = prefix;\n }\n\n // ── Stable accessors ────────────────────────────────────────────────\n getMentionId(): string {\n return this.__id;\n }\n\n getMentionPrefix(): string {\n return this.__prefix;\n }\n\n /**\n * The current label text. Reflects user edits — if the user backspaced\n * \"@John Doe\" down to \"@John\", this returns \"John\".\n */\n getMentionLabel(): string {\n return this.getTextContent();\n }\n\n // ── Behavior flags ──────────────────────────────────────────────────\n isInline(): boolean {\n return true;\n }\n\n /**\n * Returning false makes Lexical auto-remove the element as soon as its\n * children collection becomes empty. That implements \"delete the whole\n * mention when I remove all the text\" with zero plugin code.\n */\n canBeEmpty(): boolean {\n return false;\n }\n\n /**\n * Prevent adjacent text outside the chip from accidentally merging\n * INTO the chip — typing \"x\" right after a mention should produce\n * \"@John|x\", not \"@Johnx\".\n */\n canInsertTextBefore(): boolean {\n return false;\n }\n\n canInsertTextAfter(): boolean {\n return false;\n }\n\n // ── DOM ─────────────────────────────────────────────────────────────\n createDOM(_config: EditorConfig): HTMLElement {\n const span = document.createElement(\"span\");\n span.className = \"composer-mention\";\n span.setAttribute(\"data-mention-id\", this.__id);\n span.setAttribute(\"data-mention-prefix\", this.__prefix);\n return span;\n }\n\n updateDOM(prev: MentionNode, dom: HTMLElement): boolean {\n // Keep the data attributes in sync if id/prefix ever change. Children\n // are reconciled by Lexical, so we return false to keep the existing\n // DOM element.\n if (prev.__id !== this.__id) dom.setAttribute(\"data-mention-id\", this.__id);\n if (prev.__prefix !== this.__prefix) {\n dom.setAttribute(\"data-mention-prefix\", this.__prefix);\n }\n return false;\n }\n\n exportDOM(): DOMExportOutput {\n const el = document.createElement(\"span\");\n el.setAttribute(\"data-mention-id\", this.__id);\n el.setAttribute(\"data-mention-prefix\", this.__prefix);\n // For the exported DOM we inline the prefix into the text so the\n // mention survives copy/paste into apps that don't load our CSS.\n el.textContent = `${this.__prefix}${this.getTextContent()}`;\n return { element: el };\n }\n\n static importDOM(): DOMConversionMap | null {\n return {\n span: (node: HTMLElement) => {\n if (!node.hasAttribute(\"data-mention-id\")) return null;\n return {\n conversion: () => {\n const id = node.getAttribute(\"data-mention-id\") ?? \"\";\n const prefix = node.getAttribute(\"data-mention-prefix\") ?? \"@\";\n const rawText = node.textContent ?? \"\";\n // Strip the prefix we may have inlined during exportDOM.\n const label = rawText.startsWith(prefix)\n ? rawText.slice(prefix.length)\n : rawText;\n const mention = $createMentionNode(id, prefix);\n if (label) {\n mention.append($createTextNode(label));\n }\n return { node: mention };\n },\n priority: 1,\n };\n },\n };\n }\n\n // ── JSON ────────────────────────────────────────────────────────────\n exportJSON(): SerializedMentionNode {\n return {\n ...super.exportJSON(),\n type: MentionNode.getType(),\n version: 1,\n mentionId: this.__id,\n mentionPrefix: this.__prefix,\n };\n }\n\n static importJSON(json: SerializedMentionNode): MentionNode {\n // Children (the label TextNode) are restored by Lexical's default\n // ElementNode JSON handling — we only need to recover id + prefix.\n return $createMentionNode(json.mentionId, json.mentionPrefix ?? \"@\");\n }\n}\n\nexport function $createMentionNode(\n id: string,\n prefix: string = \"@\",\n): MentionNode {\n return $applyNodeReplacement(new MentionNode(id, prefix));\n}\n\nexport function $isMentionNode(\n node: LexicalNode | null | undefined,\n): node is MentionNode {\n return node instanceof MentionNode;\n}","import {\n $applyNodeReplacement,\n TextNode,\n addClassNamesToElement,\n type EditorConfig,\n type LexicalNode,\n type LexicalUpdateJSON,\n type NodeKey,\n type SerializedTextNode,\n} from \"lexical\";\n\nexport type SerializedMarkdownTokenNode = SerializedTextNode;\n\nconst TOKEN_CLASS = \"composer-md-token\";\n\n/**\n * A muted-styled TextNode used to render markdown markers (asterisks,\n * underscores, backticks, tildes) while keeping them part of the source.\n * The caret traverses these characters naturally like normal text.\n */\nexport class MarkdownTokenNode extends TextNode {\n static getType(): string {\n return \"composeai-md-token\";\n }\n\n static clone(node: MarkdownTokenNode): MarkdownTokenNode {\n return new MarkdownTokenNode(node.__text, node.__key);\n }\n\n constructor(text: string = \"\", key?: NodeKey) {\n super(text, key);\n }\n\n createDOM(config: EditorConfig): HTMLElement {\n const dom = super.createDOM(config);\n addClassNamesToElement(dom, TOKEN_CLASS);\n return dom;\n }\n\n static importJSON(\n serializedNode: SerializedMarkdownTokenNode,\n ): MarkdownTokenNode {\n return $createMarkdownTokenNode().updateFromJSON(serializedNode);\n }\n\n updateFromJSON(\n serializedNode: LexicalUpdateJSON<SerializedMarkdownTokenNode>,\n ): this {\n return super.updateFromJSON(serializedNode);\n }\n\n exportJSON(): SerializedMarkdownTokenNode {\n return {\n ...super.exportJSON(),\n type: MarkdownTokenNode.getType(),\n version: 1,\n };\n }\n}\n\nexport function $createMarkdownTokenNode(text: string = \"\"): MarkdownTokenNode {\n return $applyNodeReplacement(new MarkdownTokenNode(text));\n}\n\nexport function $isMarkdownTokenNode(\n node: LexicalNode | null | undefined,\n): node is MarkdownTokenNode {\n return node instanceof MarkdownTokenNode;\n}","/**\n * A drop-in replacement for Lexical's `ParagraphNode` that remembers the\n * markdown block marker (e.g. `\"# \"`, `\"## \"`, `\"> \"`, `` \"```ts\" ``) that\n * was originally on the paragraph but has been hidden from the visible text\n * in `live` markdown mode.\n *\n * Why we need this:\n * --------------------------------------------------------------------------\n * In hybrid mode the block marker is part of the paragraph's text content\n * (rendered as a muted `MarkdownTokenNode`). The block kind is detected\n * from the text on every restyle pass via `detectBlock()`. The serializer\n * just emits the visible text verbatim.\n *\n * In `live` mode we drop the marker chars so the user sees `# Title` as\n * \"Title\" — Notion-style. The block kind is no longer recoverable from\n * the visible text (the leading `# ` is gone) so we stash the original\n * marker string on the paragraph node itself. The detector then prefers\n * that marker, and the serializer reconstructs `# Title` for the submit\n * payload.\n *\n * Keeping the marker as a property (rather than as a hidden TextNode child)\n * sidesteps a bunch of caret-navigation footguns: the paragraph's\n * `getTextContent()` cleanly equals the visible text, so existing offset /\n * selection math in the markdown plugin and the rest of the editor needs\n * no changes.\n *\n * Lifecycle:\n * - Registered as `{replace: ParagraphNode, with: () => new BlockParagraphNode()}`\n * so every `$createParagraphNode()` actually mints a BlockParagraphNode.\n * - `__blockMarker` defaults to `\"\"` (regular paragraph).\n * - `insertNewAfter()` is overridden to return a fresh BlockParagraphNode\n * with NO marker — pressing Enter at the end of a `# Heading` line\n * creates a plain paragraph below, the expected behavior.\n * - `clone()` and `exportJSON()` persist `__blockMarker` across\n * reconciler clones and editor-state serialisation.\n */\n\nimport {\n $applyNodeReplacement,\n ParagraphNode,\n type LexicalUpdateJSON,\n type NodeKey,\n type RangeSelection,\n type SerializedParagraphNode,\n type Spread,\n} from \"lexical\";\n\nexport type SerializedBlockParagraphNode = Spread<\n { blockMarker: string },\n SerializedParagraphNode\n>;\n\nexport class BlockParagraphNode extends ParagraphNode {\n __blockMarker: string;\n\n constructor(key?: NodeKey) {\n super(key);\n this.__blockMarker = \"\";\n }\n\n static getType(): string {\n return \"composeai-block-paragraph\";\n }\n\n static clone(node: BlockParagraphNode): BlockParagraphNode {\n const next = new BlockParagraphNode(node.__key);\n next.__blockMarker = node.__blockMarker;\n return next;\n }\n\n static importJSON(\n serializedNode: SerializedBlockParagraphNode,\n ): BlockParagraphNode {\n return $createBlockParagraphNode().updateFromJSON(serializedNode);\n }\n\n updateFromJSON(\n serializedNode: LexicalUpdateJSON<SerializedBlockParagraphNode>,\n ): this {\n super.updateFromJSON(serializedNode);\n const writable = this.getWritable() as this;\n writable.__blockMarker = serializedNode.blockMarker ?? \"\";\n return writable;\n }\n\n exportJSON(): SerializedBlockParagraphNode {\n return {\n ...super.exportJSON(),\n type: BlockParagraphNode.getType(),\n version: 1,\n blockMarker: this.getBlockMarker(),\n };\n }\n\n getBlockMarker(): string {\n return this.getLatest().__blockMarker;\n }\n\n setBlockMarker(marker: string): this {\n const writable = this.getWritable();\n writable.__blockMarker = marker;\n return writable;\n }\n\n hasBlockMarker(): boolean {\n return this.getLatest().__blockMarker.length > 0;\n }\n\n // Enter inside a block paragraph should start a clean paragraph below —\n // headings, quotes, lists, fences etc. don't bleed into the next line.\n insertNewAfter(\n rangeSelection: RangeSelection,\n restoreSelection: boolean = false,\n ): ParagraphNode {\n const next = super.insertNewAfter(rangeSelection, restoreSelection);\n // `super.insertNewAfter()` calls `$createParagraphNode()` which the\n // node-replacement machinery turns into a BlockParagraphNode with\n // empty marker. Defensive: explicitly clear it in case future Lexical\n // versions bypass the replacement here.\n if (next instanceof BlockParagraphNode) {\n next.setBlockMarker(\"\");\n }\n return next;\n }\n}\n\nexport function $createBlockParagraphNode(): BlockParagraphNode {\n return $applyNodeReplacement(new BlockParagraphNode());\n}\n\nexport function $isBlockParagraphNode(\n node: unknown,\n): node is BlockParagraphNode {\n return node instanceof BlockParagraphNode;\n}","/**\n * A TextNode subclass used in `live` markdown mode to represent the\n * VISIBLE label of a link while remembering the (hidden) URL on the side.\n *\n * Why a custom node rather than Lexical's `@lexical/link` LinkNode:\n * - LinkNode is an ElementNode that wraps a TextNode child, adding a\n * real `<a>` wrapper. That works, but it complicates the plugin's\n * children-equality / per-char format map (which assumes inline =\n * TextNode and bails on element children) and pulls in another\n * package dependency. Our needs are minimal — paint as a link, hold\n * a string `url` — so a TextNode subclass keeps the rest of the\n * plugin code unchanged.\n *\n * In hybrid mode the markers `[`, `](`, `)` AND the URL all stay in the\n * visible text (rendered as muted tokens via MarkdownTokenNode). No\n * LinkTextNode is created.\n *\n * In live mode the markers + URL are removed from the visible text; the\n * URL is stashed on this node so the serializer can reconstruct\n * `[label](url)` on submit.\n */\n\nimport {\n $applyNodeReplacement,\n TextNode,\n addClassNamesToElement,\n type EditorConfig,\n type LexicalNode,\n type LexicalUpdateJSON,\n type NodeKey,\n type SerializedTextNode,\n type Spread,\n} from \"lexical\";\n\nexport type SerializedLinkTextNode = Spread<\n { url: string },\n SerializedTextNode\n>;\n\nconst LINK_CLASS = \"composer-link\";\n\nexport class LinkTextNode extends TextNode {\n __url: string;\n\n constructor(text: string = \"\", url: string = \"\", key?: NodeKey) {\n super(text, key);\n this.__url = url;\n }\n\n static getType(): string {\n return \"composeai-link-text\";\n }\n\n static clone(node: LinkTextNode): LinkTextNode {\n return new LinkTextNode(node.__text, node.__url, node.__key);\n }\n\n createDOM(config: EditorConfig): HTMLElement {\n const dom = super.createDOM(config);\n addClassNamesToElement(dom, LINK_CLASS);\n // We deliberately render as a span (the super's element type) with a\n // class rather than an actual `<a>`. The composer is an input — the\n // user can't navigate away from it by clicking — and a real anchor\n // would steal focus on click in some browsers. The CSS already\n // matches `<a>` styling closely; the URL is reachable from the\n // serialized markdown on submit.\n if (this.__url) dom.setAttribute(\"data-url\", this.__url);\n return dom;\n }\n\n updateDOM(\n prevNode: this,\n dom: HTMLElement,\n config: EditorConfig,\n ): boolean {\n const updated = super.updateDOM(prevNode, dom, config);\n if (prevNode.__url !== this.__url) {\n if (this.__url) dom.setAttribute(\"data-url\", this.__url);\n else dom.removeAttribute(\"data-url\");\n }\n return updated;\n }\n\n static importJSON(serializedNode: SerializedLinkTextNode): LinkTextNode {\n return $createLinkTextNode(\"\", \"\").updateFromJSON(serializedNode);\n }\n\n updateFromJSON(\n serializedNode: LexicalUpdateJSON<SerializedLinkTextNode>,\n ): this {\n super.updateFromJSON(serializedNode);\n const writable = this.getWritable() as this;\n writable.__url = serializedNode.url ?? \"\";\n return writable;\n }\n\n exportJSON(): SerializedLinkTextNode {\n return {\n ...super.exportJSON(),\n type: LinkTextNode.getType(),\n version: 1,\n url: this.getUrl(),\n };\n }\n\n getUrl(): string {\n return this.getLatest().__url;\n }\n\n setUrl(url: string): this {\n const writable = this.getWritable();\n writable.__url = url;\n return writable;\n }\n\n // Typing at the boundary of the link should NOT extend the link — the\n // user wants their next char to be plain text, not \"part of the link\n // label\". Lexical honours these by creating a new sibling TextNode for\n // boundary insertions. Internal edits (cursor between chars) still go\n // into this node, which keeps label editing natural.\n canInsertTextBefore(): boolean {\n return false;\n }\n\n canInsertTextAfter(): boolean {\n return false;\n }\n}\n\nexport function $createLinkTextNode(\n text: string = \"\",\n url: string = \"\",\n): LinkTextNode {\n return $applyNodeReplacement(new LinkTextNode(text, url));\n}\n\nexport function $isLinkTextNode(\n node: LexicalNode | null | undefined,\n): node is LinkTextNode {\n return node instanceof LinkTextNode;\n}","/**\n * Block-level markdown detector. Operates on a single paragraph's text and\n * (when relevant) the running \"are we inside a fenced code block\" state of\n * the previous paragraphs.\n *\n * Block kinds supported:\n * - paragraph — default; no special block\n * - heading 1..6 — `# `, `## `, … `###### `\n * - quote — `> `\n * - list-bullet — `- `, `* `, `+ `\n * - list-numbered — `1. `, `42. `, etc.\n * - hr — `---`, `***`, `___` alone on a line\n * - code-fence-open — `` ``` `` or ` ```lang ` alone on a line\n * - code-fence-close — `` ``` `` alone on a line, when currently inside\n * - code-line — any paragraph that lives between an open and close\n * fence\n *\n * The detector is *line-conservative*: a block kind is only returned when\n * the marker is at the very start of the paragraph (after optional leading\n * whitespace) and the rest of the line is shaped correctly. This avoids\n * false-positive promotion of mid-sentence `## sharps`.\n */\n\nimport { $getRoot, $isParagraphNode, type ParagraphNode } from \"lexical\";\nimport { $isBlockParagraphNode } from \"../core/nodes/BlockParagraphNode\";\n\nexport type BlockKind =\n | \"paragraph\"\n | \"heading-1\"\n | \"heading-2\"\n | \"heading-3\"\n | \"heading-4\"\n | \"heading-5\"\n | \"heading-6\"\n | \"quote\"\n | \"list-bullet\"\n | \"list-numbered\"\n | \"hr\"\n | \"code-fence-open\"\n | \"code-fence-close\"\n | \"code-line\";\n\nexport interface BlockInfo {\n kind: BlockKind;\n /** Length of the leading marker (e.g. `## ` = 3). 0 for paragraph / hr / code-line. */\n markerLen: number;\n /** For fence opens, the language tag if any (`mermaid`, `ts`, …). */\n lang?: string;\n}\n\nconst HEADING_RE = /^(#{1,6}) /;\nconst QUOTE_RE = /^> /;\nconst BULLET_RE = /^[-*+] /;\nconst NUMBERED_RE = /^\\d+\\. /;\nconst HR_RE = /^(?:---|\\*\\*\\*|___)\\s*$/;\n// Opener: three backticks, optional language tag, then anything (GFM\n// \"info string\" — we accept trailing comments etc).\nconst FENCE_OPEN_RE = /^```([A-Za-z0-9_-]*)(?:\\s.*)?$/;\n// Closer: three backticks with nothing meaningful after (strict so we don't\n// confuse a new fence opener with a close).\nconst FENCE_CLOSE_RE = /^```\\s*$/;\n\nconst PLAIN: BlockInfo = { kind: \"paragraph\", markerLen: 0 };\n\n/**\n * Resolve a BlockInfo from a hidden marker stashed on a `BlockParagraphNode`\n * (live mode). The marker contains the same chars that would have been in\n * the visible text in hybrid mode, so we can run them through the regular\n * detector instead of duplicating the lookup table.\n *\n * Returns `null` if the marker doesn't decode — caller falls back to\n * text-based detection.\n */\nfunction detectFromMarker(marker: string): BlockInfo | null {\n if (marker.length === 0) return null;\n // The marker is by definition a syntactically valid block prefix, so\n // dropping a sentinel char to feed the detector is safe. (E.g. `\"# \"` →\n // detect heading on `\"# x\"`.) Code fences are a special case because the\n // open-fence detector requires the whole line to match the regex; we\n // pass the marker as-is — `\"```ts\"` matches the FENCE_OPEN_RE.\n if (FENCE_OPEN_RE.test(marker)) {\n const m = marker.match(FENCE_OPEN_RE);\n return {\n kind: \"code-fence-open\",\n markerLen: 0,\n lang: (m && m[1]) || undefined,\n };\n }\n if (FENCE_CLOSE_RE.test(marker)) {\n return { kind: \"code-fence-close\", markerLen: 0 };\n }\n const probed = detectBlock(`${marker}x`, false);\n if (probed.kind === \"paragraph\") return null;\n // Live mode: marker chars are NOT in the visible text, so markerLen\n // should be reported as 0. The plugin keeps its own copy via the\n // stashed marker for serialization.\n return { ...probed, markerLen: 0 };\n}\n\nexport function detectBlock(text: string, insideCode: boolean): BlockInfo {\n // Inside a fenced block, only the closing fence escapes; everything else\n // is treated as a code line so its content is left untouched.\n if (insideCode) {\n if (FENCE_CLOSE_RE.test(text)) {\n return { kind: \"code-fence-close\", markerLen: 0 };\n }\n return { kind: \"code-line\", markerLen: 0 };\n }\n\n const openMatch = text.match(FENCE_OPEN_RE);\n if (openMatch) {\n return { kind: \"code-fence-open\", markerLen: 0, lang: openMatch[1] || undefined };\n }\n\n if (text.length === 0) return PLAIN;\n\n const h = text.match(HEADING_RE);\n if (h) {\n const level = h[1].length as 1 | 2 | 3 | 4 | 5 | 6;\n return { kind: (`heading-${level}` as BlockKind), markerLen: h[0].length };\n }\n\n if (QUOTE_RE.test(text)) {\n return { kind: \"quote\", markerLen: 2 };\n }\n\n if (BULLET_RE.test(text)) {\n return { kind: \"list-bullet\", markerLen: 2 };\n }\n\n const num = text.match(NUMBERED_RE);\n if (num) {\n return { kind: \"list-numbered\", markerLen: num[0].length };\n }\n\n if (HR_RE.test(text)) {\n return { kind: \"hr\", markerLen: 0 };\n }\n\n return PLAIN;\n}\n\n/**\n * Resolve a single paragraph's BlockInfo, taking into account both the\n * stashed marker (live mode) and the visible text (hybrid mode).\n * Code-line detection still requires knowing the running fence state, so\n * callers pass `insideCode` separately.\n */\nfunction $resolveBlockFor(\n paragraph: ParagraphNode,\n insideCode: boolean,\n): BlockInfo {\n if ($isBlockParagraphNode(paragraph) && paragraph.hasBlockMarker()) {\n const fromMarker = detectFromMarker(paragraph.getBlockMarker());\n if (fromMarker !== null) {\n // Inside a fence the stashed marker for the close line is also a\n // fence; we still honour the running state for correctness.\n if (insideCode && fromMarker.kind !== \"code-fence-close\") {\n return { kind: \"code-line\", markerLen: 0 };\n }\n return fromMarker;\n }\n }\n return detectBlock(paragraph.getTextContent(), insideCode);\n}\n\n/** Map paragraph NodeKey → resolved BlockInfo, computed in document order\n * so fence parity is honoured across siblings. Run inside an editor read. */\nexport function $computeBlockMap(): Map<string, BlockInfo> {\n const map = new Map<string, BlockInfo>();\n const root = $getRoot();\n let insideCode = false;\n\n for (const child of root.getChildren()) {\n if (!$isParagraphNode(child)) continue;\n const info = $resolveBlockFor(child, insideCode);\n map.set(child.getKey(), info);\n if (info.kind === \"code-fence-open\") insideCode = true;\n else if (info.kind === \"code-fence-close\") insideCode = false;\n }\n return map;\n}\n\n/** Cheap point-lookup: is this specific paragraph inside an open code fence? */\nexport function $isParagraphInsideCodeFence(paragraph: ParagraphNode): boolean {\n const root = paragraph.getParent();\n if (!root) return false;\n\n let inside = false;\n for (const child of root.getChildren()) {\n if (child === paragraph) return inside;\n if (!$isParagraphNode(child)) continue;\n // Honour both stashed markers (live mode) and visible markers (hybrid).\n if ($isBlockParagraphNode(child) && child.hasBlockMarker()) {\n const marker = child.getBlockMarker();\n if (inside) {\n if (FENCE_CLOSE_RE.test(marker)) inside = false;\n } else {\n if (FENCE_OPEN_RE.test(marker)) inside = true;\n }\n continue;\n }\n const text = child.getTextContent();\n if (inside) {\n if (FENCE_CLOSE_RE.test(text)) inside = false;\n } else {\n if (FENCE_OPEN_RE.test(text)) inside = true;\n }\n }\n return inside;\n}\n\n/** Returns the BlockInfo for a single paragraph in context (walks earlier\n * siblings to determine fence parity). */\nexport function $detectBlockFor(paragraph: ParagraphNode): BlockInfo {\n const inside = $isParagraphInsideCodeFence(paragraph);\n return $resolveBlockFor(paragraph, inside);\n}","import {\n $getRoot,\n $isElementNode,\n $isLineBreakNode,\n $isParagraphNode,\n $isTextNode,\n type LexicalEditor,\n type LexicalNode,\n} from \"lexical\";\nimport type { MentionRef } from \"../types\";\nimport { $isMentionNode } from \"./nodes/MentionNode\";\nimport { $isMarkdownTokenNode } from \"./nodes/MarkdownTokenNode\";\nimport { $isBlockParagraphNode } from \"./nodes/BlockParagraphNode\";\nimport { $isLinkTextNode } from \"./nodes/LinkTextNode\";\nimport { detectBlock, type BlockKind } from \"../plugins/markdown-blocks\";\n\n/**\n * Walks the editor tree and produces:\n * - text: plain text (chips collapse to `@label`, markdown tokens dropped).\n * - mentions: discovered MentionNodes in document order.\n *\n * \"Plain text\" means what the user *intended* to write — markers like `**`\n * around `bold` are stripped, leaving just `bold`.\n */\nexport function collectPlainAndMentions(editor: LexicalEditor): {\n text: string;\n mentions: MentionRef[];\n} {\n return editor.getEditorState().read(() => {\n const root = $getRoot();\n const mentions: MentionRef[] = [];\n\n const walkInline = (parent: LexicalNode): string => {\n if (!$isElementNode(parent)) return \"\";\n let out = \"\";\n for (const child of parent.getChildren()) {\n if ($isMentionNode(child)) {\n // Label reflects any edits the user made (e.g. backspacing\n // \"John Doe\" down to \"John\"). The id is the stable handle\n // assigned when the chip was first inserted.\n const label = child.getMentionLabel();\n mentions.push({\n id: child.getMentionId(),\n label,\n });\n out += `${child.getMentionPrefix()}${label}`;\n continue;\n }\n if ($isMarkdownTokenNode(child)) continue;\n if ($isLineBreakNode(child)) {\n out += \"\\n\";\n continue;\n }\n if ($isTextNode(child)) {\n out += child.getTextContent();\n continue;\n }\n if ($isElementNode(child)) {\n out += walkInline(child);\n }\n }\n return out;\n };\n\n const blocks: string[] = [];\n for (const child of root.getChildren()) {\n if ($isElementNode(child)) {\n blocks.push(walkInline(child));\n } else if ($isTextNode(child)) {\n blocks.push(child.getTextContent());\n }\n }\n\n return { text: blocks.join(\"\\n\").replace(/\\n+$/g, \"\"), mentions };\n });\n}\n\n/**\n * Lexical format-flag bits we care about for serialization. Mirrors\n * `FORMAT_FLAGS` in MarkdownPlugin so the two stay in lockstep — if you\n * touch one, touch the other.\n */\nconst FORMAT_BIT = {\n bold: 1,\n italic: 2,\n strike: 4,\n // underline (8) — no widely-supported markdown syntax; we drop it on\n // serialize rather than invent one.\n code: 16,\n} as const;\n\n/**\n * Wrap text with markdown markers based on its Lexical format flags. Used\n * by the serializer when running against a `live`-mode document where the\n * markers were stripped out of the editor source and need to be\n * reconstructed at submit time.\n *\n * In `hybrid` mode the markers are already in the document text (carried\n * by `MarkdownTokenNode`s), so this helper isn't called.\n *\n * Order matters: code wraps innermost (backticks shouldn't be confused\n * with surrounding bold/italic), then bold (`**`), italic (`*`), strike\n * (`~~`). Combining bold + italic produces `***text***` — CommonMark\n * accepts it; renderers that don't fall back to plain bold which is fine.\n */\nfunction wrapByFormat(text: string, format: number): string {\n if (!text) return text;\n let out = text;\n if (format & FORMAT_BIT.code) out = `\\`${out}\\``;\n if (format & FORMAT_BIT.bold) out = `**${out}**`;\n if (format & FORMAT_BIT.italic) out = `*${out}*`;\n if (format & FORMAT_BIT.strike) out = `~~${out}~~`;\n return out;\n}\n\n/**\n * Serializes the editor to markdown.\n *\n * Two paths, picked by whether the document contains any\n * `MarkdownTokenNode` children (which only the `hybrid`-mode plugin\n * produces — so the presence of one is a reliable mode-detector that\n * doesn't require threading the mode through every call site):\n *\n * - HYBRID: the document text IS the markdown source. Markers from\n * `MarkdownTokenNode` + body from `TextNode` are concatenated\n * verbatim. No format-flag inspection needed.\n *\n * - LIVE: the document text is the *rendered* state — inline markers\n * were consumed by the plugin and only the Lexical format flag on\n * each TextNode remembers that \"foo\" was bold. We rebuild the\n * markers by wrapping each TextNode according to its format.\n *\n * Inter-paragraph separator: see {@link joinWithCommonMarkSpacing}.\n */\nexport function toMarkdown(editor: LexicalEditor): string {\n return editor.getEditorState().read(() => {\n const root = $getRoot();\n\n // Detect mode by content. A live-mode document never contains\n // MarkdownTokenNodes for inline markers; a hybrid-mode document\n // emits them on every formatted span. (Block markers still live as\n // tokens in both modes — see the comment in MarkdownPlugin — so\n // checking specifically for *inline* format-flag-bearing siblings\n // isn't necessary; presence of any non-leading token is enough.)\n let usingLive = true;\n const scan = (node: LexicalNode): void => {\n if ($isMarkdownTokenNode(node)) {\n const prev = node.getPreviousSibling();\n // Leading-token-of-paragraph = block marker; ignore. Any other\n // token is an inline marker → hybrid mode.\n if (prev !== null) usingLive = false;\n } else if ($isElementNode(node)) {\n for (const child of node.getChildren()) {\n if (!usingLive) return; // early-out\n scan(child);\n }\n }\n };\n for (const child of root.getChildren()) {\n if (!usingLive) break;\n scan(child);\n }\n\n const lines: string[] = [];\n\n const serializeParagraph = (paragraph: LexicalNode): string => {\n if (!$isElementNode(paragraph)) return \"\";\n let out = \"\";\n for (const child of paragraph.getChildren()) {\n if ($isMentionNode(child)) {\n out += `${child.getMentionPrefix()}${child.getMentionLabel()}`;\n continue;\n }\n if ($isLineBreakNode(child)) {\n out += \"\\n\";\n continue;\n }\n if ($isMarkdownTokenNode(child)) {\n // Tokens are markdown markers verbatim (hybrid mode), or block\n // markers (both modes). Either way, just emit the text.\n out += child.getTextContent();\n continue;\n }\n if ($isLinkTextNode(child)) {\n // Live-mode link node: visible label + stashed URL → `[label](url)`.\n // If the URL happens to be empty (shouldn't normally happen)\n // we fall back to the bare label so the user sees their text.\n const label = child.getTextContent();\n const url = child.getUrl();\n out += url ? `[${label}](${url})` : label;\n continue;\n }\n if ($isTextNode(child)) {\n const text = child.getTextContent();\n if (usingLive) {\n out += wrapByFormat(text, child.getFormat());\n } else {\n out += text;\n }\n continue;\n }\n if ($isElementNode(child)) {\n out += serializeParagraph(child);\n }\n }\n return out;\n };\n\n for (const child of root.getChildren()) {\n if ($isParagraphNode(child)) {\n const body = serializeParagraph(child);\n // Live-mode paragraphs may carry the block marker (`# `, ` ```ts `,\n // `> ` etc.) as a stashed prop on the BlockParagraphNode. Prepend\n // it here so the rendered markdown matches what the user typed\n // even though those chars never appeared in the editor's visible\n // text. Hybrid-mode paragraphs always have empty stash.\n if ($isBlockParagraphNode(child) && child.hasBlockMarker()) {\n lines.push(child.getBlockMarker() + body);\n } else {\n lines.push(body);\n }\n } else if ($isTextNode(child)) {\n lines.push(child.getTextContent());\n }\n }\n\n return joinWithCommonMarkSpacing(lines).trim();\n });\n}\n\n/**\n * Block kinds whose paragraphs continue across un-blanked following lines\n * in CommonMark (the \"lazy continuation\" rule). When one of these is\n * immediately followed by a plain paragraph in the editor, we must emit a\n * blank line in the markdown so the next paragraph doesn't get sucked\n * into the list item / block quote.\n */\nfunction isLazyContinuationBlock(kind: BlockKind): boolean {\n return kind === \"list-bullet\" || kind === \"list-numbered\" || kind === \"quote\";\n}\n\nfunction joinWithCommonMarkSpacing(lines: string[]): string {\n if (lines.length === 0) return \"\";\n\n // Walk the document in order so fence parity (we're inside a ``` block\n // or not) is computed correctly — block detection is fence-sensitive.\n let insideCode = false;\n const blocks = lines.map((line) => {\n const info = detectBlock(line, insideCode);\n if (info.kind === \"code-fence-open\") insideCode = true;\n else if (info.kind === \"code-fence-close\") insideCode = false;\n return info;\n });\n\n let out = lines[0];\n for (let i = 1; i < lines.length; i++) {\n const prev = blocks[i - 1];\n const next = blocks[i];\n const nextText = lines[i];\n\n // Only \"plain paragraph\" follow-ups trigger lazy continuation —\n // empty lines already produce a blank in the join, and other block\n // markers (`-`, `#`, `>`, fences, hr) terminate the list/quote on\n // their own and don't need an extra separator.\n const needsBlankSeparator =\n isLazyContinuationBlock(prev.kind) &&\n next.kind === \"paragraph\" &&\n nextText.length > 0;\n\n out += needsBlankSeparator ? \"\\n\\n\" : \"\\n\";\n out += nextText;\n }\n return out;\n}","import { useEffect } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $getRoot,\n $getSelection,\n $isParagraphNode,\n $isRangeSelection,\n COMMAND_PRIORITY_HIGH,\n KEY_ENTER_COMMAND,\n type ParagraphNode,\n type Point,\n} from \"lexical\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { $detectBlockFor, type BlockInfo } from \"./markdown-blocks\";\n\ninterface Props {\n onSubmit: () => void;\n}\n\n/**\n * Returns true when the cursor is positioned somewhere where Enter should\n * mean \"structural newline\" rather than \"submit the message\".\n *\n * In Slack-style markdown, every block is a styled paragraph and Enter is\n * the user's natural submit affordance — so we only defer in one place:\n * inside (or on the opener of) a fenced code block, where pressing Enter\n * is overwhelmingly likely to mean \"add another code line\" not \"send\".\n * Everywhere else, Shift+Enter is the way to insert a soft line break.\n *\n * Run inside a `editor.getEditorState().read(...)` callback.\n */\nfunction $isInsideCodeFence(): boolean {\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return false;\n\n const anchorNode = selection.anchor.getNode();\n const top = anchorNode.getTopLevelElement();\n if (!top || !$isParagraphNode(top)) return false;\n\n const block = $detectBlockFor(top);\n return block.kind === \"code-line\" || block.kind === \"code-fence-open\";\n}\n\n/**\n * Whether the editor currently holds more than one line of content —\n * either multiple top-level paragraphs or a single paragraph with one\n * or more soft line breaks. Used by the smart-newline behavior to\n * decide whether plain Enter should submit or insert a line break.\n *\n * Run inside a `editor.getEditorState().read(...)` callback.\n */\nfunction $hasMultiLineContent(): boolean {\n const root = $getRoot();\n if (root.getChildrenSize() > 1) return true;\n return root.getTextContent().includes(\"\\n\");\n}\n\n/**\n * Plain-text offset of `point` measured from the start of `paragraph`.\n * Walks children in order so the result is comparable against\n * `BlockInfo.markerLen` (which is expressed in plain-text characters).\n *\n * Run inside an editor read or update.\n */\nfunction $offsetWithinParagraph(paragraph: ParagraphNode, point: Point): number {\n if (point.type === \"element\") {\n const children = paragraph.getChildren();\n let offset = 0;\n const limit = Math.min(point.offset, children.length);\n for (let i = 0; i < limit; i++) {\n offset += children[i].getTextContentSize();\n }\n return offset;\n }\n const anchorKey = point.getNode().getKey();\n let offset = 0;\n for (const child of paragraph.getChildren()) {\n if (child.getKey() === anchorKey) return offset + point.offset;\n offset += child.getTextContentSize();\n }\n return offset + point.offset;\n}\n\n/**\n * Smart list-continuation. When the cursor sits inside a markdown bullet\n * (`- `, `* `, `+ `) or numbered (`N. `) paragraph and the user presses\n * Enter, we either:\n *\n * - Exit the list — when the current item is empty (only the marker),\n * the marker is cleared in place so the user lands in a plain\n * paragraph ready for regular prose.\n * - Continue the list — split the paragraph at the cursor and seed\n * the new paragraph with the next marker. Bullet character is\n * preserved (`-`/`*`/`+`); numbered items auto-increment.\n *\n * Returns `true` when we handled the Enter and the caller should\n * `return true` from the command (skipping submit + Lexical's default).\n * Returns `false` to fall through to the regular Enter logic — used\n * when the cursor is in/before the marker itself, where splitting would\n * yield a confusing \"- - foo\" double-marker.\n *\n * Run inside an editor update.\n */\nfunction $handleListContinuation(): boolean {\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return false;\n if (!selection.isCollapsed()) return false;\n\n const anchorNode = selection.anchor.getNode();\n const top = anchorNode.getTopLevelElement();\n if (!top || !$isParagraphNode(top)) return false;\n\n const block: BlockInfo = $detectBlockFor(top);\n if (block.kind !== \"list-bullet\" && block.kind !== \"list-numbered\") {\n return false;\n }\n\n const text = top.getTextContent();\n const contentAfterMarker = text.slice(block.markerLen);\n const cursorOffset = $offsetWithinParagraph(top, selection.anchor);\n\n // Cursor in or before the marker — let Lexical do a vanilla split so\n // we don't accidentally produce \"- - foo\".\n if (cursorOffset < block.markerLen) return false;\n\n // Empty list item: exit the list by clearing the marker. The (now\n // empty) paragraph stays in place and the markdown plugin will\n // re-style it as plain on its next update tick.\n if (contentAfterMarker.length === 0) {\n top.clear();\n top.select(0, 0);\n return true;\n }\n\n // Continue the list. Bullet markers preserve their character (`-`,\n // `*`, `+`); numbered markers increment by one based on the current\n // line's number.\n let nextMarker: string;\n if (block.kind === \"list-bullet\") {\n const ch = text.charAt(0) || \"-\";\n nextMarker = `${ch} `;\n } else {\n const numMatch = text.match(/^(\\d+)/);\n const n = numMatch ? parseInt(numMatch[1], 10) + 1 : 2;\n nextMarker = `${n}. `;\n }\n\n selection.insertParagraph();\n const newSelection = $getSelection();\n if ($isRangeSelection(newSelection)) {\n newSelection.insertText(nextMarker);\n }\n return true;\n}\n\n/**\n * Handles Enter / Shift+Enter / Cmd|Ctrl+Enter with the rules described\n * by the `multiline`, `submitOnEnter`, and `smartNewline` props on\n * `<Composer />`. The behavior matrix, with all three defaulting to\n * `true`:\n *\n * - Cmd/Ctrl+Enter: always submit (when `submitOnEnter` is on or the\n * editor is configured to never submit on Enter — the modifier is\n * the universal \"force send\" gesture).\n * - Shift+Enter: insert a hard paragraph break (NOT a soft\n * `LineBreakNode`) so the markdown plugin can tokenize each line\n * independently. Swallowed when `multiline` is false.\n * - Inside an open code fence: defer to Lexical so Enter splits the\n * paragraph into a new code line — unless `multiline` is false.\n * - Plain Enter, `multiline` false: submit when `submitOnEnter`, else\n * swallow (single-line input with no submit affordance).\n * - Plain Enter, `multiline` true, `smartNewline` true: insert a\n * newline once the editor already holds more than one line;\n * otherwise submit (when `submitOnEnter`). When the cursor sits in\n * a markdown list paragraph (`- `, `* `, `+ `, `N. `) the list is\n * continued instead (next marker auto-inserted, double-Enter exits)\n * — this fires before any submit decision so a single bullet line\n * can be extended without an accidental send.\n * - Plain Enter, `multiline` true, `smartNewline` false: submit when\n * `submitOnEnter`, else insert a newline (Lexical default). List\n * continuation is intentionally off in this mode.\n *\n * Slash/mention menus still get first refusal via the\n * `data-composer-popover=\"open\"` marker.\n */\nexport function KeyboardPlugin({ onSubmit }: Props) {\n const [editor] = useLexicalComposerContext();\n const {\n triggerSubmit,\n multiline,\n submitOnEnter,\n smartNewline,\n mode,\n } = useComposerContext();\n\n useEffect(() => {\n const trySubmit = (event: KeyboardEvent) => {\n event.preventDefault();\n triggerSubmit();\n onSubmit();\n return true;\n };\n\n return editor.registerCommand(\n KEY_ENTER_COMMAND,\n (event) => {\n if (!event) return false;\n\n // If a typeahead popover (slash, mentions) is open, yield to its\n // own KEY_ENTER_COMMAND handler at COMMAND_PRIORITY_LOW so the\n // highlighted option is selected. We MUST NOT call\n // event.preventDefault() or return true here — both would steal\n // the keystroke before the typeahead ever sees it.\n if (document.querySelector('[data-composer-popover=\"open\"]')) {\n return false;\n }\n\n const isModEnter = event.metaKey || event.ctrlKey;\n const isShiftEnter = event.shiftKey;\n\n // Cmd/Ctrl+Enter is the universal \"force submit\" gesture — it\n // always wins regardless of the other props.\n if (isModEnter) return trySubmit(event);\n\n // Shift+Enter: insert a new paragraph, NOT a soft-break\n // `LineBreakNode`. The Slack-style markdown stack\n // (`markdown-blocks.ts`, `MarkdownPlugin`, `serializer.ts`,\n // `insertText.ts`) operates strictly per-paragraph — block kind\n // (heading, list, quote, code-fence, …) is detected from the\n // paragraph's text, styling is applied per `<p>` via\n // `data-md-block`, and CSS for headings uses `::first-line`.\n // A `LineBreakNode` inside a paragraph would leave any line\n // after the break untokenized in the editor (e.g. `# foo`\n // styled as a heading, the `# bar` line after Shift+Enter\n // unstyled) even though the serialized markdown still produces\n // two real headings — so the editor view silently disagrees\n // with the rendered bubble. Treating Shift+Enter as a hard\n // paragraph break (the same gesture Slack, Discord, ChatGPT\n // and Claude all use) restores per-line consistency and\n // matches how pasted/initial multi-line text is already\n // ingested by this composer.\n if (isShiftEnter) {\n if (!multiline) {\n event.preventDefault();\n return true;\n }\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return false;\n selection.insertParagraph();\n event.preventDefault();\n return true;\n }\n\n // Inside a fenced code block we always want a new code line,\n // unless multi-line content is disallowed entirely.\n let inCodeFence = false;\n let hasMultiLine = false;\n editor.getEditorState().read(() => {\n inCodeFence = $isInsideCodeFence();\n hasMultiLine = $hasMultiLineContent();\n });\n if (inCodeFence) {\n if (!multiline) {\n event.preventDefault();\n return true;\n }\n return false;\n }\n\n // Single-line composer: Enter submits or is a no-op.\n if (!multiline) {\n if (!submitOnEnter) {\n event.preventDefault();\n return true;\n }\n return trySubmit(event);\n }\n\n // Smart list continuation: when typing a markdown bullet or\n // numbered item, Enter continues the list (auto-incrementing\n // numbers, preserving the bullet character) and Enter on an\n // empty item exits the list. Runs before the submit / smart\n // newline branches so a single-line bullet doesn't get sent\n // when the user clearly meant to add a second item.\n //\n // NB: we call `$handleListContinuation` directly, NOT via\n // `editor.update(...)`. Lexical dispatches KEY_ENTER_COMMAND\n // from inside its own `updateEditor` wrapper, so we're already\n // in a writable context. A nested `editor.update` would be\n // queued and run AFTER this command returns — by which point\n // we'd have already submitted, which is exactly the bug we're\n // trying to avoid.\n if (smartNewline && mode === \"markdown\") {\n if ($handleListContinuation()) {\n event.preventDefault();\n return true;\n }\n }\n\n // Smart newline: once the editor holds >1 line, plain Enter\n // adds a newline instead of submitting. Cmd/Ctrl+Enter (handled\n // above) is the way to send. This protects long drafts from\n // accidental submission.\n if (smartNewline && hasMultiLine) return false;\n\n if (!submitOnEnter) return false;\n\n return trySubmit(event);\n },\n COMMAND_PRIORITY_HIGH,\n );\n }, [\n editor,\n onSubmit,\n triggerSubmit,\n multiline,\n submitOnEnter,\n smartNewline,\n mode,\n ]);\n\n return null;\n}","import type { LexicalEditor } from \"lexical\";\n\n/**\n * Robustly focus a Lexical editor — used by `AutoFocusPlugin`, the\n * `focusShortcut` window handler, and the `refocusOnSubmit` branch.\n *\n * Why this isn't just `editor.focus()`:\n * A bare `editor.focus()` restores the Lexical *selection* and dispatches\n * the FOCUS_COMMAND, which is enough when the contenteditable already has\n * DOM focus (e.g. the user just pressed Enter to send — the editor was\n * the active element, so refocusing is a no-op-ish). It is NOT enough\n * when DOM focus lives elsewhere — body, a sidebar button, an\n * EmptyState description, etc. In that case the Lexical selection moves\n * but the browser never actually focuses the contenteditable, so the\n * visible caret never appears and keystrokes still hit whatever element\n * originally held focus.\n *\n * The fix mirrors `@lexical/react/LexicalAutoFocusPlugin`: pass a\n * callback into `editor.focus(cb, opts)` that, AFTER Lexical's own\n * focus attempt, manually `rootElement.focus({preventScroll: true})`\n * when the contenteditable still isn't part of `document.activeElement`.\n * `preventScroll` keeps the page from jumping when the composer sits\n * below the fold.\n *\n * `defaultSelection: \"rootEnd\"` lands the caret at the end of any seeded\n * `initialValue`, which is the natural \"ready to keep typing\" position\n * for a chat composer.\n */\nexport function focusEditor(editor: LexicalEditor): void {\n editor.focus(\n () => {\n const active = document.activeElement;\n const root = editor.getRootElement();\n if (root !== null && (active === null || !root.contains(active))) {\n root.focus({ preventScroll: true });\n }\n },\n { defaultSelection: \"rootEnd\" },\n );\n}","import { useEffect } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { focusEditor } from \"../internal/focusEditor\";\n\ninterface Props {\n enabled?: boolean;\n}\n\n/**\n * Lexical doesn't ship a plain `autoFocus` boolean, so we wrap\n * `editor.focus()` ourselves. See `internal/focusEditor.ts` for the full\n * story on why a bare `editor.focus()` isn't enough.\n *\n * Previously this plugin wrapped `editor.focus()` in a single\n * `requestAnimationFrame`, which raced with React's commit phase and\n * occasionally let the click-target keep focus instead.\n */\nexport function AutoFocusPlugin({ enabled }: Props) {\n const [editor] = useLexicalComposerContext();\n useEffect(() => {\n if (!enabled) return;\n focusEditor(editor);\n }, [editor, enabled]);\n return null;\n}","/**\n * PasteDropPlugin — intercepts clipboard paste and drag/drop on the editor.\n *\n * - Pasted images / files become attachment chips in the tray (Phase 2).\n * - Pasted plain text is split on `\\n` into one paragraph per line so the\n * markdown / mermaid block detectors can actually see fence boundaries\n * (the per-paragraph detectors can't recognise a ```mermaid block that\n * landed inside a single paragraph as line breaks).\n * - Drag-over shows a soft overlay so users know the target accepts files.\n *\n * Paste handling lives on `PASTE_COMMAND` (Lexical) rather than a native DOM\n * listener so we don't fight RichTextPlugin's own paste handler for\n * ordering. Drag/drop stays on native DOM events because they aren't\n * surfaced as Lexical commands.\n */\nimport { useEffect } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { COMMAND_PRIORITY_HIGH, PASTE_COMMAND } from \"lexical\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { $insertTextWithParagraphBreaks } from \"../internal/insertText\";\n\nexport function PasteDropPlugin() {\n const [editor] = useLexicalComposerContext();\n const { addFiles, features, multiline, setIsDraggingFiles } =\n useComposerContext();\n\n // ── Paste: files → attachments, text → paragraph-aware insertion ────\n useEffect(() => {\n return editor.registerCommand(\n PASTE_COMMAND,\n (event) => {\n if (!(event instanceof ClipboardEvent)) return false;\n const clipboard = event.clipboardData;\n if (!clipboard) return false;\n\n // 1. Files (only when attachments are enabled).\n if (features.attachments) {\n const files: File[] = [];\n for (const item of clipboard.items) {\n if (item.kind === \"file\") {\n const file = item.getAsFile();\n if (file) files.push(file);\n }\n }\n if (files.length > 0) {\n event.preventDefault();\n addFiles(files);\n return true;\n }\n }\n\n const text = clipboard.getData(\"text/plain\");\n if (!text) return false;\n\n // 2a. Inline / single-line mode — paragraph breaks are meaningless\n // here (the user can't even hit Enter), so flatten newlines to\n // spaces and let Lexical's default handler do the insert. If\n // the paste is already single-line we don't preventDefault and\n // just let the default path run.\n if (!multiline) {\n if (!text.includes(\"\\n\") && !text.includes(\"\\r\")) return false;\n event.preventDefault();\n const flat = text.replace(/\\r\\n?|\\n/g, \" \").replace(/\\s+/g, \" \");\n editor.update(() => {\n $insertTextWithParagraphBreaks(flat);\n });\n return true;\n }\n\n // 2b. Multi-line text — split on `\\n` so each line becomes its own\n // paragraph (required for fence / heading / list detection).\n // Single-line text falls through to Lexical's default handler\n // which already does the right thing.\n if (!text.includes(\"\\n\")) return false;\n event.preventDefault();\n editor.update(() => {\n $insertTextWithParagraphBreaks(text);\n });\n return true;\n },\n COMMAND_PRIORITY_HIGH,\n );\n }, [editor, features.attachments, multiline, addFiles]);\n\n // ── Drag / drop: native DOM events (no Lexical equivalent) ──────────\n useEffect(() => {\n if (!features.attachments) return;\n const root = editor.getRootElement();\n if (!root) return;\n\n let dragDepth = 0;\n const onDragEnter = (event: DragEvent) => {\n if (!event.dataTransfer?.types.includes(\"Files\")) return;\n dragDepth += 1;\n setIsDraggingFiles(true);\n };\n const onDragOver = (event: DragEvent) => {\n if (event.dataTransfer?.types.includes(\"Files\")) {\n event.preventDefault();\n if (event.dataTransfer) event.dataTransfer.dropEffect = \"copy\";\n }\n };\n const onDragLeave = (event: DragEvent) => {\n if (!event.dataTransfer?.types.includes(\"Files\")) return;\n dragDepth = Math.max(0, dragDepth - 1);\n if (dragDepth === 0) setIsDraggingFiles(false);\n };\n const onDrop = (event: DragEvent) => {\n dragDepth = 0;\n setIsDraggingFiles(false);\n const files = event.dataTransfer?.files;\n if (files && files.length > 0) {\n event.preventDefault();\n addFiles(Array.from(files));\n }\n };\n\n root.addEventListener(\"dragenter\", onDragEnter);\n root.addEventListener(\"dragover\", onDragOver);\n root.addEventListener(\"dragleave\", onDragLeave);\n root.addEventListener(\"drop\", onDrop);\n return () => {\n root.removeEventListener(\"dragenter\", onDragEnter);\n root.removeEventListener(\"dragover\", onDragOver);\n root.removeEventListener(\"dragleave\", onDragLeave);\n root.removeEventListener(\"drop\", onDrop);\n };\n }, [editor, addFiles, features.attachments, setIsDraggingFiles]);\n\n return null;\n}","/**\n * Inline-markdown tokenizer used by `MarkdownPlugin`. Produces a flat\n * stream of tokens — markers stay visible (rendered via MarkdownTokenNode)\n * while content carries the matching inline format.\n *\n * Supported inline marks:\n * **bold** __bold__\n * *italic* _italic_\n * ~~strike~~ ~strike~ — CommonMark *and* Slack syntax\n * `code`\n * [label](url) — link\n *  — image (alt text shown like a link)\n *\n * Notes:\n * - Markers are non-greedy and must not have whitespace immediately adjacent\n * to the inner text (matches CommonMark behaviour).\n * - Nested marks are not supported in this first iteration — the outermost\n * match wins and the inner content is treated as plain text.\n * - Newlines never appear inside a single inline mark.\n * - Link / image URLs are rendered as styled (not muted) text and produce\n * an additional `link` format on the URL itself for theming.\n */\n\nexport type InlineFormat =\n | \"bold\"\n | \"italic\"\n | \"underline\"\n | \"code\"\n | \"strike\"\n | \"link\";\n\nexport type Token =\n | { type: \"text\"; text: string }\n | { type: \"marker\"; text: string; format: InlineFormat }\n | { type: \"formatted\"; text: string; format: InlineFormat };\n\ninterface PairedPattern {\n open: string;\n close: string;\n format: InlineFormat;\n}\n\n// Order matters: longer markers must be tried first so `**` is not eaten by `*`,\n// and `~~` is not eaten by single-tilde Slack-style strike.\nconst PAIRED_PATTERNS: PairedPattern[] = [\n { open: \"**\", close: \"**\", format: \"bold\" },\n { open: \"__\", close: \"__\", format: \"bold\" },\n { open: \"~~\", close: \"~~\", format: \"strike\" },\n { open: \"`\", close: \"`\", format: \"code\" },\n { open: \"*\", close: \"*\", format: \"italic\" },\n { open: \"_\", close: \"_\", format: \"italic\" },\n { open: \"~\", close: \"~\", format: \"strike\" }, // Slack-style strike\n];\n\n// `[label](url)` or `` — captured by a single regex anchored at i.\nconst LINK_RE = /^(!?)\\[([^\\]\\n]+)\\]\\(([^)\\n\\s]+)\\)/;\n\nfunction isInvalidInner(inner: string): boolean {\n if (inner.length === 0) return true;\n if (/\\n/.test(inner)) return true;\n if (/^\\s|\\s$/.test(inner)) return true;\n return false;\n}\n\nexport function tokenize(text: string): Token[] {\n const tokens: Token[] = [];\n let i = 0;\n let buf = \"\";\n\n const flushBuf = () => {\n if (buf.length > 0) {\n tokens.push({ type: \"text\", text: buf });\n buf = \"\";\n }\n };\n\n while (i < text.length) {\n // 1) Link / image — matched first because `[` is not a paired marker.\n const ch = text[i];\n if (ch === \"[\" || (ch === \"!\" && text[i + 1] === \"[\")) {\n const m = text.slice(i).match(LINK_RE);\n if (m) {\n const [whole, bang, label, url] = m;\n flushBuf();\n if (bang) {\n tokens.push({ type: \"marker\", text: \"!\", format: \"link\" });\n }\n tokens.push({ type: \"marker\", text: \"[\", format: \"link\" });\n tokens.push({ type: \"formatted\", text: label, format: \"link\" });\n tokens.push({ type: \"marker\", text: \"](\", format: \"link\" });\n tokens.push({ type: \"formatted\", text: url, format: \"code\" });\n tokens.push({ type: \"marker\", text: \")\", format: \"link\" });\n i += whole.length;\n continue;\n }\n }\n\n // 2) Paired inline markers — bold / italic / strike / code.\n let matched = false;\n for (const pat of PAIRED_PATTERNS) {\n if (!text.startsWith(pat.open, i)) continue;\n const searchStart = i + pat.open.length;\n let endIdx = -1;\n let probe = searchStart;\n while (probe < text.length) {\n const candidate = text.indexOf(pat.close, probe);\n if (candidate === -1) break;\n // Reject doubled-marker false positives for single-char patterns.\n if (pat.open.length === 1) {\n const prev = text[candidate - 1];\n const next = text[candidate + 1];\n if (prev === pat.close || next === pat.close) {\n probe = candidate + 1;\n continue;\n }\n }\n endIdx = candidate;\n break;\n }\n if (endIdx === -1) continue;\n const inner = text.slice(searchStart, endIdx);\n if (isInvalidInner(inner)) continue;\n // Don't let single-char `*italic*` / `_italic_` / `~strike~` swallow\n // a half-typed double pair. We check BOTH sides of the open:\n //\n // text[i+1] === open → we're the first of a `**` opener that the\n // user is still typing (`**hello**`).\n // text[i-1] === open → we're the second of a `**` opener that\n // already exists; matching here would eat\n // half the bold marker.\n //\n // The second check matters especially in `live` mode: matching the\n // italic on `**test*` would consume the inner `*`s the moment the\n // 7th char is typed, leaving the closing 8th `*` orphaned — the\n // bold pair could then never form. In hybrid mode the markers stay\n // visible so the next keystroke recovers, but the visual flicker is\n // still unwanted. Both modes benefit from the symmetric guard.\n if (pat.open.length === 1) {\n if (text[i + 1] === pat.open[0]) continue;\n if (text[i - 1] === pat.open[0]) continue;\n }\n flushBuf();\n tokens.push({ type: \"marker\", text: pat.open, format: pat.format });\n tokens.push({ type: \"formatted\", text: inner, format: pat.format });\n tokens.push({ type: \"marker\", text: pat.close, format: pat.format });\n i = endIdx + pat.close.length;\n matched = true;\n break;\n }\n if (matched) continue;\n\n buf += text[i];\n i += 1;\n }\n flushBuf();\n return tokens;\n}\n\n/** Concatenated text length of a token. */\nexport function tokenLength(t: Token): number {\n return t.text.length;\n}","/**\n * Unified Slack-style markdown plugin.\n *\n * Two operating modes, picked via `features.markdown.mode`:\n *\n * - **hybrid** (default): ALL markdown markers stay visible AND apply\n * visual styling. The paragraph's text content IS the markdown source.\n * Nothing is converted to a different Lexical node.\n *\n * - **live**: Notion-style. Markers vanish once matched; the format\n * flags / stashed marker / LinkTextNode become the source of truth.\n * The serializer reconstructs the markdown on submit.\n *\n * Responsibilities (all rolled into one plugin so the rules stay consistent):\n *\n * 1. Inline tokenization\n * `**bold**`, `*italic*`, `_italic_`, `~~strike~~`, `` `code` ``,\n * `[label](url)`, ``. Hybrid: markers rendered as muted\n * `MarkdownTokenNode`s, body picks up format flags. Live: markers\n * dropped from the visible text; format flags / LinkTextNode hold\n * the state needed to rebuild the source.\n *\n * 2. Block-marker tokenization (leading marker of the paragraph)\n * `# `, `> `, `- `, `1. `, ```` ``` ``` `` — hybrid mode emits a\n * muted token; live mode stashes the marker on the\n * `BlockParagraphNode` (via `__blockMarker`) and drops the visible\n * chars so the user sees only the heading / quote / list body.\n *\n * 3. Block styling via DOM attribute\n * Each paragraph DOM element receives `data-md-block=\"<kind>\"` (e.g.\n * `heading-2`, `code-line`, `quote`). CSS does the actual visual work\n * (font sizes, indentation, monospace, left border, etc.). In live\n * mode the kind is resolved from the stashed marker, so styling\n * survives the marker chars being hidden.\n *\n * 4. Backspace-at-start escape (live mode only)\n * Backspace pressed at column 0 of a paragraph with a stashed block\n * marker clears the marker instead of merging up — the only way to\n * remove a heading style when the `# ` chars aren't visible.\n *\n * Re-entrancy: a single tagged `editor.update` is scheduled per real user\n * change and re-styles every paragraph idempotently. This catches \"context\"\n * changes (typing ```` ``` ```` shifts every paragraph below into a code\n * block) without per-paragraph propagation gymnastics.\n */\n\nimport { useEffect, useRef } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isParagraphNode,\n $isRangeSelection,\n $isTextNode,\n COMMAND_PRIORITY_LOW,\n KEY_BACKSPACE_COMMAND,\n type ParagraphNode,\n} from \"lexical\";\nimport {\n $createMarkdownTokenNode,\n $isMarkdownTokenNode,\n} from \"../core/nodes/MarkdownTokenNode\";\nimport {\n $isBlockParagraphNode,\n type BlockParagraphNode,\n} from \"../core/nodes/BlockParagraphNode\";\nimport {\n $createLinkTextNode,\n $isLinkTextNode,\n} from \"../core/nodes/LinkTextNode\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { MarkdownMode } from \"../types\";\nimport { tokenize, type InlineFormat, type Token } from \"./markdown-tokenizer\";\nimport {\n $computeBlockMap,\n $detectBlockFor,\n type BlockInfo,\n type BlockKind,\n} from \"./markdown-blocks\";\n\n// Lexical format flag bits — using `code` for inline code and reusing it for\n// link URLs so they render with a monospace tint. `link` doesn't map to a\n// native Lexical bit; we surface it via the token coloring instead.\nconst FORMAT_FLAGS: Record<InlineFormat, number> = {\n bold: 1,\n italic: 2,\n strike: 4,\n underline: 8,\n code: 16,\n link: 0,\n};\n\ninterface DesiredNode {\n kind: \"text\" | \"token\" | \"link\";\n text: string;\n format: number;\n /** Populated for `link` kind only — the URL to stash on the LinkTextNode. */\n url?: string;\n}\n\nfunction readCurrentChildren(paragraph: ParagraphNode): DesiredNode[] | null {\n const out: DesiredNode[] = [];\n for (const child of paragraph.getChildren()) {\n // LinkTextNode is also a TextNode subclass — check it BEFORE the\n // generic text branch so its URL gets surfaced in the diff.\n if ($isLinkTextNode(child)) {\n out.push({\n kind: \"link\",\n text: child.getTextContent(),\n format: child.getFormat(),\n url: child.getUrl(),\n });\n } else if ($isMarkdownTokenNode(child)) {\n out.push({ kind: \"token\", text: child.getTextContent(), format: 0 });\n } else if ($isTextNode(child)) {\n out.push({\n kind: \"text\",\n text: child.getTextContent(),\n format: child.getFormat(),\n });\n } else {\n // Mentions / other inlines — bail out so we don't disturb them.\n return null;\n }\n }\n return out;\n}\n\nfunction nodesEqual(a: DesiredNode[], b: DesiredNode[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const ai = a[i];\n const bi = b[i];\n // `text` and `link` are interchangeable for equality purposes: on a\n // subsequent pass the tokenizer no longer sees the URL (it's hidden\n // on the LinkTextNode) and emits a plain text token. Treating them\n // as equal here prevents a wasteful rewrite that would discard the\n // URL. The writer preserves the LinkTextNode in this case.\n const aKind = ai.kind === \"link\" ? \"text\" : ai.kind;\n const bKind = bi.kind === \"link\" ? \"text\" : bi.kind;\n if (aKind !== bKind) return false;\n if (ai.text !== bi.text) return false;\n if (ai.format !== bi.format) return false;\n }\n return true;\n}\n\nfunction getSelectionOffsetWithin(\n paragraph: ParagraphNode,\n): { anchor: number; focus: number } | null {\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return null;\n\n const measure = (key: string, offset: number): number | null => {\n let acc = 0;\n for (const child of paragraph.getChildren()) {\n if (child.getKey() === key) return acc + offset;\n acc += child.getTextContentSize();\n }\n return null;\n };\n\n const measureNodeOffset = (key: string, offset: number): number | null => {\n if (paragraph.getKey() === key) {\n let acc = 0;\n const children = paragraph.getChildren();\n for (let i = 0; i < Math.min(offset, children.length); i++) {\n acc += children[i].getTextContentSize();\n }\n return acc;\n }\n return measure(key, offset);\n };\n\n const a = measureNodeOffset(selection.anchor.key, selection.anchor.offset);\n const f = measureNodeOffset(selection.focus.key, selection.focus.offset);\n if (a === null || f === null) return null;\n return { anchor: a, focus: f };\n}\n\nfunction setSelectionFromOffsets(\n paragraph: ParagraphNode,\n offsets: { anchor: number; focus: number },\n): void {\n type Point = { key: string; offset: number; type: \"text\" | \"element\" };\n const locate = (target: number): Point | null => {\n const children = paragraph.getChildren();\n if (children.length === 0) {\n // Empty paragraph (e.g. a live-mode heading where the user hasn't\n // typed a body yet, or a hidden code-fence line) — Lexical\n // represents the caret as an element-type point.\n return { key: paragraph.getKey(), offset: 0, type: \"element\" };\n }\n let acc = 0;\n for (const child of children) {\n const size = child.getTextContentSize();\n if (target <= acc + size) {\n return {\n key: child.getKey(),\n offset: Math.max(0, target - acc),\n type: \"text\",\n };\n }\n acc += size;\n }\n const last = children[children.length - 1];\n return {\n key: last.getKey(),\n offset: last.getTextContentSize(),\n type: \"text\",\n };\n };\n\n const a = locate(offsets.anchor);\n const f = locate(offsets.focus);\n if (!a || !f) return;\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return;\n selection.anchor.set(a.key, a.offset, a.type);\n selection.focus.set(f.key, f.offset, f.type);\n}\n\nfunction isCodeKind(kind: BlockKind): boolean {\n return (\n kind === \"code-line\" ||\n kind === \"code-fence-open\" ||\n kind === \"code-fence-close\"\n );\n}\n\n/**\n * Walk the paragraph's existing children and produce a per-character map of\n * the format flags currently in effect. Used by live-mode `$applyStyling`\n * so plain-text tokens (i.e. text the new tokenizer pass doesn't claim\n * with a marker) keep whatever format they had before — without this we'd\n * lose every previously-applied format on the very next keystroke (the\n * paragraph text no longer contains `**` markers, so the tokenizer just\n * sees plain text and would otherwise reset the format to 0).\n *\n * MarkdownTokenNodes (block-marker leaders) are counted as format=0 even\n * though they're TextNode subclasses; that matches what `$applyStyling`\n * emits for the block prefix in live mode.\n */\nfunction buildCurrentFormatMap(paragraph: ParagraphNode): number[] {\n const out: number[] = [];\n for (const child of paragraph.getChildren()) {\n if (!$isTextNode(child)) continue;\n const text = child.getTextContent();\n const fmt = $isMarkdownTokenNode(child) ? 0 : child.getFormat();\n for (let i = 0; i < text.length; i++) out.push(fmt);\n }\n return out;\n}\n\n/**\n * Build a function that maps a SOURCE-text offset (the paragraph before the\n * rewrite, which still contains every character the user typed) to a TARGET\n * offset (the paragraph after the rewrite, where in `live` mode the inline\n * marker characters have been dropped).\n *\n * In `hybrid` mode the mapping is the identity, so we skip this work\n * entirely and let the caller pass source offsets straight through.\n *\n * In `live` mode only INLINE markers are dropped — block markers stay\n * visible (see `$applyStyling`). So the prefix-sum starts by keeping the\n * leading block-marker chars 1:1 and only marks inline `marker` tokens as\n * dropped. The caret then lands at the end of the visible content — the\n * same place it would have been if the inline markers had been invisible\n * all along.\n */\n/**\n * For each inline token, decide whether its chars stay visible (`true`) or\n * are dropped (`false`) in `live` mode. Markers are always dropped. Most\n * `formatted` tokens are kept. Link sequences are a special case: the\n * label stays visible, the URL is dropped (it's stashed on a LinkTextNode\n * by the desired-children pass).\n */\nfunction buildKeptMask(tokens: Token[]): boolean[] {\n const mask = new Array<boolean>(tokens.length);\n for (let i = 0; i < tokens.length; i++) {\n mask[i] = tokens[i].type !== \"marker\";\n }\n // Walk again to look for link sequences and flip the URL token off.\n // Mirrors the detection in `$applyStyling`'s token loop — keep these\n // in sync.\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i];\n if (t.type !== \"marker\") continue;\n if (t.text !== \"[\" && t.text !== \"!\") continue;\n const offset = t.text === \"!\" ? 1 : 0;\n const open = tokens[i + offset];\n const label = tokens[i + offset + 1];\n const mid = tokens[i + offset + 2];\n const url = tokens[i + offset + 3];\n const close = tokens[i + offset + 4];\n if (\n open?.type === \"marker\" &&\n open.text === \"[\" &&\n label?.type === \"formatted\" &&\n label.format === \"link\" &&\n mid?.type === \"marker\" &&\n mid.text === \"](\" &&\n url?.type === \"formatted\" &&\n close?.type === \"marker\" &&\n close.text === \")\"\n ) {\n mask[i + offset + 3] = false; // URL — dropped\n }\n }\n return mask;\n}\n\nfunction buildLiveOffsetMap(\n text: string,\n leadingDrop: number,\n tokens: Token[] | null,\n trailingDrop: number = 0,\n): (srcOffset: number) => number {\n const kept = new Array<number>(text.length + 1);\n kept[0] = 0;\n let cursor = 0;\n // Leading block-marker chars that we just stashed on the paragraph in\n // live mode → dropped (mapped to target offset 0).\n for (let i = 0; i < leadingDrop && cursor < text.length; i++) {\n kept[cursor + 1] = kept[cursor];\n cursor++;\n }\n // Inline body — walk tokens in order. Drop / keep per `buildKeptMask`\n // so link-sequence collapsing (URL → dropped) matches the desired-\n // children pass. (HR / code-line / code-fence paragraphs pass `null`\n // for `tokens` because we don't tokenize inline markers inside them.)\n if (tokens) {\n const mask = buildKeptMask(tokens);\n for (let ti = 0; ti < tokens.length; ti++) {\n const t = tokens[ti];\n const isKept = mask[ti];\n for (let i = 0; i < t.text.length && cursor < text.length; i++) {\n kept[cursor + 1] = kept[cursor] + (isKept ? 1 : 0);\n cursor++;\n }\n }\n }\n // Any chars that aren't covered by leadingDrop or tokens — the trailing\n // run, normally kept verbatim. `trailingDrop` lets the caller mark the\n // last N source chars as dropped (used for code-fence close lines in\n // live mode, where the whole text becomes invisible).\n const trailDropStart = text.length - trailingDrop;\n for (; cursor < text.length; cursor++) {\n const dropped = cursor >= trailDropStart;\n kept[cursor + 1] = kept[cursor] + (dropped ? 0 : 1);\n }\n return (srcOffset: number) =>\n kept[Math.max(0, Math.min(srcOffset, text.length))];\n}\n\nfunction $applyStyling(\n paragraph: ParagraphNode,\n block: BlockInfo,\n mode: MarkdownMode,\n): boolean {\n const text = paragraph.getTextContent();\n\n const current = readCurrentChildren(paragraph);\n if (current === null) return false; // contains non-text inlines\n\n const desired: DesiredNode[] = [];\n const isLive = mode === \"live\";\n\n // Per-character format map of what's CURRENTLY in the paragraph, only\n // needed in live mode. Used so plain-text tokens (text the new\n // tokenizer pass doesn't claim with a marker pair) keep whatever\n // format they had before. Without this, typing any character after a\n // matched `**bold**` re-runs the plugin, the tokenizer sees no\n // markers, and we'd drop bold back to plain text — the regression\n // that triggered this code path.\n const currentFmt = isLive ? buildCurrentFormatMap(paragraph) : null;\n\n // ─── Block marker handling ──────────────────────────────────────────────\n //\n // Hybrid mode: keep the marker chars in the visible text, emit them as a\n // muted MarkdownTokenNode. The user sees `# Heading` with `# ` greyed\n // out, the text content is the markdown source verbatim.\n //\n // Live mode: hide the marker entirely. We stash the marker string on the\n // BlockParagraphNode so the serializer can rebuild `# Heading` on submit,\n // then drop the chars from the visible body.\n //\n // Also handles mode toggling:\n // live → hybrid: a paragraph with a stashed marker has it promoted\n // back to a visible token, and the caret shifts right\n // by markerLen so it stays on the same character.\n // hybrid → live: visible marker chars in the text get stashed and\n // sliced off; caret is mapped via buildLiveOffsetMap.\n const stashedNow =\n $isBlockParagraphNode(paragraph) ? paragraph.getBlockMarker() : \"\";\n let body = text;\n let stashedMarkerForOffsetMap = \"\"; // chars we just sliced off (live-mode pass)\n let hybridPromoteShift = 0; // chars we just put BACK (hybrid promote)\n if (block.markerLen > 0 && text.length >= block.markerLen) {\n const marker = text.slice(0, block.markerLen);\n if (isLive) {\n if (stashedNow !== marker && $isBlockParagraphNode(paragraph)) {\n paragraph.setBlockMarker(marker);\n }\n stashedMarkerForOffsetMap = marker;\n body = text.slice(marker.length);\n } else {\n desired.push({ kind: \"token\", text: marker, format: 0 });\n body = text.slice(marker.length);\n // Hybrid mode shouldn't carry a stale stash from a previous live run.\n if (stashedNow.length > 0 && $isBlockParagraphNode(paragraph)) {\n paragraph.setBlockMarker(\"\");\n }\n }\n } else if (!isLive && stashedNow.length > 0) {\n // Mode toggle: live → hybrid. Surface the hidden marker so the user\n // sees the raw markdown again. Clearing the stash here means\n // subsequent hybrid passes detect it from the (now visible) text.\n desired.push({ kind: \"token\", text: stashedNow, format: 0 });\n hybridPromoteShift = stashedNow.length;\n if ($isBlockParagraphNode(paragraph)) {\n paragraph.setBlockMarker(\"\");\n }\n }\n\n // Track absolute source position as we walk the inline tokens, so plain\n // text tokens can look up their existing format from `currentFmt`. In\n // hybrid mode the block marker contributes `markerLen` chars (the\n // visible muted token), in live-mode case (a) we've sliced them off so\n // srcPos starts at the same offset but the live offset map will\n // collapse them.\n let srcPos = block.markerLen;\n\n // We capture the inline-tokenizer result so the live-mode offset map can\n // see exactly which chars are markers. Code / HR paragraphs skip inline\n // tokenization (their content is rendered verbatim) so they pass null.\n let inlineTokens: Token[] | null = null;\n // Code-fence open/close lines in live mode: their whole text IS the\n // marker (`` ``` `` or ` ```lang `). Stash on the paragraph and drop the\n // visible body so the paragraph renders as an empty styled divider.\n // Tracked separately from `stashedMarkerForOffsetMap` because the source\n // chars here aren't a `markerLen` prefix — they're the entire body.\n let trailingDropForOffsetMap = 0;\n if (isCodeKind(block.kind)) {\n if (\n isLive &&\n (block.kind === \"code-fence-open\" || block.kind === \"code-fence-close\") &&\n body.length > 0 &&\n $isBlockParagraphNode(paragraph)\n ) {\n // The fence line. Stash it and emit nothing; CSS handles the visual.\n if (paragraph.getBlockMarker() !== body) {\n paragraph.setBlockMarker(body);\n }\n trailingDropForOffsetMap = body.length;\n body = \"\";\n } else if (body.length > 0) {\n // Hybrid mode, or code-line content — render verbatim.\n desired.push({ kind: \"text\", text: body, format: 0 });\n }\n } else if (block.kind === \"hr\") {\n // HR is a special case: in hybrid mode the whole line is a token so\n // CSS can paint a rule across it. In live mode we collapse it the\n // same way so the user can still see / edit / delete the `---` they\n // typed — a fully-invisible HR would be undeletable without remembering\n // it's there. (Real Notion-style HRs would need a DecoratorNode, which\n // is more work than this flag merits for v1.)\n if (body.length > 0) {\n desired.push({ kind: \"token\", text: body, format: 0 });\n }\n } else {\n inlineTokens = tokenize(body);\n for (let ti = 0; ti < inlineTokens.length; ti++) {\n const t = inlineTokens[ti];\n const tokenLen = t.text.length;\n\n // ─── Link sequence (live mode collapse) ────────────────────────────\n // Tokens for `[label](url)` come as: marker `[`, formatted label,\n // marker `](`, formatted url (in code format), marker `)`. Image\n // links additionally start with a marker `!`. In live mode we\n // collapse the whole sequence into a single LinkTextNode that\n // shows the label and remembers the URL — the markers + URL\n // vanish from the visible text. Hybrid mode falls through to the\n // regular per-token rendering below.\n if (\n isLive &&\n t.type === \"marker\" &&\n (t.text === \"[\" || t.text === \"!\") &&\n ti + 4 < inlineTokens.length\n ) {\n const offset = t.text === \"!\" ? 1 : 0; // skip the bang for images\n const open = inlineTokens[ti + offset];\n const label = inlineTokens[ti + offset + 1];\n const mid = inlineTokens[ti + offset + 2];\n const url = inlineTokens[ti + offset + 3];\n const close = inlineTokens[ti + offset + 4];\n if (\n open?.type === \"marker\" &&\n open.text === \"[\" &&\n label?.type === \"formatted\" &&\n label.format === \"link\" &&\n mid?.type === \"marker\" &&\n mid.text === \"](\" &&\n url?.type === \"formatted\" &&\n close?.type === \"marker\" &&\n close.text === \")\"\n ) {\n desired.push({\n kind: \"link\",\n text: label.text,\n format: 0,\n url: url.text,\n });\n // Advance srcPos past every consumed token (including the\n // optional leading `!`) so the format map / offset map stay\n // in lockstep with the source text.\n srcPos += t.text.length;\n if (offset === 1) {\n // Already counted the `!` above; advance past the rest.\n srcPos +=\n open.text.length +\n label.text.length +\n mid.text.length +\n url.text.length +\n close.text.length;\n ti += 5;\n } else {\n srcPos +=\n label.text.length +\n mid.text.length +\n url.text.length +\n close.text.length;\n ti += 4;\n }\n continue;\n }\n }\n\n if (t.type === \"marker\") {\n if (!isLive) {\n desired.push({ kind: \"token\", text: t.text, format: 0 });\n }\n // live mode → drop the marker chars from the output\n } else if (t.type === \"formatted\") {\n // Fresh marker pair in the source text — use its format. We\n // deliberately don't OR in the existing format here: the\n // pre-existing chars under this token (in live mode) had a\n // format inherited from typing context, and the user's\n // intent when wrapping with markers is to *set* the new\n // format, not combine it.\n desired.push({\n kind: \"text\",\n text: t.text,\n format: FORMAT_FLAGS[t.format],\n });\n } else if (isLive && currentFmt) {\n // Plain text in live mode — preserve the existing per-char\n // format. Walk the source range, split into runs of equal\n // format so each run becomes its own DesiredNode (Lexical\n // merges them later if formats match adjacent nodes anyway).\n let runStart = 0;\n let runFmt = currentFmt[srcPos] ?? 0;\n for (let i = 1; i < tokenLen; i++) {\n const f = currentFmt[srcPos + i] ?? 0;\n if (f !== runFmt) {\n desired.push({\n kind: \"text\",\n text: t.text.slice(runStart, i),\n format: runFmt,\n });\n runStart = i;\n runFmt = f;\n }\n }\n desired.push({\n kind: \"text\",\n text: t.text.slice(runStart),\n format: runFmt,\n });\n } else {\n // Plain text in hybrid mode — format is always 0; the only way\n // text gets a format in hybrid is via a `formatted` token.\n desired.push({ kind: \"text\", text: t.text, format: 0 });\n }\n srcPos += tokenLen;\n }\n }\n\n if (nodesEqual(current, desired)) return false;\n\n // Snapshot URLs from any existing LinkTextNodes so a rewrite triggered\n // by an unrelated change (e.g. typing after a link) can re-attach them\n // to the rebuilt text nodes. Keyed by visible label — duplicates inside\n // the same paragraph fall back to the first match.\n const preservedLinkUrls = new Map<string, string>();\n for (const child of paragraph.getChildren()) {\n if ($isLinkTextNode(child)) {\n const label = child.getTextContent();\n const url = child.getUrl();\n if (label && url && !preservedLinkUrls.has(label)) {\n preservedLinkUrls.set(label, url);\n }\n }\n }\n\n const srcOffsets = getSelectionOffsetWithin(paragraph);\n for (const child of paragraph.getChildren()) child.remove();\n for (const node of desired) {\n if (node.kind === \"token\") {\n paragraph.append($createMarkdownTokenNode(node.text));\n } else if (node.kind === \"link\") {\n const t = $createLinkTextNode(node.text, node.url ?? \"\");\n if (node.format !== 0) t.setFormat(node.format);\n paragraph.append(t);\n } else {\n // Plain text — but if this label was previously a LinkTextNode, the\n // URL has only been \"hidden\" by the latest tokenizer pass; restore\n // it so the link survives unrelated paragraph edits.\n const preservedUrl = preservedLinkUrls.get(node.text);\n const t = preservedUrl\n ? $createLinkTextNode(node.text, preservedUrl)\n : $createTextNode(node.text);\n if (node.format !== 0) t.setFormat(node.format);\n paragraph.append(t);\n }\n }\n // Caret restoration:\n // live mode — prefix-sum offset map (we just dropped some chars).\n // hybrid mode — identity, except on a `live → hybrid` promotion where\n // we put `hybridPromoteShift` chars BACK at the start of\n // the paragraph and need to push the caret right.\n if (srcOffsets) {\n if (isLive) {\n const map = buildLiveOffsetMap(\n text,\n stashedMarkerForOffsetMap.length,\n inlineTokens,\n trailingDropForOffsetMap,\n );\n setSelectionFromOffsets(paragraph, {\n anchor: map(srcOffsets.anchor),\n focus: map(srcOffsets.focus),\n });\n } else {\n setSelectionFromOffsets(paragraph, {\n anchor: srcOffsets.anchor + hybridPromoteShift,\n focus: srcOffsets.focus + hybridPromoteShift,\n });\n }\n }\n return true;\n}\n\nfunction $restyleAllParagraphs(mode: MarkdownMode): void {\n const root = $getRoot();\n const map = $computeBlockMap();\n for (const child of root.getChildren()) {\n if (!$isParagraphNode(child)) continue;\n const info = map.get(child.getKey()) ?? $detectBlockFor(child);\n $applyStyling(child, info, mode);\n }\n}\n\n/**\n * UX nicety: when a paragraph transitions to `code-fence-close` and is the\n * last block in the document, append an empty paragraph after it and move\n * the caret there. This way typing ```` ``` ```` to close a code block also\n * \"exits\" the block — the user can immediately start typing the next message\n * line (or press Enter to submit). They can still arrow / click back into\n * the close-fence line to edit it.\n *\n * Triggered only on the *transition* into the close kind (tracked via\n * `prevKinds`) so navigating back to the line and re-entering it doesn't\n * keep appending paragraphs.\n */\nfunction $autoEscapeClosedFence(prevKinds: Map<string, BlockKind>): void {\n const map = $computeBlockMap();\n const root = $getRoot();\n\n for (const child of root.getChildren()) {\n if (!$isParagraphNode(child)) continue;\n const key = child.getKey();\n const info = map.get(key);\n if (!info) continue;\n const oldKind = prevKinds.get(key);\n if (\n info.kind === \"code-fence-close\" &&\n oldKind !== \"code-fence-close\" &&\n child.getNextSibling() === null\n ) {\n const next = $createParagraphNode();\n child.insertAfter(next);\n next.select();\n }\n }\n\n prevKinds.clear();\n for (const [k, v] of map) prevKinds.set(k, v.kind);\n}\n\nconst BLOCK_ATTR = \"data-md-block\";\nconst LANG_ATTR = \"data-md-lang\";\n\nfunction syncBlockAttributes(\n editor: ReturnType<typeof useLexicalComposerContext>[0],\n): void {\n editor.getEditorState().read(() => {\n const root = editor.getRootElement();\n if (!root) return;\n\n const seen = new Set<HTMLElement>();\n const map = $computeBlockMap();\n for (const [key, info] of map) {\n const el = editor.getElementByKey(key);\n if (!(el instanceof HTMLElement)) continue;\n seen.add(el);\n if (info.kind === \"paragraph\") {\n if (el.hasAttribute(BLOCK_ATTR)) el.removeAttribute(BLOCK_ATTR);\n } else {\n if (el.getAttribute(BLOCK_ATTR) !== info.kind) {\n el.setAttribute(BLOCK_ATTR, info.kind);\n }\n }\n // Language tag (code-fence-open only) — used by CSS to render a\n // small label since the visible `` ```ts `` chars are hidden in\n // live mode. Cleared for non-fence-open blocks so a paragraph that\n // *was* a fence and is now plain doesn't keep a stale label.\n if (info.kind === \"code-fence-open\" && info.lang) {\n if (el.getAttribute(LANG_ATTR) !== info.lang) {\n el.setAttribute(LANG_ATTR, info.lang);\n }\n } else if (el.hasAttribute(LANG_ATTR)) {\n el.removeAttribute(LANG_ATTR);\n }\n }\n\n // Strip the attribute from any paragraph the reconciler kept around but\n // that we no longer recognise (defensive — e.g. after delete).\n const stale = root.querySelectorAll<HTMLElement>(`[${BLOCK_ATTR}]`);\n stale.forEach((el) => {\n if (!seen.has(el)) {\n el.removeAttribute(BLOCK_ATTR);\n el.removeAttribute(LANG_ATTR);\n }\n });\n });\n}\n\nconst RESTYLE_TAG = \"md-restyle\";\n\nexport function MarkdownPlugin() {\n const [editor] = useLexicalComposerContext();\n const { markdownMode } = useComposerContext();\n const prevKindsRef = useRef<Map<string, BlockKind>>(new Map());\n // Ref-mirror so the long-lived update listener inside the effect always\n // sees the current mode without being torn down on every flag change.\n // (Effect itself depends on `markdownMode` too, so when it actually\n // changes we also re-run the initial restyle pass below.)\n const modeRef = useRef<MarkdownMode>(markdownMode);\n modeRef.current = markdownMode;\n\n useEffect(() => {\n const prevKinds = prevKindsRef.current;\n // Initial pass so any `initialValue` gets styled immediately, AND so\n // toggling between modes at runtime restyles the document end-to-end\n // (collapsing markers when switching to `live`, re-emitting them when\n // switching back to `hybrid`). We seed `prevKinds` with the\n // *post-style* state so the auto-escape doesn't fire on a fence the\n // user pre-loaded as initial content.\n editor.update(\n () => {\n $restyleAllParagraphs(modeRef.current);\n const map = $computeBlockMap();\n prevKinds.clear();\n for (const [k, v] of map) prevKinds.set(k, v.kind);\n },\n { tag: RESTYLE_TAG },\n );\n syncBlockAttributes(editor);\n\n let scheduled = false;\n\n const unregisterUpdate = editor.registerUpdateListener(\n ({ tags, dirtyElements, dirtyLeaves }) => {\n // DOM attributes are pure — sync after every render.\n syncBlockAttributes(editor);\n\n // Re-style content only when something actually changed and the\n // change wasn't our own restyle pass.\n if (tags.has(RESTYLE_TAG)) return;\n if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return;\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n editor.update(\n () => {\n $restyleAllParagraphs(modeRef.current);\n $autoEscapeClosedFence(prevKinds);\n },\n { tag: RESTYLE_TAG },\n );\n });\n },\n );\n\n // Backspace at the start of a live-mode paragraph that carries a\n // stashed block marker → clear the marker instead of merging up. This\n // is the only way for the user to \"remove the heading style\" since\n // the `# ` chars aren't in the visible text anymore. Mirrors Notion's\n // behaviour: backspace at the start of a heading converts it to plain.\n const unregisterBackspace = editor.registerCommand(\n KEY_BACKSPACE_COMMAND,\n () => {\n if (modeRef.current !== \"live\") return false;\n const selection = $getSelection();\n if (!$isRangeSelection(selection) || !selection.isCollapsed()) {\n return false;\n }\n if (selection.anchor.offset !== 0) return false;\n\n const anchor = selection.anchor.getNode();\n const top = anchor.getTopLevelElement();\n if (!top || !$isParagraphNode(top)) return false;\n if (!$isBlockParagraphNode(top)) return false;\n if (!(top as BlockParagraphNode).hasBlockMarker()) return false;\n\n // Verify the cursor is at the very start of the visible body\n // (offset 0 in the first child, or element-type at the paragraph).\n if (selection.anchor.type === \"element\") {\n if (selection.anchor.getNode().getKey() !== top.getKey()) {\n return false;\n }\n } else {\n const first = top.getFirstChild();\n if (!first || first.getKey() !== anchor.getKey()) return false;\n }\n\n editor.update(() => {\n const latest = top.getLatest();\n if ($isBlockParagraphNode(latest)) {\n (latest as BlockParagraphNode).setBlockMarker(\"\");\n }\n });\n return true;\n },\n COMMAND_PRIORITY_LOW,\n );\n\n return () => {\n unregisterUpdate();\n unregisterBackspace();\n };\n }, [editor, markdownMode]);\n\n return null;\n}","import { useEffect, useState, type ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\n/** Internal portal — used by ImageLightbox. Mounts after first effect. */\nexport function Portal({ children }: { children: ReactNode }) {\n const [mounted, setMounted] = useState(false);\n useEffect(() => {\n setMounted(true);\n }, []);\n if (!mounted) return null;\n return createPortal(children, document.body);\n}","import { useEffect } from \"react\";\nimport { Portal } from \"../internal/Portal\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n src: string;\n alt: string;\n onClose: () => void;\n}\n\nexport function ImageLightbox({ src, alt, onClose }: Props) {\n const { icons, tokenStyle } = useComposerContext();\n const { close: CloseIcon } = icons;\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") onClose();\n };\n document.addEventListener(\"keydown\", onKey);\n const prev = document.body.style.overflow;\n document.body.style.overflow = \"hidden\";\n return () => {\n document.removeEventListener(\"keydown\", onKey);\n document.body.style.overflow = prev;\n };\n }, [onClose]);\n\n return (\n <Portal>\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n className=\"fixed inset-0 z-50 flex items-center justify-center p-6\"\n style={tokenStyle}\n >\n <div\n aria-hidden\n className=\"absolute inset-0 bg-foreground/70 backdrop-blur-sm\"\n onClick={onClose}\n />\n <button\n type=\"button\"\n onClick={onClose}\n aria-label=\"Close\"\n className=\"absolute end-5 top-5 flex h-9 w-9 items-center justify-center rounded-full bg-card text-foreground shadow-soft transition-colors hover:bg-accent\"\n >\n <CloseIcon className=\"h-4 w-4\" />\n </button>\n <img\n src={src}\n alt={alt}\n className=\"relative max-h-[85vh] max-w-[85vw] rounded-lg object-contain shadow-xl\"\n />\n </div>\n </Portal>\n );\n}","/**\n * MermaidPlugin — detects ```mermaid code blocks inside the editor and shows\n * an inline preview row below the contenteditable surface.\n *\n * Rendering strategy (in priority order):\n * 1. If the consumer supplied a `renderDiagram` prop on <Composer />, every\n * detected diagram is delegated to that callback. The `mermaid` package\n * is never loaded, so consumers who already own a diagram pipeline can\n * omit `mermaid` from their install entirely.\n * 2. Otherwise, the optional `mermaid` peer package is dynamic-imported on\n * first sighting. If the import fails (package not installed), we log\n * one friendly warning and render a small \"install mermaid or pass\n * renderDiagram\" hint in place of the diagram.\n *\n * When `features.mermaid.keepSource === false`, the raw ```mermaid code\n * blocks are visually hidden from the editor (still present in the editor\n * state, so they survive serialization) — only the rendered diagram tiles\n * are shown. Default is `true` so the user keeps seeing the code they\n * authored alongside the live preview.\n */\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { $getRoot, $isParagraphNode } from \"lexical\";\nimport { ImageLightbox } from \"../ui/ImageLightbox\";\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { DiagramRenderer } from \"../types\";\n\ninterface DetectedDiagram {\n /** Stable id — paragraph key of the opening ```mermaid fence. */\n id: string;\n code: string;\n /** Keys of every paragraph that participates in this diagram (open fence,\n * code lines, optional close fence) so we can hide them in `!keepSource`. */\n paragraphKeys: string[];\n}\n\nconst FENCE_OPEN_MERMAID = /^```mermaid(?:\\s.*)?$/;\nconst FENCE_CLOSE = /^```\\s*$/;\n\n// Type-only — the actual module is loaded lazily and is optional.\ntype MermaidModule = {\n initialize: (config: Record<string, unknown>) => void;\n render: (id: string, code: string) => Promise<{ svg: string }>;\n};\n\nlet mermaidPromise: Promise<MermaidModule | null> | null = null;\nlet mermaidInitialized = false;\nlet mermaidMissingWarned = false;\n\nasync function loadMermaid(): Promise<MermaidModule | null> {\n if (!mermaidPromise) {\n // Static string + plain dynamic import so bundlers (Vite, Webpack,\n // Rollup, ...) can statically analyze the dependency and produce a\n // properly resolved code-split chunk. We still catch runtime errors so\n // a transient network failure (chunk 404, CDN hiccup) degrades to the\n // friendly fallback tile instead of throwing into React.\n //\n // If `mermaid` is genuinely not in the consumer's `node_modules`, the\n // *build* fails with a clear \"Could not resolve 'mermaid'\" error and\n // the consumer either `npm install mermaid` or supplies a\n // `renderDiagram` prop (which short-circuits this entire code path).\n mermaidPromise = import(\"mermaid\")\n .then((m) => m.default as MermaidModule)\n .catch((err) => {\n if (!mermaidMissingWarned) {\n mermaidMissingWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n \"[composeai] Failed to load the `mermaid` package. \" +\n \"Either `npm install mermaid` or pass a `renderDiagram` prop \" +\n \"to <Composer /> to render diagrams yourself.\",\n err,\n );\n }\n return null;\n });\n }\n const mermaid = await mermaidPromise;\n if (mermaid && !mermaidInitialized) {\n mermaid.initialize({\n startOnLoad: false,\n theme: \"default\",\n securityLevel: \"strict\",\n fontFamily: \"inherit\",\n });\n mermaidInitialized = true;\n }\n return mermaid;\n}\n\nfunction svgToDataUri(svg: string): string {\n return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;\n}\n\nexport function MermaidPlugin() {\n const [editor] = useLexicalComposerContext();\n const { features, icons, renderDiagram, classNames, sx } = useComposerContext();\n const { sparkle: SparkleIcon } = icons;\n const [diagrams, setDiagrams] = useState<DetectedDiagram[]>([]);\n\n // Default `keepSource` to true (visible) — opt-in to hide.\n const keepSource =\n typeof features.mermaid === \"object\"\n ? features.mermaid.keepSource !== false\n : true;\n\n useEffect(() => {\n const sync = () => {\n editor.getEditorState().read(() => {\n const found: DetectedDiagram[] = [];\n const root = $getRoot();\n const children = root.getChildren();\n\n let i = 0;\n while (i < children.length) {\n const opener = children[i];\n if (!$isParagraphNode(opener) || !FENCE_OPEN_MERMAID.test(opener.getTextContent())) {\n i++;\n continue;\n }\n // Collect every following paragraph until a closing ``` fence or\n // a non-paragraph sibling.\n const paragraphKeys: string[] = [opener.getKey()];\n const codeLines: string[] = [];\n let j = i + 1;\n while (j < children.length) {\n const next = children[j];\n if (!$isParagraphNode(next)) break;\n const text = next.getTextContent();\n paragraphKeys.push(next.getKey());\n if (FENCE_CLOSE.test(text)) {\n j++;\n break;\n }\n codeLines.push(text);\n j++;\n }\n found.push({\n id: opener.getKey(),\n code: codeLines.join(\"\\n\").trim(),\n paragraphKeys,\n });\n i = j;\n }\n\n setDiagrams((prev) => {\n if (\n prev.length === found.length &&\n prev.every(\n (d, idx) =>\n d.id === found[idx].id &&\n d.code === found[idx].code &&\n d.paragraphKeys.length === found[idx].paragraphKeys.length &&\n d.paragraphKeys.every((k, kk) => k === found[idx].paragraphKeys[kk]),\n )\n ) {\n return prev;\n }\n return found;\n });\n });\n };\n sync();\n return editor.registerUpdateListener(sync);\n }, [editor]);\n\n // Hide / re-show the mermaid fence paragraphs based on `keepSource`. We\n // imperatively toggle `display` on the rendered DOM elements — Lexical\n // recreates them on each update so we re-apply after diagrams change.\n // The previously-hidden keys are tracked so we can clean up if a fence\n // is removed or shrunk.\n const hiddenKeysRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n const currentKeys = new Set<string>();\n for (const d of diagrams) for (const k of d.paragraphKeys) currentKeys.add(k);\n\n if (keepSource) {\n for (const key of hiddenKeysRef.current) {\n const el = editor.getElementByKey(key);\n if (el) el.style.removeProperty(\"display\");\n }\n hiddenKeysRef.current.clear();\n return;\n }\n\n for (const key of hiddenKeysRef.current) {\n if (!currentKeys.has(key)) {\n const el = editor.getElementByKey(key);\n if (el) el.style.removeProperty(\"display\");\n }\n }\n for (const key of currentKeys) {\n const el = editor.getElementByKey(key);\n if (el) el.style.display = \"none\";\n }\n hiddenKeysRef.current = currentKeys;\n }, [diagrams, keepSource, editor]);\n\n // On unmount, restore any blocks we hid so a future remount sees the\n // editor's natural rendering.\n useEffect(() => {\n return () => {\n for (const key of hiddenKeysRef.current) {\n const el = editor.getElementByKey(key);\n if (el) el.style.removeProperty(\"display\");\n }\n hiddenKeysRef.current.clear();\n };\n }, [editor]);\n\n if (diagrams.length === 0) return null;\n\n const preview = slotProps(\n \"mermaidPreview\",\n \"border-t border-border/60 bg-muted/30 px-4 py-3\",\n classNames,\n sx,\n );\n\n return (\n <div {...preview}>\n <div className=\"mb-1.5 flex items-center gap-1.5 text-[10px] font-medium uppercase tracking-wide text-muted-foreground\">\n <SparkleIcon className=\"h-3 w-3\" />\n Diagram preview\n </div>\n <div className=\"flex gap-2 overflow-x-auto scrollbar-thin\">\n {diagrams.map((d) => (\n <DiagramTile\n key={d.id}\n diagram={d}\n renderDiagram={renderDiagram}\n />\n ))}\n </div>\n </div>\n );\n}\n\ninterface TileProps {\n diagram: DetectedDiagram;\n renderDiagram?: DiagramRenderer;\n}\n\nfunction DiagramTile({ diagram, renderDiagram }: TileProps) {\n if (renderDiagram) {\n return <ConsumerTile diagram={diagram} renderDiagram={renderDiagram} />;\n }\n return <MermaidTile diagram={diagram} />;\n}\n\nfunction ConsumerTile({\n diagram,\n renderDiagram,\n}: {\n diagram: DetectedDiagram;\n renderDiagram: DiagramRenderer;\n}) {\n let content: ReactNode = null;\n try {\n content = renderDiagram({ code: diagram.code, language: \"mermaid\" });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[composeai] renderDiagram threw\", err);\n content = (\n <div className=\"flex h-24 w-40 items-center justify-center px-2 text-center text-[10px] text-destructive\">\n {err instanceof Error ? err.message.slice(0, 80) : \"Render failed\"}\n </div>\n );\n }\n return (\n <div className=\"shrink-0 overflow-hidden rounded-lg border border-border bg-card\">\n {content}\n </div>\n );\n}\n\nfunction MermaidTile({ diagram }: { diagram: DetectedDiagram }) {\n const { icons } = useComposerContext();\n const { zoom: ZoomIcon } = icons;\n const [svg, setSvg] = useState<string | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [zoom, setZoom] = useState(false);\n const [mermaidMissing, setMermaidMissing] = useState(false);\n const renderId = useMemo(\n () => `mermaid-${diagram.id}-${Math.random().toString(36).slice(2, 8)}`,\n [diagram.id],\n );\n\n useEffect(() => {\n let cancelled = false;\n if (!diagram.code) {\n setSvg(null);\n return;\n }\n loadMermaid()\n .then((mermaid) => {\n if (cancelled) return null;\n if (!mermaid) {\n setMermaidMissing(true);\n return null;\n }\n return mermaid.render(renderId, diagram.code);\n })\n .then((result) => {\n if (cancelled || !result) return;\n setSvg(result.svg);\n setError(null);\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n const msg = err instanceof Error ? err.message : \"Render failed\";\n setError(msg);\n setSvg(null);\n });\n return () => {\n cancelled = true;\n };\n }, [diagram.code, renderId]);\n\n return (\n <>\n <button\n type=\"button\"\n onClick={() => svg && setZoom(true)}\n aria-label=\"Zoom diagram\"\n className=\"group/dia relative shrink-0 overflow-hidden rounded-lg border border-border bg-card transition-colors hover:border-primary/40\"\n >\n {svg ? (\n <>\n <div\n className=\"h-24 w-40 [&_svg]:h-full [&_svg]:w-full\"\n // SVG is generated by mermaid (securityLevel: strict).\n dangerouslySetInnerHTML={{ __html: svg }}\n />\n <span className=\"absolute end-1 top-1 flex h-5 w-5 items-center justify-center rounded-full bg-foreground/70 text-background opacity-0 transition-opacity group-hover/dia:opacity-100\">\n <ZoomIcon className=\"h-3 w-3\" />\n </span>\n </>\n ) : mermaidMissing ? (\n <div className=\"grid h-24 w-40 place-items-center px-3 text-center text-[11px] leading-snug text-muted-foreground\">\n <span>\n Install <code className=\"rounded bg-muted px-1 font-mono\">mermaid</code>{\" \"}\n or pass{\" \"}\n <code className=\"rounded bg-muted px-1 font-mono\">renderDiagram</code>\n </span>\n </div>\n ) : error ? (\n <div className=\"grid h-24 w-40 place-items-center px-2 text-center text-[10px] leading-snug text-destructive\">\n <span>{error.slice(0, 80)}</span>\n </div>\n ) : (\n <div className=\"grid h-24 w-40 place-items-center text-[10px] text-muted-foreground\">\n <span>Rendering…</span>\n </div>\n )}\n </button>\n {zoom && svg && (\n <ImageLightbox\n src={svgToDataUri(svg)}\n alt=\"Mermaid diagram\"\n onClose={() => setZoom(false)}\n />\n )}\n </>\n );\n}","import { useEffect, useMemo, useRef } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { resolveSx, slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { SlashCommand } from \"../types\";\n\ninterface Props {\n options: SlashCommand[];\n selectedIndex: number;\n /** Renders skeleton rows while an async fetch is in flight + no items yet. */\n isLoading?: boolean;\n onSelect: (index: number) => void;\n onHover: (index: number) => void;\n}\n\nexport function SlashMenu({\n options,\n selectedIndex,\n isLoading = false,\n onSelect,\n onHover,\n}: Props) {\n const listRef = useRef<HTMLUListElement>(null);\n const { classNames, sx } = useComposerContext();\n\n useEffect(() => {\n const el = listRef.current?.querySelector<HTMLElement>(\n `[data-index=\"${selectedIndex}\"]`,\n );\n if (el) el.scrollIntoView({ block: \"nearest\" });\n }, [selectedIndex]);\n\n const grouped = options.reduce<Record<string, { item: SlashCommand; index: number }[]>>(\n (acc, item, index) => {\n const g = item.group ?? \"Commands\";\n if (!acc[g]) acc[g] = [];\n acc[g].push({ item, index });\n return acc;\n },\n {},\n );\n\n const menu = slotProps(\n \"slashMenu\",\n \"z-50 w-72 origin-top animate-slide-up overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-soft\",\n classNames,\n sx,\n );\n const itemStyle = useMemo(() => resolveSx(sx?.slashItem), [sx]);\n\n const showSkeleton = isLoading && options.length === 0;\n\n return (\n <div\n data-composer-popover=\"open\"\n role=\"listbox\"\n aria-label=\"Slash commands\"\n aria-busy={isLoading || undefined}\n {...menu}\n >\n <ul ref={listRef} className=\"max-h-72 overflow-y-auto scrollbar-thin py-1\">\n {showSkeleton && <SlashSkeleton rows={4} />}\n {Object.entries(grouped).map(([group, entries]) => (\n <li key={group}>\n <div className=\"px-3 pb-1 pt-2 text-[10px] font-medium uppercase tracking-wide text-muted-foreground\">\n {group}\n </div>\n <ul>\n {entries.map(({ item, index }) => (\n <li\n key={item.id}\n data-index={index}\n role=\"option\"\n aria-selected={selectedIndex === index}\n onMouseDown={(e) => {\n e.preventDefault();\n onSelect(index);\n }}\n onMouseEnter={() => onHover(index)}\n className={cn(\n \"flex cursor-pointer items-center gap-2.5 px-2.5 py-1.5 text-sm\",\n selectedIndex === index\n ? \"bg-accent text-accent-foreground\"\n : \"text-foreground\",\n classNames?.slashItem,\n )}\n style={itemStyle}\n >\n {item.icon && (\n <span className=\"flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-muted text-muted-foreground\">\n {item.icon}\n </span>\n )}\n <span className=\"flex min-w-0 flex-col leading-tight\">\n <span className=\"truncate font-medium\">{item.label}</span>\n {item.description && (\n <span className=\"truncate text-[11px] text-muted-foreground\">\n {item.description}\n </span>\n )}\n </span>\n {item.shortcut && (\n <span className=\"ms-auto rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground\">\n {item.shortcut}\n </span>\n )}\n </li>\n ))}\n </ul>\n </li>\n ))}\n </ul>\n </div>\n );\n}\n\n/**\n * Shimmer rows shown while an async slash-commands resolver is in flight\n * and we don't yet have any items to display. Mirrors the icon + label +\n * description layout of a real command row.\n */\nfunction SlashSkeleton({ rows = 4 }: { rows?: number }) {\n return (\n <li aria-hidden=\"true\" className=\"px-2.5 py-1.5\">\n <div className=\"px-0.5 pb-1.5 pt-0.5\">\n <span className=\"block h-2 w-16 animate-pulse rounded bg-muted/70\" />\n </div>\n <ul className=\"flex flex-col gap-1\">\n {Array.from({ length: rows }).map((_, i) => (\n <li\n key={i}\n className=\"flex items-center gap-2.5 rounded-md px-0 py-1.5\"\n >\n <span className=\"h-7 w-7 shrink-0 animate-pulse rounded-md bg-muted\" />\n <span className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n <span\n className=\"h-2.5 animate-pulse rounded bg-muted\"\n style={{ width: `${50 + ((i * 19) % 35)}%` }}\n />\n <span\n className=\"h-2 animate-pulse rounded bg-muted/70\"\n style={{ width: `${30 + ((i * 13) % 30)}%` }}\n />\n </span>\n </li>\n ))}\n </ul>\n <span className=\"sr-only\">Loading commands…</span>\n </li>\n );\n}","/**\n * SmartPopover — positions a typeahead menu relative to the trigger\n * character (`@`/`/`/`#`/…) that opened it.\n *\n * Two RTL/bidi pitfalls we have to navigate:\n *\n * 1. Chromium resolves `Range#getBoundingClientRect()` for ranges that\n * span more than one bidi run (the caret at a run boundary, or\n * Lexical's `[trigger, caret]` range) against the paragraph's\n * *logical* origin — which can be on the visually opposite side of\n * the line from where the trigger glyph is actually painted. Anchor\n * a menu to that rect and it lands on the far side of the screen.\n *\n * Workaround: walk back from the caret inside its host TextNode,\n * find the single trigger character, build a `Range` over *just\n * that one character*, and use that range's bbox. Single-character\n * ranges always sit wholly inside one bidi run, so their box is\n * the real painted glyph position in every mixed-bidi permutation.\n *\n * 2. Lexical's bidi handling lives at the *paragraph* level (it sets\n * `dir` on the paragraph element based on the first strong char\n * typed). So a `dir=\"rtl\"` composer can perfectly happily contain\n * an `dir=\"ltr\"` paragraph (`test @|`) — the trigger glyph is then\n * laid out left-aligned at the visual *left* of the editor card,\n * even though the surrounding chrome is RTL. If we keyed alignment\n * off the outer composer's `dir` we'd open the menu leftward of an\n * `@` that's already on the left — straight off-screen.\n *\n * Workaround: ask for the resolved CSS `direction` of the trigger\n * character's parent paragraph (the actual element it lives in),\n * not the editor wrapper. The menu opens into the reading flow of\n * the text the user is actually typing, regardless of the outer\n * `dir` setting. The `dir` prop is only used as an explicit\n * override hint for `dir=\"ltr\"` and `dir=\"rtl\"` when we can't\n * locate a paragraph (defensive fallback).\n *\n * Other notes:\n * - We render with `position: fixed` and viewport coordinates.\n * Lexical mounts its typeahead anchor under `<body>` and re-\n * positions it for its own overflow heuristic, so offset-parent-\n * relative positioning is unreliable.\n * - Vertical flip: when there isn't enough room below the trigger we\n * pin the menu's bottom edge just above the entire composer card.\n * - Recomputed on scroll, resize, selection change, anchor resize and\n * self-resize (the menu height changes as the filter narrows).\n */\nimport { useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n children: ReactNode;\n /** Gap between the menu and its anchor (caret or composer edge). */\n gap?: number;\n}\n\ninterface Placement {\n /** Final viewport-x for the menu's left edge. */\n left: number;\n /** Final viewport-y. Either `top` or `bottom` is set, never both. */\n top?: number;\n bottom?: number;\n /**\n * Resolved direction at the trigger character — used to set `dir`\n * on the popover wrapper so the menu's content (avatars, shortcuts,\n * descriptions) flips with the reading flow of the text the user\n * is actually typing.\n */\n rtl: boolean;\n}\n\nconst MARGIN = 8;\n\nfunction findComposerRoot(anchor: HTMLElement | null): HTMLElement | null {\n const active = document.activeElement;\n if (active instanceof HTMLElement) {\n const root = active.closest<HTMLElement>(\"[data-composer-root]\");\n if (root) return root;\n }\n if (anchor) {\n const anchorRect = anchor.getBoundingClientRect();\n const x = anchorRect.left + 1;\n const y = anchorRect.top + 1;\n const el = document.elementFromPoint(x, y);\n if (el instanceof HTMLElement) {\n const root = el.closest<HTMLElement>(\"[data-composer-root]\");\n if (root) return root;\n }\n }\n return document.querySelector<HTMLElement>(\"[data-composer-root]\");\n}\n\ninterface CaretRect {\n left: number;\n right: number;\n top: number;\n bottom: number;\n width: number;\n height: number;\n}\n\ninterface TriggerInfo {\n rect: CaretRect;\n /**\n * Resolved CSS direction of the *paragraph element* that visually\n * contains the trigger character. This is what we key the menu's\n * inline-start alignment off — it reflects the actual reading\n * direction of the text the user is typing, even when it differs\n * from the outer composer `dir`.\n */\n rtl: boolean;\n}\n\nfunction rectFromDom(rect: DOMRect): CaretRect {\n return {\n left: rect.left,\n right: rect.right,\n top: rect.top,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n };\n}\n\n// Word-class characters across the scripts the composer is most likely\n// to encounter. We treat anything in this set as \"not a trigger\". Latin\n// letters and digits, Hebrew, Arabic, Persian/Urdu, CJK, plus the\n// underscore and any whitespace.\nconst WORD_OR_SPACE = /[A-Za-z0-9_\\s\\u0590-\\u05FF\\u0600-\\u06FF\\u4E00-\\u9FFF]/;\n\n/**\n * Walk up to the closest block-level ancestor that has a `dir`/CSS\n * `direction` we can read. This is typically the Lexical paragraph\n * the trigger character lives in — Lexical sets `dir` on the\n * paragraph element based on the first strong character typed, which\n * is exactly what we want to follow.\n */\nfunction isBlockRtl(node: Node): boolean | null {\n let el: Element | null =\n node.nodeType === Node.ELEMENT_NODE\n ? (node as Element)\n : node.parentElement;\n while (el) {\n // Read the *resolved* direction. Lexical applies `dir` as an\n // attribute on its paragraph element which CSS resolves into\n // `direction`. We don't need to crawl `dir` attributes by hand.\n const display = getComputedStyle(el).display;\n if (display && display !== \"inline\" && display !== \"contents\") {\n return getComputedStyle(el).direction === \"rtl\";\n }\n el = el.parentElement;\n }\n return null;\n}\n\n/**\n * Walk back from the live caret inside its host text node, find the\n * single trigger character (`@`/`/`/`#`/`?`/etc.), and return the\n * bounding rect of *just that character* together with the resolved\n * direction of its containing paragraph.\n *\n * The single-character `Range` trick is what makes this bidi-safe:\n * spanning multiple offsets across a bidi-run boundary (which is what\n * Lexical's anchor range does) gives a bbox the bidi engine resolves\n * against the line's logical origin — often on the opposite visual\n * side from the painted glyph. A range over one character sits wholly\n * inside one bidi run and always reports the real painted position.\n */\nfunction readTriggerInfo(): TriggerInfo | null {\n if (typeof window === \"undefined\") return null;\n const sel = window.getSelection?.();\n if (!sel || sel.rangeCount === 0) return null;\n const range = sel.getRangeAt(0);\n const node = range.startContainer;\n if (node.nodeType !== Node.TEXT_NODE) return null;\n\n const text = (node as Text).data;\n const cursorOffset = range.startOffset;\n\n // Look back at most ~64 chars — the default typeahead match window\n // is 32, so this is more than enough headroom while still bounding\n // the search.\n let triggerOffset = -1;\n const lookbackStart = Math.max(0, cursorOffset - 64);\n for (let i = cursorOffset - 1; i >= lookbackStart; i--) {\n const c = text[i];\n if (WORD_OR_SPACE.test(c)) continue;\n triggerOffset = i;\n break;\n }\n if (triggerOffset < 0) return null;\n\n const triggerRange = document.createRange();\n try {\n triggerRange.setStart(node, triggerOffset);\n triggerRange.setEnd(node, triggerOffset + 1);\n } catch {\n return null;\n }\n const rect = triggerRange.getBoundingClientRect();\n if (rect.height === 0 && rect.width === 0) return null;\n\n return {\n rect: rectFromDom(rect),\n rtl: isBlockRtl(node) ?? false,\n };\n}\n\n/**\n * Last-resort positioning info when we can't pinpoint the trigger\n * character. Falls back to the live caret rect, then to the Lexical\n * anchor element's rect, and infers direction from the editor wrapper.\n */\nfunction readFallbackInfo(\n fallback: HTMLElement,\n dirHint: \"ltr\" | \"rtl\" | \"auto\" | undefined,\n): TriggerInfo {\n const sel = typeof window !== \"undefined\" ? window.getSelection?.() : null;\n let rect: CaretRect;\n if (sel && sel.rangeCount > 0) {\n const r = sel.getRangeAt(0).getBoundingClientRect();\n rect =\n r.height > 0 || r.width > 0\n ? rectFromDom(r)\n : rectFromDom(fallback.getBoundingClientRect());\n const blockRtl =\n sel.rangeCount > 0\n ? isBlockRtl(sel.getRangeAt(0).startContainer)\n : null;\n if (blockRtl !== null) return { rect, rtl: blockRtl };\n } else {\n rect = rectFromDom(fallback.getBoundingClientRect());\n }\n if (dirHint === \"rtl\") return { rect, rtl: true };\n if (dirHint === \"ltr\") return { rect, rtl: false };\n // Last fallback: the editor wrapper's resolved direction.\n const root =\n fallback.closest<HTMLElement>(\"[data-composer-root]\") ??\n document.querySelector<HTMLElement>(\"[data-composer-root]\");\n const editor = root?.querySelector<HTMLElement>(\".composer-editor\");\n const probe = editor ?? root ?? fallback;\n return { rect, rtl: getComputedStyle(probe).direction === \"rtl\" };\n}\n\nexport function SmartPopover({ children, gap = 6 }: Props) {\n const ref = useRef<HTMLDivElement>(null);\n const [placement, setPlacement] = useState<Placement | null>(null);\n // Lexical mounts the typeahead anchor under <body>, escaping the inline\n // CSS variables we set on `[data-composer-root]`. Re-apply them here so\n // the brand-colour tokens reach the menu's children (selected row bg,\n // mention avatar, etc.).\n const { tokenStyle, dir } = useComposerContext();\n\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n const anchor = el.parentElement;\n if (!anchor) return;\n\n const update = () => {\n // Find the trigger character's actual painted rect (single-char\n // range — bidi-safe) and the resolved direction of its host\n // paragraph. Fall back to the caret / Lexical anchor rect if we\n // can't locate the trigger (unusual editor state).\n const info = readTriggerInfo() ?? readFallbackInfo(anchor, dir);\n const triggerRect = info.rect;\n\n const menuHeight = el.offsetHeight;\n const menuWidth = el.offsetWidth;\n const viewportH = window.innerHeight;\n const viewportW = window.innerWidth;\n\n // Inline-start alignment, keyed off the *paragraph's* direction\n // (not the outer composer's). In LTR the menu's left edge meets\n // the trigger's left edge; in RTL its right edge meets the\n // trigger's right edge. The popup therefore opens into the line's\n // actual reading flow even when an LTR run lives inside an RTL\n // composer or vice versa.\n const baseLeft = info.rtl\n ? triggerRect.right - menuWidth\n : triggerRect.left;\n\n // Clamp to the viewport so the menu never escapes either edge.\n let left = baseLeft;\n if (left + menuWidth + MARGIN > viewportW) {\n left = viewportW - menuWidth - MARGIN;\n }\n if (left < MARGIN) left = MARGIN;\n\n // Vertical: prefer below, flip above (anchored to the composer's\n // top edge) when the menu would clip the viewport bottom.\n const spaceBelow = viewportH - triggerRect.bottom;\n const spaceAbove = triggerRect.top;\n const wantsAbove =\n spaceBelow < menuHeight + MARGIN && spaceAbove > spaceBelow;\n\n let next: Placement;\n if (wantsAbove) {\n const composerRoot = findComposerRoot(anchor);\n const topEdge = composerRoot\n ? composerRoot.getBoundingClientRect().top\n : triggerRect.top;\n next = {\n left,\n bottom: Math.max(MARGIN, viewportH - topEdge + gap),\n rtl: info.rtl,\n };\n } else {\n next = { left, top: triggerRect.bottom + gap, rtl: info.rtl };\n }\n\n setPlacement((prev) =>\n prev &&\n prev.left === next.left &&\n prev.top === next.top &&\n prev.bottom === next.bottom &&\n prev.rtl === next.rtl\n ? prev\n : next,\n );\n };\n\n update();\n const ro = new ResizeObserver(update);\n ro.observe(el);\n // Lexical re-positions its anchor element as the caret moves. We\n // don't read the anchor's rect anymore, but observing its size still\n // gives us a free reposition signal whenever the typeahead match\n // grows or shrinks — handy because `selectionchange` doesn't fire\n // for typing-only changes inside an already-collapsed selection.\n ro.observe(anchor);\n // Caret-driven repositioning. The selection's range moves under our\n // feet as the user types, arrows around, or clicks elsewhere; this\n // keeps the menu glued to that movement without leaning on Lexical's\n // own (sometimes-misplaced) anchor.\n document.addEventListener(\"selectionchange\", update);\n window.addEventListener(\"resize\", update);\n window.addEventListener(\"scroll\", update, true);\n return () => {\n ro.disconnect();\n document.removeEventListener(\"selectionchange\", update);\n window.removeEventListener(\"resize\", update);\n window.removeEventListener(\"scroll\", update, true);\n };\n }, [children, gap, dir]);\n\n const style: React.CSSProperties =\n placement === null\n ? {\n position: \"fixed\",\n left: 0,\n top: 0,\n visibility: \"hidden\",\n zIndex: 60,\n }\n : {\n position: \"fixed\",\n left: placement.left,\n top: placement.top,\n bottom: placement.bottom,\n zIndex: 60,\n };\n\n // Merge the consumer's token CSS vars first so positioning props (which\n // can be `undefined`) don't blow them away.\n const mergedStyle: React.CSSProperties = tokenStyle\n ? { ...tokenStyle, ...style }\n : style;\n\n return (\n <div\n ref={ref}\n data-composer-popover-placement={\n placement?.bottom !== undefined ? \"above-composer\" : \"below\"\n }\n // Match the popover's inline direction to the resolved direction\n // at the trigger character. Children (mention rows, slash items,\n // shortcuts) use logical flexbox + `ms-*`/`me-*` utilities so\n // setting `dir` here is enough to flip avatars to the start side,\n // shortcuts to the end side, and text alignment to follow the\n // language being typed.\n dir={placement?.rtl ? \"rtl\" : \"ltr\"}\n style={mergedStyle}\n >\n {children}\n </div>\n );\n}","/**\n * useOutsideClickDismiss — closes the active typeahead menu of `editor` when\n * the user clicks (or touches) outside the composer root and outside any\n * open popover. Disabled when `enabled` is false; safe to call\n * unconditionally because the listeners are only attached while enabled.\n *\n * \"Outside\" means: the event target is not a descendant of\n * `[data-composer-root]` and not a descendant of an element rendered by\n * `<SmartPopover />` (which carries `data-composer-popover-placement`).\n *\n * Closing is performed by dispatching `KEY_ESCAPE_COMMAND` on the editor —\n * the same path used by Lexical's typeahead plugin when the user presses\n * Escape, so dismissal feels native and triggers `onClose` callbacks.\n */\nimport { useEffect } from \"react\";\nimport { KEY_ESCAPE_COMMAND, type LexicalEditor } from \"lexical\";\n\nexport function useOutsideClickDismiss(\n editor: LexicalEditor,\n enabled: boolean,\n): void {\n useEffect(() => {\n if (!enabled) return;\n\n const dismiss = () => {\n const event = new KeyboardEvent(\"keydown\", { key: \"Escape\" });\n editor.dispatchCommand(KEY_ESCAPE_COMMAND, event);\n };\n\n const isOutside = (target: EventTarget | null): boolean => {\n if (!(target instanceof Node)) return false;\n const popover = document.querySelector(\n \"[data-composer-popover-placement]\",\n );\n if (!popover) return false; // No menu open — nothing to dismiss\n if (popover.contains(target)) return false;\n\n const el =\n target instanceof Element\n ? target\n : (target.parentElement as Element | null);\n if (!el) return true;\n if (el.closest(\"[data-composer-root]\")) return false;\n return true;\n };\n\n const onPointer = (e: MouseEvent | TouchEvent) => {\n const target =\n e instanceof TouchEvent ? e.touches[0]?.target ?? null : e.target;\n if (isOutside(target)) dismiss();\n };\n\n document.addEventListener(\"mousedown\", onPointer, true);\n document.addEventListener(\"touchstart\", onPointer, true);\n return () => {\n document.removeEventListener(\"mousedown\", onPointer, true);\n document.removeEventListener(\"touchstart\", onPointer, true);\n };\n }, [editor, enabled]);\n}","/**\n * SlashCommandPlugin — typeahead menu that opens when the user types `/` at\n * the start of a line (or after whitespace). Consumers feed commands via\n * `features.slashCommands`.\n *\n * Built on Lexical's `LexicalTypeaheadMenuPlugin` so we get IME-safe match\n * detection, keyboard navigation, and caret-anchored positioning for free.\n */\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n LexicalTypeaheadMenuPlugin,\n MenuOption,\n useBasicTypeaheadTriggerMatch,\n} from \"@lexical/react/LexicalTypeaheadMenuPlugin\";\nimport { createPortal } from \"react-dom\";\nimport { $getSelection, $isRangeSelection, type TextNode } from \"lexical\";\nimport type {\n SlashCommand,\n SlashCommandContext,\n SlashConfig,\n} from \"../types\";\nimport { SlashMenu } from \"../ui/SlashMenu\";\nimport { SmartPopover } from \"../ui/SmartPopover\";\nimport { useOutsideClickDismiss } from \"../hooks/useOutsideClickDismiss\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\nclass SlashOption extends MenuOption {\n command: SlashCommand;\n constructor(command: SlashCommand) {\n super(command.id);\n this.command = command;\n }\n}\n\ninterface Props {\n config: SlashConfig;\n onSubmit: () => void;\n}\n\nfunction isSyncItems(\n items: SlashConfig[\"items\"],\n): items is SlashCommand[] {\n return Array.isArray(items);\n}\n\nexport function SlashCommandPlugin({ config, onSubmit }: Props) {\n const [editor] = useLexicalComposerContext();\n const { closeMenusOnOutsideClick } = useComposerContext();\n const [query, setQuery] = useState<string>(\"\");\n const [asyncItems, setAsyncItems] = useState<SlashCommand[] | null>(null);\n const [isLoading, setIsLoading] = useState<boolean>(\n !isSyncItems(config.items),\n );\n\n useOutsideClickDismiss(editor, closeMenusOnOutsideClick);\n\n const triggerFn = useBasicTypeaheadTriggerMatch(\n config.trigger ?? \"/\",\n { minLength: 0, maxLength: 32, allowWhitespace: false },\n );\n\n // Resolve async items when query changes.\n useEffect(() => {\n if (isSyncItems(config.items)) {\n setIsLoading(false);\n return;\n }\n let cancelled = false;\n setIsLoading(true);\n Promise.resolve(config.items(query)).then((res) => {\n if (cancelled) return;\n setAsyncItems(res);\n setIsLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [query, config.items]);\n\n const allItems = useMemo<SlashCommand[]>(() => {\n return isSyncItems(config.items) ? config.items : asyncItems ?? [];\n }, [config.items, asyncItems]);\n\n const options = useMemo(() => {\n const q = query.trim().toLowerCase();\n const max = config.maxItems ?? 8;\n const filtered = q\n ? allItems.filter((it) => {\n const hay = `${it.label} ${it.description ?? \"\"} ${it.group ?? \"\"}`.toLowerCase();\n return hay.includes(q);\n })\n : allItems;\n return filtered.slice(0, max).map((c) => new SlashOption(c));\n }, [allItems, query, config.maxItems]);\n\n const onSelectOption = useCallback(\n (\n selectedOption: SlashOption,\n nodeToReplace: TextNode | null,\n closeMenu: () => void,\n matchingString: string,\n ) => {\n editor.update(() => {\n if (nodeToReplace) nodeToReplace.remove();\n });\n const ctx: SlashCommandContext = {\n insertText: (text) => {\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) sel.insertText(text);\n });\n },\n insertMarkdown: (md) => {\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) sel.insertText(md);\n });\n },\n cancel: () => closeMenu(),\n submit: () => onSubmit(),\n };\n selectedOption.command.onSelect?.(ctx);\n closeMenu();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n void matchingString;\n },\n [editor, onSubmit],\n );\n\n return (\n <LexicalTypeaheadMenuPlugin<SlashOption>\n onQueryChange={(s) => setQuery(s ?? \"\")}\n onSelectOption={onSelectOption}\n triggerFn={triggerFn}\n options={options}\n menuRenderFn={(anchorElementRef, { selectedIndex, selectOptionAndCleanUp, setHighlightedIndex }) => {\n if (!anchorElementRef.current) return null;\n // Keep the menu open while an async fetch is in flight even without\n // any items so the consumer's SlashMenu can render its skeleton.\n if (options.length === 0 && !isLoading) return null;\n return createPortal(\n <SmartPopover>\n <SlashMenu\n options={options.map((o) => o.command)}\n selectedIndex={selectedIndex ?? 0}\n isLoading={isLoading}\n onSelect={(index) => selectOptionAndCleanUp(options[index])}\n onHover={(index) => setHighlightedIndex(index)}\n />\n </SmartPopover>,\n anchorElementRef.current,\n );\n }}\n />\n );\n}","import { useState } from \"react\";\n\ninterface Props {\n src?: string;\n alt: string;\n size?: number;\n className?: string;\n}\n\n/** Small circular avatar used inside MentionMenu. Falls back to initials. */\nexport function Avatar({ src, alt, size = 28, className }: Props) {\n const [errored, setErrored] = useState(false);\n const showImage = src && !errored;\n const initial = (alt || \"?\").slice(0, 1).toUpperCase();\n return (\n <span\n className={\n \"inline-flex shrink-0 select-none items-center justify-center overflow-hidden rounded-full bg-primary/10 text-xs font-semibold text-primary\" +\n (className ? ` ${className}` : \"\")\n }\n style={{ width: size, height: size }}\n >\n {showImage ? (\n <img\n src={src}\n alt={alt}\n className=\"h-full w-full object-cover\"\n onError={() => setErrored(true)}\n />\n ) : (\n initial\n )}\n </span>\n );\n}","import { useEffect, useMemo, useRef } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { resolveSx, slotProps } from \"../internal/sx\";\nimport { Avatar } from \"../internal/Avatar\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { MentionItem } from \"../types\";\n\ninterface Props {\n options: MentionItem[];\n selectedIndex: number;\n /** Renders skeleton rows while an async fetch is in flight + no items yet. */\n isLoading?: boolean;\n onSelect: (index: number) => void;\n onHover: (index: number) => void;\n}\n\nexport function MentionMenu({\n options,\n selectedIndex,\n isLoading = false,\n onSelect,\n onHover,\n}: Props) {\n const listRef = useRef<HTMLUListElement>(null);\n const { classNames, sx } = useComposerContext();\n\n useEffect(() => {\n const el = listRef.current?.querySelector<HTMLElement>(\n `[data-index=\"${selectedIndex}\"]`,\n );\n if (el) el.scrollIntoView({ block: \"nearest\" });\n }, [selectedIndex]);\n\n const menu = slotProps(\n \"mentionMenu\",\n \"z-50 w-64 origin-top animate-slide-up overflow-hidden rounded-xl border border-border bg-popover text-popover-foreground shadow-soft\",\n classNames,\n sx,\n );\n const itemStyle = useMemo(() => resolveSx(sx?.mentionItem), [sx]);\n\n // Only show skeleton when we genuinely have nothing to display — once\n // we have stale items from a previous query we keep showing them while\n // the next fetch resolves to avoid flicker.\n const showSkeleton = isLoading && options.length === 0;\n\n return (\n <div\n data-composer-popover=\"open\"\n role=\"listbox\"\n aria-label=\"Mentions\"\n aria-busy={isLoading || undefined}\n {...menu}\n >\n <ul ref={listRef} className=\"max-h-72 overflow-y-auto scrollbar-thin py-1\">\n {showSkeleton ? (\n <MentionSkeleton rows={3} />\n ) : null}\n {options.map((item, index) => (\n <li\n key={item.id}\n data-index={index}\n role=\"option\"\n aria-selected={selectedIndex === index}\n onMouseDown={(e) => {\n e.preventDefault();\n onSelect(index);\n }}\n onMouseEnter={() => onHover(index)}\n className={cn(\n \"flex cursor-pointer items-center gap-2.5 px-2.5 py-1.5 text-sm\",\n selectedIndex === index\n ? \"bg-accent text-accent-foreground\"\n : \"text-foreground\",\n classNames?.mentionItem,\n )}\n style={itemStyle}\n >\n {item.avatarUrl ? (\n <Avatar src={item.avatarUrl} alt={item.label} />\n ) : item.icon ? (\n <span className=\"flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary\">\n {item.icon}\n </span>\n ) : (\n <span className=\"flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-semibold text-primary\">\n {item.label.slice(0, 1).toUpperCase()}\n </span>\n )}\n <span className=\"flex min-w-0 flex-col leading-tight\">\n <span className=\"truncate font-medium\">{item.label}</span>\n {item.description && (\n <span className=\"truncate text-[11px] text-muted-foreground\">\n {item.description}\n </span>\n )}\n </span>\n </li>\n ))}\n </ul>\n </div>\n );\n}\n\n/**\n * Three-line shimmer placeholder mirroring the avatar + label + description\n * layout of a real mention row. Pure CSS animation via the `animate-pulse`\n * utility — no JS keyframes, no layout thrash.\n */\nfunction MentionSkeleton({ rows = 3 }: { rows?: number }) {\n return (\n <li aria-hidden=\"true\" className=\"px-2.5 py-1.5\">\n <ul className=\"flex flex-col gap-1\">\n {Array.from({ length: rows }).map((_, i) => (\n <li\n key={i}\n className=\"flex items-center gap-2.5 rounded-md px-0 py-1.5\"\n >\n <span className=\"h-7 w-7 shrink-0 animate-pulse rounded-full bg-muted\" />\n <span className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n <span\n className=\"h-2.5 animate-pulse rounded bg-muted\"\n style={{ width: `${60 + ((i * 17) % 30)}%` }}\n />\n <span\n className=\"h-2 animate-pulse rounded bg-muted/70\"\n style={{ width: `${35 + ((i * 23) % 25)}%` }}\n />\n </span>\n </li>\n ))}\n </ul>\n <span className=\"sr-only\">Loading suggestions…</span>\n </li>\n );\n}","/**\n * MentionPlugin — typeahead that triggers on `@` and replaces the trigger\n * text with a `MentionNode` chip on select. The chip is atomic (single\n * backspace removes it) and rendered in the theme primary color.\n */\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n LexicalTypeaheadMenuPlugin,\n MenuOption,\n useBasicTypeaheadTriggerMatch,\n} from \"@lexical/react/LexicalTypeaheadMenuPlugin\";\nimport { createPortal } from \"react-dom\";\nimport {\n $createTextNode,\n $getSelection,\n $isRangeSelection,\n type TextNode,\n} from \"lexical\";\nimport type { MentionConfig, MentionItem } from \"../types\";\nimport { $createMentionNode } from \"../core/nodes/MentionNode\";\nimport { MentionMenu } from \"../ui/MentionMenu\";\nimport { SmartPopover } from \"../ui/SmartPopover\";\nimport { useOutsideClickDismiss } from \"../hooks/useOutsideClickDismiss\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\nclass MentionOption extends MenuOption {\n item: MentionItem;\n constructor(item: MentionItem) {\n super(item.id);\n this.item = item;\n }\n}\n\ninterface Props {\n config: MentionConfig;\n}\n\nfunction isSyncItems(\n items: MentionConfig[\"items\"],\n): items is MentionItem[] {\n return Array.isArray(items);\n}\n\nexport function MentionPlugin({ config }: Props) {\n const [editor] = useLexicalComposerContext();\n const { closeMenusOnOutsideClick } = useComposerContext();\n const [query, setQuery] = useState<string>(\"\");\n const [asyncItems, setAsyncItems] = useState<MentionItem[] | null>(null);\n // Initial state: async lists are \"loading\" until the first resolution.\n // Sync arrays are never loading.\n const [isLoading, setIsLoading] = useState<boolean>(\n !isSyncItems(config.items),\n );\n\n useOutsideClickDismiss(editor, closeMenusOnOutsideClick);\n\n const trigger = config.trigger ?? \"@\";\n\n const triggerFn = useBasicTypeaheadTriggerMatch(trigger, {\n minLength: 0,\n maxLength: 32,\n allowWhitespace: false,\n });\n\n useEffect(() => {\n if (isSyncItems(config.items)) {\n setIsLoading(false);\n return;\n }\n let cancelled = false;\n setIsLoading(true);\n Promise.resolve(config.items(query)).then((res) => {\n if (cancelled) return;\n setAsyncItems(res);\n setIsLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [query, config.items]);\n\n const allItems = useMemo<MentionItem[]>(() => {\n return isSyncItems(config.items) ? config.items : asyncItems ?? [];\n }, [config.items, asyncItems]);\n\n const options = useMemo(() => {\n const q = query.trim().toLowerCase();\n const max = config.maxItems ?? 8;\n const filtered = q\n ? allItems.filter((it) =>\n `${it.label} ${it.description ?? \"\"}`.toLowerCase().includes(q),\n )\n : allItems;\n return filtered.slice(0, max).map((c) => new MentionOption(c));\n }, [allItems, query, config.maxItems]);\n\n const onSelectOption = useCallback(\n (\n selectedOption: MentionOption,\n nodeToReplace: TextNode | null,\n closeMenu: () => void,\n ) => {\n editor.update(() => {\n // The chip is an inline ElementNode that contains a TextNode for\n // the label. Storing the label as a real child means the user can\n // backspace through it character-by-character — the ID on the\n // wrapping element stays attached to whatever text remains.\n const chip = $createMentionNode(selectedOption.item.id, trigger);\n chip.append($createTextNode(selectedOption.item.label));\n if (nodeToReplace) {\n nodeToReplace.replace(chip);\n } else {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) sel.insertNodes([chip]);\n }\n // Add a trailing space so the user can keep typing immediately\n // after the chip without their next char being captured inside.\n const space = $createTextNode(\" \");\n chip.insertAfter(space);\n space.select();\n });\n closeMenu();\n },\n [editor, trigger],\n );\n\n return (\n <LexicalTypeaheadMenuPlugin<MentionOption>\n onQueryChange={(s) => setQuery(s ?? \"\")}\n onSelectOption={onSelectOption}\n triggerFn={triggerFn}\n options={options}\n menuRenderFn={(anchorElementRef, { selectedIndex, selectOptionAndCleanUp, setHighlightedIndex }) => {\n if (!anchorElementRef.current) return null;\n // Keep the menu visible while an async fetch is in flight even if\n // we currently have no items — the MentionMenu renders a skeleton\n // in that case so the user gets immediate feedback.\n if (options.length === 0 && !isLoading) return null;\n return createPortal(\n <SmartPopover>\n <MentionMenu\n options={options.map((o) => o.item)}\n selectedIndex={selectedIndex ?? 0}\n isLoading={isLoading}\n onSelect={(index) => selectOptionAndCleanUp(options[index])}\n onHover={(index) => setHighlightedIndex(index)}\n />\n </SmartPopover>,\n anchorElementRef.current,\n );\n }}\n />\n );\n}","/**\n * GhostedAutoCompletePlugin — inline \"ghost text\" autocomplete suggested\n * from a fixed list.\n *\n * UX contract:\n * - Watches the editor's plain-text content. When that text is a prefix\n * of one of the consumer's `suggestions`, the remainder is rendered\n * just after the caret in a muted style — same trick GitHub Copilot,\n * iOS QuickType and shell autocompletion use to nudge users toward\n * the completion without committing to it.\n * - **Tab** accepts the suggestion (the remainder is inserted into the\n * editor and the ghost clears). Escape, a non-matching keystroke, or\n * moving the caret away dismisses it without committing.\n * - The ghost only appears when the caret sits at the END of the\n * document — typing in the middle would render a confusing\n * \"wraparound\" suggestion.\n * - When several suggestions share a prefix, the FIRST match wins. The\n * consumer is expected to order the list by priority.\n *\n * Why ghost-text instead of a dropdown menu? It's the lowest-friction\n * autocomplete UI for a curated, sentence-shaped suggestion list (chat\n * prompts, templated commands, FAQ answers). There's nothing to click\n * through and nothing to dismiss — just keep typing or hit Tab.\n *\n * Why an overlay div instead of decorating the editor itself? Lexical's\n * source-of-truth model means the editor's text content is what we'd\n * eventually serialize on submit; inserting \"soft\" ghost characters into\n * the document would either need a custom non-selectable node (heavy)\n * or risk being captured by serializers / cursor traversal. A sibling\n * overlay positioned over the editor's padding box gives us pixel-perfect\n * alignment with zero risk of leaking into the payload.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $getRoot,\n $getSelection,\n $isRangeSelection,\n COMMAND_PRIORITY_HIGH,\n COMMAND_PRIORITY_LOW,\n KEY_ESCAPE_COMMAND,\n KEY_TAB_COMMAND,\n} from \"lexical\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { GhostedAutoCompleteConfig } from \"../types\";\n\ninterface Props {\n /**\n * Normalized feature value — either a plain `string[]` shorthand or the\n * full {@link GhostedAutoCompleteConfig} object. Plugin handles both.\n */\n config: string[] | GhostedAutoCompleteConfig;\n}\n\ninterface ResolvedConfig {\n suggestions: string[];\n caseSensitive: boolean;\n minLength: number;\n}\n\nfunction resolveConfig(config: Props[\"config\"]): ResolvedConfig {\n if (Array.isArray(config)) {\n return { suggestions: config, caseSensitive: false, minLength: 1 };\n }\n return {\n suggestions: config.suggestions,\n caseSensitive: !!config.caseSensitive,\n // `1` (not `0`) so the ghost never appears on an empty editor — the\n // placeholder handles that, and showing a ghost there would feel like\n // the composer is auto-typing on its own.\n minLength: Math.max(1, config.minLength ?? 1),\n };\n}\n\n/**\n * Find the first suggestion that starts with `typed` (per `caseSensitive`)\n * and return its UN-typed remainder. Strict-prefix only — if `typed`\n * equals a suggestion exactly, there's nothing to suggest and we return\n * `null`.\n */\nfunction findGhost(\n typed: string,\n suggestions: ReadonlyArray<string>,\n caseSensitive: boolean,\n): string | null {\n if (typed.length === 0) return null;\n const needle = caseSensitive ? typed : typed.toLowerCase();\n for (const candidate of suggestions) {\n if (candidate.length <= typed.length) continue;\n const hay = caseSensitive ? candidate : candidate.toLowerCase();\n if (hay.startsWith(needle)) {\n // Preserve the candidate's casing in the remainder — `typed` already\n // sits in the editor, so we only return what's NOT yet typed.\n return candidate.slice(typed.length);\n }\n }\n return null;\n}\n\n/**\n * Whether the current selection is collapsed at the very end of the\n * document. Run inside a `getEditorState().read(...)` scope.\n *\n * Used as a gating signal: showing a ghost while the caret is parked\n * mid-paragraph would visually claim the user is about to overwrite\n * trailing text, which they aren't.\n */\nfunction $isCaretAtDocumentEnd(): boolean {\n const sel = $getSelection();\n if (!$isRangeSelection(sel) || !sel.isCollapsed()) return false;\n const root = $getRoot();\n const last = root.getLastDescendant();\n if (last === null) {\n // Empty document — `selectEnd` lands on the root element with\n // offset 0; treat that as \"at end\".\n return sel.focus.key === root.getKey();\n }\n if (sel.focus.key !== last.getKey()) return false;\n const size =\n \"getTextContentSize\" in last && typeof last.getTextContentSize === \"function\"\n ? (last as { getTextContentSize: () => number }).getTextContentSize()\n : last.getTextContent().length;\n return sel.focus.offset === size;\n}\n\ninterface GhostState {\n typed: string;\n remainder: string;\n}\n\nexport function GhostedAutoCompletePlugin({ config }: Props) {\n const [editor] = useLexicalComposerContext();\n const { multiline } = useComposerContext();\n const resolved = useMemo(() => resolveConfig(config), [config]);\n\n const [ghost, setGhost] = useState<GhostState | null>(null);\n // Ref mirror so key-command handlers (which need a stable identity\n // across renders) can read the latest ghost without re-subscribing on\n // every state change — re-subscribing churns the command priority\n // stack and racy popovers.\n const ghostRef = useRef<GhostState | null>(null);\n ghostRef.current = ghost;\n\n // Recompute the ghost whenever the editor state changes. We read the\n // plain text (chips collapse to their labels) and the selection, then\n // probe the suggestion list for a strict-prefix match.\n useEffect(() => {\n const compute = () => {\n editor.getEditorState().read(() => {\n if (!$isCaretAtDocumentEnd()) {\n setGhost(null);\n return;\n }\n const typed = $getRoot().getTextContent();\n if (typed.length < resolved.minLength) {\n setGhost(null);\n return;\n }\n const remainder = findGhost(\n typed,\n resolved.suggestions,\n resolved.caseSensitive,\n );\n if (!remainder) {\n setGhost(null);\n return;\n }\n // Only nudge React when something actually changed — avoids\n // overlay flicker for every cursor-move tick Lexical emits.\n setGhost((prev) =>\n prev && prev.typed === typed && prev.remainder === remainder\n ? prev\n : { typed, remainder },\n );\n });\n };\n compute();\n return editor.registerUpdateListener(compute);\n }, [editor, resolved]);\n\n // Tab accepts the ghost. We hijack KEY_TAB_COMMAND at HIGH priority so\n // the keystroke is fully consumed before the browser ever sees it —\n // otherwise focus would jump to the next focusable in the toolbar\n // (Send button, etc.) and the user would lose their composing context.\n // When no ghost is showing we let the key fall through so Tab keeps its\n // normal \"leave the editor\" semantics.\n const acceptGhost = useCallback(() => {\n const current = ghostRef.current;\n if (!current) return false;\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) {\n sel.insertText(current.remainder);\n }\n });\n setGhost(null);\n return true;\n }, [editor]);\n\n useEffect(() => {\n return editor.registerCommand(\n KEY_TAB_COMMAND,\n (event) => {\n if (!ghostRef.current) return false;\n event?.preventDefault();\n return acceptGhost();\n },\n COMMAND_PRIORITY_HIGH,\n );\n }, [editor, acceptGhost]);\n\n // Escape clears the ghost (matches the \"dismiss the suggestion\"\n // gesture in shells / IDEs) but only when there's something to clear —\n // otherwise we'd swallow Escape from anything else that wants it.\n useEffect(() => {\n return editor.registerCommand(\n KEY_ESCAPE_COMMAND,\n () => {\n if (!ghostRef.current) return false;\n setGhost(null);\n return true;\n },\n COMMAND_PRIORITY_LOW,\n );\n }, [editor]);\n\n if (!ghost) return null;\n return (\n <GhostOverlay\n typed={ghost.typed}\n remainder={ghost.remainder}\n multiline={multiline}\n />\n );\n}\n\ninterface OverlayProps {\n typed: string;\n remainder: string;\n multiline: boolean;\n}\n\n/**\n * Renders the ghost text inside the editor's padding box via a portal,\n * so the suggestion floats exactly where the next typed character would\n * land — no measuring, no math.\n *\n * Implementation: we lay an absolutely-positioned, pointer-events:none\n * div over the editor's parent (`.composer-editor-block`) and fill it\n * with `[invisible-typed][muted-remainder]`. The invisible span occupies\n * the same horizontal space as the user's text, so the visible remainder\n * starts precisely at the caret.\n *\n * Limitations (acceptable for the curated-suggestion use case):\n * - Doesn't follow per-paragraph block styling (headings render at\n * larger sizes than this overlay). Ghost autocomplete is most useful\n * in plain prompts / search bars where this isn't a factor.\n * - In multiline mode, if the editor scrolls past its viewport the\n * overlay stays anchored to the box (it doesn't scroll with the\n * content). For multi-paragraph drafts the suggestion will simply\n * be clipped — same as a placeholder hint would be.\n */\nfunction GhostOverlay({ typed, remainder, multiline }: OverlayProps) {\n const [editor] = useLexicalComposerContext();\n const [container, setContainer] = useState<HTMLElement | null>(null);\n\n useEffect(() => {\n const root = editor.getRootElement();\n // The contenteditable is wrapped by the EditorShell's\n // `.composer-editor-block` div, which is `position: relative` —\n // perfect anchor for our absolute overlay.\n const block = root?.closest<HTMLElement>(\".composer-editor-block\") ?? null;\n setContainer(block);\n }, [editor]);\n\n if (!container) return null;\n\n // Mirror the editor's padding / typography so the overlay text lines\n // up exactly with the contenteditable's own text origin. We keep the\n // two padding strings in lock-step with `EditorShell.tsx`'s\n // `editorClass` — when one changes, change both.\n const paddingClass = multiline\n ? \"composer-ghost-overlay--multiline px-5 py-3.5\"\n : \"composer-ghost-overlay--inline px-2 leading-9\";\n\n return createPortal(\n <div\n aria-hidden\n data-composer-ghost=\"\"\n className={`composer-ghost-overlay pointer-events-none absolute inset-0 select-none ${paddingClass}`}\n >\n <span className=\"composer-ghost-overlay-typed\" aria-hidden>\n {typed}\n </span>\n <span className=\"composer-ghost-suggestion\">{remainder}</span>\n </div>,\n container,\n );\n}","import { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { Attachment } from \"../types\";\n\ninterface Props {\n attachment: Attachment;\n onRemove: () => void;\n onZoom?: () => void;\n}\n\nfunction formatBytes(bytes: number) {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function AttachmentChip({ attachment, onRemove, onZoom }: Props) {\n const { icons, classNames, sx } = useComposerContext();\n const {\n file: FileIcon,\n audio: AudioIcon,\n close: CloseIcon,\n zoom: ZoomIcon,\n spinner: SpinnerIcon,\n warning: WarningIcon,\n } = icons;\n const isImage = attachment.kind === \"image\" && !!attachment.previewUrl;\n const isUploading = attachment.status === \"uploading\";\n const isFailed = attachment.status === \"failed\";\n // Surface the upload error on hover. Falls back to the file name when\n // nothing's wrong, so the chip is still scannable.\n const titleText = isFailed && attachment.error\n ? `${attachment.name} — ${attachment.error}`\n : attachment.name;\n\n if (isImage) {\n const chip = slotProps(\n \"attachmentChip\",\n \"group/chip relative h-16 w-16 overflow-hidden rounded-xl border border-border bg-muted\",\n classNames,\n sx,\n );\n return (\n <div {...chip} title={titleText}>\n <img\n src={attachment.previewUrl}\n alt={attachment.name}\n className=\"h-full w-full object-cover\"\n />\n {/* Uploading overlay — sits above the image, eats hover events\n below so the user doesn't accidentally trigger zoom mid-upload. */}\n {isUploading && (\n <div\n aria-label=\"Uploading\"\n className=\"absolute inset-0 grid place-items-center bg-foreground/50\"\n >\n <SpinnerIcon className=\"h-5 w-5 animate-spin text-background\" />\n </div>\n )}\n {/* Failed overlay — destructive tint + warning glyph + persistent\n (no hover gating) so the failure stays obvious. */}\n {isFailed && (\n <div\n aria-label=\"Upload failed\"\n className=\"absolute inset-0 grid place-items-center bg-destructive/55\"\n >\n <WarningIcon className=\"h-5 w-5 text-destructive-foreground\" />\n </div>\n )}\n {!isUploading && !isFailed && (\n <button\n type=\"button\"\n onClick={onZoom}\n aria-label={`Zoom ${attachment.name}`}\n className=\"absolute inset-0 flex items-center justify-center bg-foreground/40 opacity-0 transition-opacity group-hover/chip:opacity-100\"\n >\n <ZoomIcon className=\"h-4 w-4 text-background\" />\n </button>\n )}\n <button\n type=\"button\"\n onClick={onRemove}\n aria-label={`Remove ${attachment.name}`}\n // Remove stays available during upload/failure too — clicking it\n // is the user's \"cancel\" / \"retry from scratch\" gesture.\n className={\n \"absolute end-1 top-1 z-10 flex h-5 w-5 items-center justify-center rounded-full bg-foreground text-background transition-opacity \" +\n (isUploading || isFailed\n ? \"opacity-100\"\n : \"opacity-0 group-hover/chip:opacity-100\")\n }\n >\n <CloseIcon className=\"h-3 w-3\" strokeWidth={2.5} />\n </button>\n </div>\n );\n }\n\n const KindIcon = attachment.kind === \"audio\" ? AudioIcon : FileIcon;\n const chip = slotProps(\n \"attachmentChip\",\n \"group/chip flex items-center gap-2 rounded-xl border bg-card ps-2 pe-1 py-1.5 \" +\n (isFailed ? \"border-destructive/60\" : \"border-border\"),\n classNames,\n sx,\n );\n\n return (\n <div {...chip} title={titleText}>\n <span\n className={\n \"flex h-8 w-8 items-center justify-center rounded-md \" +\n (isFailed\n ? \"bg-destructive/15 text-destructive\"\n : \"bg-muted text-muted-foreground\")\n }\n >\n {isUploading ? (\n <SpinnerIcon className=\"h-4 w-4 animate-spin\" />\n ) : isFailed ? (\n <WarningIcon className=\"h-4 w-4\" />\n ) : (\n <KindIcon className=\"h-4 w-4\" />\n )}\n </span>\n <span className=\"flex flex-col\">\n <span className=\"max-w-[160px] truncate text-xs font-medium leading-tight\">\n {attachment.name}\n </span>\n <span\n className={\n \"text-[10px] \" +\n (isFailed ? \"text-destructive\" : \"text-muted-foreground\")\n }\n >\n {isUploading\n ? \"Uploading…\"\n : isFailed\n ? attachment.error || \"Upload failed\"\n : formatBytes(attachment.size)}\n </span>\n </span>\n <button\n type=\"button\"\n onClick={onRemove}\n aria-label={`Remove ${attachment.name}`}\n className=\"flex h-6 w-6 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\"\n >\n <CloseIcon className=\"h-3.5 w-3.5\" />\n </button>\n </div>\n );\n}","import { useState } from \"react\";\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { AttachmentChip } from \"../ui/AttachmentChip\";\nimport { ImageLightbox } from \"../ui/ImageLightbox\";\nimport type { Attachment } from \"../types\";\n\n/** Renders attachment chips above the editor input. */\nexport function AttachmentTray() {\n const { attachments, removeAttachment, classNames, sx } = useComposerContext();\n const [zoom, setZoom] = useState<Attachment | null>(null);\n\n if (attachments.length === 0) return null;\n\n const tray = slotProps(\n \"attachmentTray\",\n \"flex flex-wrap gap-2 px-4 pt-3\",\n classNames,\n sx,\n );\n\n return (\n <>\n <div {...tray}>\n {attachments.map((att) => (\n <AttachmentChip\n key={att.id}\n attachment={att}\n onRemove={() => removeAttachment(att.id)}\n onZoom={att.kind === \"image\" ? () => setZoom(att) : undefined}\n />\n ))}\n </div>\n {zoom && zoom.previewUrl && (\n <ImageLightbox\n src={zoom.previewUrl}\n alt={zoom.name}\n onClose={() => setZoom(null)}\n />\n )}\n </>\n );\n}","import {\n cloneElement,\n isValidElement,\n useId,\n useRef,\n useState,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport { cn } from \"./cn\";\n\ntype Side = \"top\" | \"right\" | \"bottom\" | \"left\";\n\nexport interface TooltipProps {\n children: ReactNode;\n content: ReactNode;\n side?: Side;\n delay?: number;\n className?: string;\n}\n\n// `left`/`right` are interpreted as inline-start / inline-end so the tooltip\n// flips automatically under `dir=\"rtl\"`. The horizontal centring offsets stay\n// physical (`left-1/2 -translate-x-1/2`) — the result is direction-agnostic\n// because the centre line is the same in either writing mode.\nconst sideClasses: Record<Side, string> = {\n top: \"bottom-full left-1/2 mb-2 -translate-x-1/2\",\n bottom: \"top-full left-1/2 mt-2 -translate-x-1/2\",\n left: \"end-full top-1/2 me-2 -translate-y-1/2\",\n right: \"start-full top-1/2 ms-2 -translate-y-1/2\",\n};\n\n/** Minimal tooltip inlined into the composer package. */\nexport function Tooltip({\n children,\n content,\n side = \"top\",\n delay = 150,\n className,\n}: TooltipProps) {\n const [open, setOpen] = useState(false);\n const id = useId();\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const show = () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n timerRef.current = setTimeout(() => setOpen(true), delay);\n };\n const hide = () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n setOpen(false);\n };\n\n const trigger = isValidElement(children) ? (\n cloneElement(children as ReactElement<Record<string, unknown>>, {\n \"aria-describedby\": id,\n onMouseEnter: show,\n onMouseLeave: hide,\n onFocus: show,\n onBlur: hide,\n })\n ) : (\n <span\n tabIndex={0}\n aria-describedby={id}\n onMouseEnter={show}\n onMouseLeave={hide}\n onFocus={show}\n onBlur={hide}\n >\n {children}\n </span>\n );\n\n return (\n <span className=\"relative inline-flex\">\n {trigger}\n {open && (\n <span\n id={id}\n role=\"tooltip\"\n className={cn(\n \"absolute z-50 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-xs text-background shadow-md\",\n sideClasses[side],\n className,\n )}\n >\n {content}\n </span>\n )}\n </span>\n );\n}","/**\n * VoicePlugin — toolbar mic button that captures voice input. Prefers the\n * Web Speech API for live transcription (Chromium, Safari); falls back to\n * MediaRecorder which posts the recorded clip as an audio attachment.\n *\n * - All capture APIs are accessed lazily — no permissions are requested\n * until the user actually presses the button.\n * - While recording: button shows a pulsing red dot and live elapsed time.\n */\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { Tooltip } from \"../internal/Tooltip\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $getSelection,\n $isRangeSelection,\n} from \"lexical\";\n\ntype RecState = \"idle\" | \"starting\" | \"recording\" | \"transcribing\";\n\ninterface SpeechRecognitionLike extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n onresult: ((ev: SpeechRecognitionEventLike) => void) | null;\n onerror: ((ev: Event) => void) | null;\n onend: (() => void) | null;\n}\n\ninterface SpeechRecognitionEventLike {\n results: ArrayLike<\n ArrayLike<{ transcript: string }> & { isFinal: boolean }\n >;\n resultIndex: number;\n}\n\nfunction getSpeechRecognition(): (new () => SpeechRecognitionLike) | null {\n const w = window as unknown as {\n SpeechRecognition?: new () => SpeechRecognitionLike;\n webkitSpeechRecognition?: new () => SpeechRecognitionLike;\n };\n return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;\n}\n\nfunction formatSeconds(s: number): string {\n const mm = Math.floor(s / 60);\n const ss = s % 60;\n return `${mm}:${ss.toString().padStart(2, \"0\")}`;\n}\n\nexport function VoiceButton() {\n const [editor] = useLexicalComposerContext();\n const { addFiles, icons, classNames } = useComposerContext();\n const { voice: VoiceIcon, voiceRecording: VoiceRecordingIcon } = icons;\n const [state, setState] = useState<RecState>(\"idle\");\n const [elapsed, setElapsed] = useState(0);\n const recognitionRef = useRef<SpeechRecognitionLike | null>(null);\n const mediaRef = useRef<MediaRecorder | null>(null);\n const chunksRef = useRef<Blob[]>([]);\n const startedAtRef = useRef<number>(0);\n const tickerRef = useRef<number | null>(null);\n\n useEffect(() => {\n return () => {\n try {\n recognitionRef.current?.stop();\n } catch {\n // ignore\n }\n try {\n mediaRef.current?.stop();\n } catch {\n // ignore\n }\n if (tickerRef.current) window.clearInterval(tickerRef.current);\n };\n }, []);\n\n const startTicker = () => {\n startedAtRef.current = Date.now();\n setElapsed(0);\n if (tickerRef.current) window.clearInterval(tickerRef.current);\n tickerRef.current = window.setInterval(() => {\n setElapsed(Math.floor((Date.now() - startedAtRef.current) / 1000));\n }, 500);\n };\n\n const stopTicker = () => {\n if (tickerRef.current) {\n window.clearInterval(tickerRef.current);\n tickerRef.current = null;\n }\n };\n\n const insertText = useCallback(\n (text: string) => {\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) {\n sel.insertText(text);\n }\n });\n },\n [editor],\n );\n\n const startSpeech = (Recognition: new () => SpeechRecognitionLike) => {\n const rec = new Recognition();\n rec.continuous = false;\n rec.interimResults = true;\n rec.lang = navigator.language || \"en-US\";\n\n let finalBuffer = \"\";\n rec.onresult = (event) => {\n let interim = \"\";\n for (let i = event.resultIndex; i < event.results.length; i++) {\n const result = event.results[i];\n const transcript = result[0].transcript;\n if ((result as unknown as { isFinal: boolean }).isFinal) {\n finalBuffer += transcript;\n } else {\n interim += transcript;\n }\n }\n if (finalBuffer.trim().length > 0) {\n insertText(finalBuffer + (interim ? \"\" : \" \"));\n finalBuffer = \"\";\n }\n };\n rec.onerror = () => {\n stopTicker();\n setState(\"idle\");\n };\n rec.onend = () => {\n stopTicker();\n setState(\"idle\");\n };\n recognitionRef.current = rec;\n setState(\"recording\");\n startTicker();\n rec.start();\n };\n\n const startMediaRecorder = async () => {\n try {\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n const rec = new MediaRecorder(stream);\n chunksRef.current = [];\n rec.ondataavailable = (e) => {\n if (e.data.size > 0) chunksRef.current.push(e.data);\n };\n rec.onstop = () => {\n const blob = new Blob(chunksRef.current, { type: \"audio/webm\" });\n const file = new File([blob], `voice-${Date.now()}.webm`, {\n type: \"audio/webm\",\n });\n addFiles([file]);\n stream.getTracks().forEach((t) => t.stop());\n stopTicker();\n setState(\"idle\");\n };\n mediaRef.current = rec;\n rec.start();\n setState(\"recording\");\n startTicker();\n } catch {\n stopTicker();\n setState(\"idle\");\n }\n };\n\n const start = async () => {\n setState(\"starting\");\n const Recognition = getSpeechRecognition();\n if (Recognition) {\n try {\n startSpeech(Recognition);\n return;\n } catch {\n // fall through to MediaRecorder fallback\n }\n }\n await startMediaRecorder();\n };\n\n const stop = () => {\n setState(\"transcribing\");\n try {\n recognitionRef.current?.stop();\n } catch {\n // ignore\n }\n try {\n mediaRef.current?.stop();\n } catch {\n // ignore\n }\n };\n\n const isRecording = state === \"recording\" || state === \"starting\";\n\n return (\n <div className=\"flex items-center gap-1.5\">\n <Tooltip\n content={isRecording ? \"Stop recording\" : \"Voice input\"}\n side=\"top\"\n >\n <button\n type=\"button\"\n aria-label={isRecording ? \"Stop voice recording\" : \"Start voice input\"}\n aria-pressed={isRecording}\n onClick={() => (isRecording ? stop() : void start())}\n className={cn(\n \"flex h-8 w-8 items-center justify-center rounded-full transition-colors\",\n isRecording\n ? \"bg-destructive/10 text-destructive ring-1 ring-destructive/40\"\n : \"text-muted-foreground hover:bg-accent hover:text-foreground\",\n classNames?.toolbarButton,\n )}\n >\n {state === \"transcribing\" ? (\n <VoiceRecordingIcon className=\"h-4 w-4 animate-spin\" />\n ) : (\n <VoiceIcon className={cn(\"h-4 w-4\", isRecording && \"animate-pulse\")} />\n )}\n </button>\n </Tooltip>\n {isRecording && (\n <span className=\"flex items-center gap-1 rounded-full bg-destructive/10 px-2 py-0.5 text-[11px] font-mono font-medium tabular-nums text-destructive\">\n <span className=\"h-1.5 w-1.5 animate-pulse rounded-full bg-destructive\" />\n {formatSeconds(elapsed)}\n </span>\n )}\n </div>\n );\n}","/**\n * AttachmentTypePicker — the paperclip-as-popover variant of the toolbar's\n * attachment button. Used when the consumer supplies a non-empty\n * `attachments.types` list; otherwise the toolbar renders the plain\n * single-click paperclip instead.\n *\n * Interaction model:\n * - Click paperclip → opens a small dropdown menu listing the types.\n * - Click a type → closes the menu and opens the OS file picker\n * scoped to that type's `accept` value.\n * - Outside click / Escape / second paperclip click → closes the menu.\n * - Arrow keys + Enter / Space navigate and pick (a11y friendly).\n *\n * Positioning: the popover is `position: absolute` anchored to the\n * paperclip's wrapper. The toolbar lives at the bottom of the composer\n * card, so we open *upward* (`bottom-full`). Logical alignment (`start-0`)\n * keeps it on the toolbar side in both LTR and RTL.\n */\nimport { useCallback, useEffect, useId, useRef, useState } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { IconComponent } from \"../internal/icons\";\nimport type { AttachmentTypeOption } from \"../types\";\n\ninterface Props {\n types: AttachmentTypeOption[];\n /** Forwarded to the hidden `<input type=file>`. */\n addFiles: (files: File[]) => void;\n /** Resolved className for the trigger button, from the slot system. */\n triggerClassName: string;\n /** Resolved inline style for the trigger button, from the slot system. */\n triggerStyle?: React.CSSProperties;\n /** Icon component the toolbar uses for the paperclip. */\n TriggerIcon: IconComponent;\n}\n\nexport function AttachmentTypePicker({\n types,\n addFiles,\n triggerClassName,\n triggerStyle,\n TriggerIcon,\n}: Props) {\n const { closeMenusOnOutsideClick } = useComposerContext();\n const [open, setOpen] = useState(false);\n const [activeIndex, setActiveIndex] = useState(0);\n\n const triggerRef = useRef<HTMLButtonElement | null>(null);\n const popoverRef = useRef<HTMLDivElement | null>(null);\n const fileInputRef = useRef<HTMLInputElement | null>(null);\n const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);\n\n const menuId = useId();\n\n const close = useCallback(() => setOpen(false), []);\n\n const triggerPicker = useCallback(\n (type: AttachmentTypeOption) => {\n const input = fileInputRef.current;\n if (!input) return;\n // Imperatively set accept so we don't have to round-trip through a\n // React re-render before clicking — keeps the dialog snappy.\n input.accept = type.accept;\n input.click();\n },\n [],\n );\n\n const pick = useCallback(\n (index: number) => {\n const type = types[index];\n if (!type) return;\n close();\n triggerRef.current?.focus();\n triggerPicker(type);\n },\n [types, close, triggerPicker],\n );\n\n // Outside click — honours the same global pref as the typeahead menus.\n useEffect(() => {\n if (!open || !closeMenusOnOutsideClick) return;\n const onPointerDown = (event: PointerEvent) => {\n const target = event.target as Node | null;\n if (!target) return;\n if (popoverRef.current?.contains(target)) return;\n if (triggerRef.current?.contains(target)) return;\n close();\n };\n document.addEventListener(\"pointerdown\", onPointerDown, true);\n return () =>\n document.removeEventListener(\"pointerdown\", onPointerDown, true);\n }, [open, closeMenusOnOutsideClick, close]);\n\n // Escape closes; arrow keys move the active row. We rebind on every open\n // so the listener captures the up-to-date `activeIndex` via the state\n // setter (not via a stale closure).\n useEffect(() => {\n if (!open) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === \"Escape\") {\n event.preventDefault();\n close();\n triggerRef.current?.focus();\n return;\n }\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n setActiveIndex((i) => (i + 1) % types.length);\n return;\n }\n if (event.key === \"ArrowUp\") {\n event.preventDefault();\n setActiveIndex((i) => (i - 1 + types.length) % types.length);\n return;\n }\n if (event.key === \"Home\") {\n event.preventDefault();\n setActiveIndex(0);\n return;\n }\n if (event.key === \"End\") {\n event.preventDefault();\n setActiveIndex(types.length - 1);\n return;\n }\n if (event.key === \"Enter\" || event.key === \" \") {\n // Only intercept if focus is inside the popover — otherwise the\n // user is typing in the editor and Enter must keep its normal\n // submit semantics.\n if (popoverRef.current?.contains(document.activeElement)) {\n event.preventDefault();\n pick(activeIndex);\n }\n }\n };\n document.addEventListener(\"keydown\", onKeyDown);\n return () => document.removeEventListener(\"keydown\", onKeyDown);\n }, [open, types.length, activeIndex, pick, close]);\n\n // Move keyboard focus onto the active row when the menu opens or the\n // active row changes via arrows. Mouse hover updates activeIndex without\n // stealing focus (we only call focus() when open transitions or on a key\n // event, not on hover).\n useEffect(() => {\n if (!open) return;\n itemRefs.current[activeIndex]?.focus();\n }, [open, activeIndex]);\n\n // When opening, reset to the first row. When closing, drop any picked\n // file off the input so the same file can be selected twice in a row.\n useEffect(() => {\n if (open) setActiveIndex(0);\n }, [open]);\n\n return (\n <div className=\"relative\">\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n hidden\n onChange={(e) => {\n const files = e.target.files;\n if (files && files.length > 0) addFiles(Array.from(files));\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n }}\n />\n <button\n ref={triggerRef}\n type=\"button\"\n aria-label=\"Attach file\"\n aria-haspopup=\"menu\"\n aria-expanded={open}\n aria-controls={open ? menuId : undefined}\n onClick={() => setOpen((o) => !o)}\n className={triggerClassName}\n style={triggerStyle}\n >\n <TriggerIcon className=\"h-4 w-4\" />\n </button>\n\n {open && (\n <div\n ref={popoverRef}\n id={menuId}\n role=\"menu\"\n aria-label=\"Attachment types\"\n data-composer-popover=\"open\"\n className={cn(\n \"composer-popover-in absolute bottom-full start-0 z-30 mb-2 min-w-[200px] overflow-hidden\",\n \"rounded-xl border border-border bg-popover p-1 text-popover-foreground\",\n \"shadow-soft\",\n )}\n >\n {types.map((type, index) => {\n const active = index === activeIndex;\n return (\n <button\n key={type.id}\n ref={(el) => {\n itemRefs.current[index] = el;\n }}\n role=\"menuitem\"\n type=\"button\"\n tabIndex={active ? 0 : -1}\n onMouseEnter={() => setActiveIndex(index)}\n onClick={() => pick(index)}\n className={cn(\n \"flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-start text-sm transition-colors\",\n active\n ? \"bg-accent text-accent-foreground\"\n : \"text-foreground hover:bg-accent/60\",\n )}\n >\n {type.icon ? (\n <span className=\"flex h-5 w-5 shrink-0 items-center justify-center text-muted-foreground\">\n {type.icon}\n </span>\n ) : null}\n <span className=\"min-w-0 flex-1 truncate font-medium\">\n {type.label}\n </span>\n {type.description ? (\n <span className=\"shrink-0 font-mono text-[11px] text-muted-foreground\">\n {type.description}\n </span>\n ) : null}\n </button>\n );\n })}\n </div>\n )}\n </div>\n );\n}","import { useRef, type ReactNode } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { slotProps } from \"../internal/sx\";\nimport { Tooltip } from \"../internal/Tooltip\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { VoiceButton } from \"../plugins/VoicePlugin\";\nimport { AttachmentTypePicker } from \"./AttachmentTypePicker\";\n\ninterface Props {\n extras?: ReactNode;\n}\n\nconst TOOLBAR_BTN_BASE =\n \"flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-accent hover:text-foreground\";\n\nexport function Toolbar({ extras }: Props) {\n const {\n features,\n attachmentsConfig,\n addFiles,\n webEnabled,\n toggleWeb,\n icons,\n classNames,\n sx,\n } = useComposerContext();\n const { attach: AttachIcon, image: ImageIcon, web: WebIcon } = icons;\n const fileInputRef = useRef<HTMLInputElement>(null);\n const imageInputRef = useRef<HTMLInputElement>(null);\n\n const attachmentsEnabled = !!features.attachments;\n // Per-picker toggles. `file` defaults to true (one-click paperclip);\n // `image` defaults to false (opt-in mobile camera-roll shortcut). Pass\n // `{ file: false }` to hide the paperclip, `{ image: true }` to add the\n // dedicated image picker.\n const showFileBtn = attachmentsEnabled && attachmentsConfig.file !== false;\n const showImageBtn = attachmentsEnabled && attachmentsConfig.image !== false;\n // When `types` is supplied, the paperclip flips into a popover trigger\n // that lets the user pre-pick the format before the OS dialog opens.\n const hasTypePicker =\n showFileBtn &&\n Array.isArray(attachmentsConfig.types) &&\n attachmentsConfig.types.length > 0;\n\n const toolbar = slotProps(\"toolbar\", \"flex items-center gap-1\", classNames, sx);\n const toolbarBtn = slotProps(\"toolbarButton\", TOOLBAR_BTN_BASE, classNames, sx);\n\n return (\n <div {...toolbar}>\n {showFileBtn && !hasTypePicker && (\n <>\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n accept={attachmentsConfig.accept}\n hidden\n onChange={(e) => {\n const files = e.target.files;\n if (files) addFiles(Array.from(files));\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n }}\n />\n <Tooltip content=\"Attach file\" side=\"top\">\n <button\n type=\"button\"\n aria-label=\"Attach file\"\n onClick={() => fileInputRef.current?.click()}\n {...toolbarBtn}\n >\n <AttachIcon className=\"h-4 w-4\" />\n </button>\n </Tooltip>\n </>\n )}\n {hasTypePicker && attachmentsConfig.types && (\n <AttachmentTypePicker\n types={attachmentsConfig.types}\n addFiles={addFiles}\n triggerClassName={toolbarBtn.className ?? \"\"}\n triggerStyle={toolbarBtn.style}\n TriggerIcon={AttachIcon}\n />\n )}\n {showImageBtn && (\n <>\n <input\n ref={imageInputRef}\n type=\"file\"\n multiple\n accept=\"image/*\"\n hidden\n onChange={(e) => {\n const files = e.target.files;\n if (files) addFiles(Array.from(files));\n if (imageInputRef.current) imageInputRef.current.value = \"\";\n }}\n />\n <Tooltip content=\"Add image\" side=\"top\">\n <button\n type=\"button\"\n aria-label=\"Add image\"\n onClick={() => imageInputRef.current?.click()}\n {...toolbarBtn}\n >\n <ImageIcon className=\"h-4 w-4\" />\n </button>\n </Tooltip>\n </>\n )}\n {features.voice && <VoiceButton />}\n {features.web && (\n <button\n type=\"button\"\n onClick={toggleWeb}\n aria-pressed={webEnabled}\n className={cn(\n \"ms-0.5 inline-flex h-8 items-center gap-1.5 rounded-full px-2.5 text-xs font-medium transition-colors\",\n webEnabled\n ? \"bg-primary/10 text-primary\"\n : \"text-muted-foreground hover:bg-accent hover:text-foreground\",\n classNames?.toolbarButton,\n )}\n >\n <WebIcon className=\"h-3.5 w-3.5\" />\n Web\n </button>\n )}\n {extras}\n </div>\n );\n}","/**\n * SendButton — the affordance for \"submit\" and \"stop streaming\".\n *\n * Customization model (loosest → tightest control):\n *\n * 1. `icons.send` / `icons.stop` → swap just the SVG inside the\n * default chrome.\n * 2. `classNames.sendButton` / → append classes to the default\n * `classNames.stopButton` <button> element.\n * 3. `sx.sendButton` / `sx.stopButton` → token-driven inline styles on\n * the default <button>.\n * 4. `slots.sendButton` / → replace the entire element with\n * `slots.stopButton` the consumer's own component.\n * See `ComposerSlots` in types.ts.\n *\n * When a slot is provided, the resolved `className` / `style` from layers\n * 2 and 3 are still passed in — consumers can spread them for \"your DOM,\n * our theme\" or ignore them for a from-scratch design.\n */\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n canSend: boolean;\n isStreaming: boolean;\n onSend: () => void;\n onStop?: () => void;\n}\n\nexport function SendButton({ canSend, isStreaming, onSend, onStop }: Props) {\n const { icons, classNames, sx, slots } = useComposerContext();\n const { send: SendIcon, stop: StopIcon } = icons;\n\n if (isStreaming) {\n const stop = slotProps(\n \"stopButton\",\n \"inline-flex h-9 w-9 items-center justify-center rounded-full bg-foreground text-background transition-transform hover:scale-105\",\n classNames,\n sx,\n );\n // Custom stop slot — bypass our default chrome entirely. We still\n // forward `onStop` (no-op safe via `?? noop` so the slot signature\n // never has to deal with `undefined`) and the resolved class/style so\n // the consumer can opt in to our theme tokens if they want.\n if (slots.stopButton) {\n const Slot = slots.stopButton;\n return (\n <Slot\n onStop={onStop ?? noop}\n className={stop.className}\n style={stop.style}\n />\n );\n }\n return (\n <button type=\"button\" onClick={onStop} aria-label=\"Stop generating\" {...stop}>\n <StopIcon className=\"h-3.5 w-3.5 fill-current\" />\n </button>\n );\n }\n const send = slotProps(\n \"sendButton\",\n [\n \"inline-flex h-9 w-9 items-center justify-center rounded-full transition-all\",\n canSend\n ? \"bg-foreground text-background shadow-sm hover:scale-105\"\n : \"bg-muted text-muted-foreground/60\",\n ],\n classNames,\n sx,\n );\n // Custom send slot — same contract as the stop slot above. We pass\n // `canSend` rather than `disabled` so the consumer can use it for both\n // the DOM `disabled` attribute AND any other UI affordance (label\n // change, opacity, tooltip, etc.).\n if (slots.sendButton) {\n const Slot = slots.sendButton;\n return (\n <Slot\n canSend={canSend}\n onSend={onSend}\n className={send.className}\n style={send.style}\n />\n );\n }\n return (\n <button\n type=\"button\"\n onClick={onSend}\n disabled={!canSend}\n aria-label=\"Send message\"\n {...send}\n >\n <SendIcon className=\"h-4 w-4\" strokeWidth={2.5} />\n </button>\n );\n}\n\n// Safe fallback so the slot signature doesn't have to make `onStop`\n// optional. `onStop` on `<Composer />` is optional — if the consumer\n// doesn't pass one, a click is a no-op (same as the default button).\nfunction noop() {}","import { useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n hint: boolean | ReactNode;\n}\n\nfunction Key({ children }: { children: ReactNode }) {\n return (\n <kbd className=\"rounded border border-border bg-card px-1 py-0.5 font-mono text-[10px]\">\n {children}\n </kbd>\n );\n}\n\n/** Render a shortcut spec like `\"mod+/\"` as a `<kbd>` chip the user can\n * recognise: `⌘/Ctrl + /`. Returns `null` if the spec doesn't have a\n * printable key, so the caller can skip the chip entirely. */\nfunction formatShortcut(spec: string): ReactNode {\n const parts = spec\n .split(\"+\")\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean);\n if (parts.length === 0) return null;\n const labels: string[] = [];\n for (const p of parts) {\n switch (p) {\n case \"mod\":\n labels.push(\"⌘/Ctrl\");\n break;\n case \"cmd\":\n case \"command\":\n case \"meta\":\n case \"win\":\n case \"super\":\n labels.push(\"⌘\");\n break;\n case \"ctrl\":\n case \"control\":\n labels.push(\"Ctrl\");\n break;\n case \"alt\":\n case \"option\":\n labels.push(\"Alt\");\n break;\n case \"shift\":\n labels.push(\"Shift\");\n break;\n default:\n labels.push(p.length === 1 ? p.toUpperCase() : p);\n }\n }\n return labels.join(\" + \");\n}\n\nexport function HintBar({ hint }: Props) {\n const {\n multiline,\n submitOnEnter,\n smartNewline,\n focusShortcut,\n classNames,\n sx,\n } = useComposerContext();\n\n // The default hint reflects whichever Enter behavior the composer is\n // actually wired up for, so a smart-newline composer doesn't lie to\n // the user about how to send. Consumers can still pass a custom node\n // via the `hint` prop to override entirely.\n const defaultShortcuts = useMemo(() => {\n if (!multiline) {\n if (!submitOnEnter) return null;\n return (\n <>\n Press <Key>Enter</Key> to send.\n </>\n );\n }\n if (smartNewline && submitOnEnter) {\n return (\n <>\n Press <Key>Enter</Key> to send a single line,{\" \"}\n <Key>⌘/Ctrl + Enter</Key> to send once you've started a new line.\n </>\n );\n }\n if (!submitOnEnter) {\n return (\n <>\n Press <Key>⌘/Ctrl + Enter</Key> to send, <Key>Enter</Key> for newline.\n </>\n );\n }\n return (\n <>\n Press <Key>Enter</Key> to send, <Key>Shift + Enter</Key> for newline.\n </>\n );\n }, [multiline, submitOnEnter, smartNewline]);\n\n const focusHint = useMemo(() => {\n if (!focusShortcut) return null;\n const label = formatShortcut(focusShortcut);\n if (!label) return null;\n return (\n <>\n {\" \"}\n <Key>{label}</Key> to jump back here.\n </>\n );\n }, [focusShortcut]);\n\n if (!hint) return null;\n const hintProps = slotProps(\n \"hint\",\n \"text-center text-[11px] text-muted-foreground\",\n classNames,\n sx,\n );\n return (\n <p {...hintProps}>\n {hint === true ? (\n <>\n AI can make mistakes — verify important info.\n {defaultShortcuts ? (\n <span className=\"hidden sm:inline\"> {defaultShortcuts}</span>\n ) : null}\n {focusHint ? (\n <span className=\"hidden md:inline\">{focusHint}</span>\n ) : null}\n </>\n ) : (\n hint\n )}\n </p>\n );\n}","/**\n * QuickPrompts — a chip row of \"starter\" prompts rendered above the composer.\n *\n * Each chip click pipes through the provider's `runPrompt` channel; the\n * subscriber (registered by `ComposerInner`, which owns the editor state and\n * the submit function) then either:\n * - inserts the prompt into the editor (`behavior: \"initValue\"`) so the\n * user can edit it before sending, or\n * - inserts AND immediately submits (`behavior: \"sendValue\"`, default).\n *\n * Visible subset selection is stable per mount: with `randomize: true`\n * (default) the picked items are shuffled once via Fisher-Yates and then\n * frozen for the lifetime of the component, so the chips don't reshuffle on\n * every parent re-render.\n */\nimport { useMemo } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { ComposerPromptsConfig } from \"../types\";\n\nconst DEFAULT_MAX = 3;\nconst HARD_CAP = 5;\n\ninterface Props {\n prompts: ComposerPromptsConfig;\n}\n\nfunction pickDisplay(\n items: string[],\n maxToShow: number | undefined,\n randomize: boolean | undefined,\n): string[] {\n const cleaned = items.filter((s) => typeof s === \"string\" && s.length > 0);\n if (cleaned.length === 0) return [];\n const max = Math.min(Math.max(1, maxToShow ?? DEFAULT_MAX), HARD_CAP);\n if (cleaned.length <= max) return cleaned;\n if (randomize === false) return cleaned.slice(0, max);\n // Fisher-Yates — uses Math.random; fine for UI selection (not security).\n const arr = [...cleaned];\n for (let i = arr.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [arr[i], arr[j]] = [arr[j], arr[i]];\n }\n return arr.slice(0, max);\n}\n\nexport function QuickPrompts({ prompts }: Props) {\n const { runPrompt, icons } = useComposerContext();\n const { sparkle: SparkleIcon } = icons;\n\n // Stable per mount. We DO want to re-pick if the consumer hands us a\n // brand-new items array (e.g. after fetching a fresh batch from the\n // server), so the array reference participates in the dep list.\n const display = useMemo(\n () => pickDisplay(prompts.items, prompts.maxToShow, prompts.randomize),\n [prompts.items, prompts.maxToShow, prompts.randomize],\n );\n\n if (display.length === 0) return null;\n\n const behavior = prompts.behavior ?? \"sendValue\";\n\n const handleClick = (prompt: string) => {\n prompts.onSelect?.(prompt);\n runPrompt(prompt, behavior);\n };\n\n return (\n <div\n role=\"group\"\n aria-label=\"Quick prompts\"\n className=\"flex flex-wrap items-center gap-2 px-1 pb-1\"\n >\n {display.map((p) => (\n <button\n key={p}\n type=\"button\"\n onClick={() => handleClick(p)}\n title={p}\n className={cn(\n \"group inline-flex max-w-full items-center gap-1.5 rounded-full\",\n \"border border-border bg-card/60 px-3 py-1.5 text-xs\",\n \"text-muted-foreground backdrop-blur transition-all\",\n \"hover:-translate-y-px hover:border-primary/40 hover:bg-card\",\n \"hover:text-foreground hover:shadow-sm\",\n \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40\",\n )}\n >\n <SparkleIcon className=\"h-3 w-3 shrink-0 text-primary opacity-70 group-hover:opacity-100\" />\n <span className=\"truncate\" style={{ maxWidth: \"32ch\" }}>\n {p}\n </span>\n </button>\n ))}\n </div>\n );\n}","import { useEffect, type Ref } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { $createParagraphNode, $getRoot } from \"lexical\";\nimport type { ComposerHandle } from \"../types\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport {\n $insertTextWithParagraphBreaks,\n $seedInitialValue,\n} from \"../internal/insertText\";\n\nexport function useComposerHandle(\n ref: Ref<ComposerHandle> | undefined,\n onSubmit: () => void,\n) {\n const [editor] = useLexicalComposerContext();\n const { addFiles } = useComposerContext();\n\n useEffect(() => {\n if (!ref) return;\n const handle: ComposerHandle = {\n focus: () => editor.focus(),\n clear: () => {\n editor.update(() => {\n const root = $getRoot();\n root.clear();\n root.append($createParagraphNode());\n });\n },\n insert: (text) => {\n editor.update(() => {\n // Empty editor → seed from scratch so every line becomes its own\n // paragraph. Non-empty editor → insert at the current selection\n // (or end, if selection is detached) with `\\n` → paragraph\n // breaks, so multi-line blobs like a ```mermaid fence keep their\n // structure and the markdown detectors can see them.\n const root = $getRoot();\n const isEmpty =\n root.getChildrenSize() === 0 ||\n (root.getChildrenSize() === 1 &&\n root.getFirstChild()?.getTextContent() === \"\");\n if (isEmpty) {\n $seedInitialValue(text);\n } else {\n $insertTextWithParagraphBreaks(text);\n }\n });\n },\n submit: () => onSubmit(),\n addAttachments: (files) => addFiles(files),\n };\n if (typeof ref === \"function\") {\n ref(handle);\n return () => ref(null);\n }\n (ref as { current: ComposerHandle | null }).current = handle;\n return () => {\n (ref as { current: ComposerHandle | null }).current = null;\n };\n }, [editor, ref, onSubmit, addFiles]);\n}","/**\n * Tiny keyboard-shortcut parser used by `<Composer focusShortcut>` (and a\n * good fit for any future global shortcut the library wants to expose).\n *\n * Why bespoke instead of pulling in a library:\n * - We need ONE thing: parse a string like `\"mod+/\"` once, then test\n * `KeyboardEvent`s against it on every `keydown`. ~30 lines.\n * - Zero deps + zero bundle cost > matching the exact ergonomics of\n * `mousetrap` / `hotkeys-js`.\n *\n * Grammar (case-insensitive):\n * shortcut := segment (\"+\" segment)*\n * segment := modifier | key\n * modifier := \"mod\" | \"cmd\" | \"meta\" | \"ctrl\" | \"control\"\n * | \"alt\" | \"option\" | \"shift\"\n * key := any non-modifier token (single char, \"Enter\", \"Escape\",\n * \"ArrowUp\", \"/\", \"?\", …)\n *\n * `mod` resolves to ⌘ on macOS and Ctrl elsewhere — the \"do what the\n * platform expects\" modifier. `cmd` / `meta` / `ctrl` are explicit and\n * never aliased.\n *\n * Modifier matching is strict: a parsed `\"mod+/\"` only fires when the\n * platform mod IS down AND every other modifier (Shift, Alt, the\n * non-platform one) is NOT — so `Cmd+Shift+/` won't accidentally trigger\n * a `Cmd+/` shortcut.\n */\n\nconst MODIFIERS = new Set([\n \"mod\",\n \"cmd\",\n \"command\",\n \"meta\",\n \"win\",\n \"super\",\n \"ctrl\",\n \"control\",\n \"alt\",\n \"option\",\n \"shift\",\n]);\n\nexport interface ParsedShortcut {\n /** Required modifier flags after platform resolution. */\n mod: boolean; // mod === Cmd on mac, Ctrl elsewhere\n altMod: boolean; // the other one — Ctrl on mac, Cmd on Windows/Linux (only if explicitly named)\n shift: boolean;\n alt: boolean;\n /** Lower-cased key to match. Special keys keep their `KeyboardEvent.key` casing-folded. */\n key: string;\n}\n\nfunction isMac(): boolean {\n if (typeof navigator === \"undefined\") return false;\n // `userAgentData.platform` is the modern path; userAgent is the fallback.\n // We accept either \"macOS\" / \"Mac\" / \"iPhone\" / \"iPad\" so the shortcut\n // works on iPadOS too (where Cmd is still the natural mod).\n const platform =\n (navigator as Navigator & {\n userAgentData?: { platform?: string };\n }).userAgentData?.platform ?? navigator.platform ?? navigator.userAgent;\n return /mac|iphone|ipad|ipod/i.test(platform);\n}\n\n/**\n * Parse a shortcut string into a `ParsedShortcut`, or `null` if the input\n * is empty / invalid (so the caller can simply skip registering it).\n */\nexport function parseShortcut(spec: string): ParsedShortcut | null {\n const segments = spec\n .split(\"+\")\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean);\n if (segments.length === 0) return null;\n\n const mac = isMac();\n let mod = false;\n let altMod = false;\n let shift = false;\n let alt = false;\n let key: string | null = null;\n\n for (const seg of segments) {\n if (MODIFIERS.has(seg)) {\n switch (seg) {\n case \"mod\":\n mod = true;\n break;\n case \"cmd\":\n case \"command\":\n case \"meta\":\n case \"win\":\n case \"super\":\n if (mac) mod = true;\n else altMod = true;\n break;\n case \"ctrl\":\n case \"control\":\n if (mac) altMod = true;\n else mod = true;\n break;\n case \"alt\":\n case \"option\":\n alt = true;\n break;\n case \"shift\":\n shift = true;\n break;\n }\n } else {\n // Last non-modifier wins — keeps `\"mod+/\"` and `\"/+mod\"` equivalent\n // even though only the former is the documented form.\n key = seg;\n }\n }\n\n if (!key) return null;\n return { mod, altMod, shift, alt, key };\n}\n\n/** Test a parsed shortcut against a `KeyboardEvent`. */\nexport function matchesShortcut(\n parsed: ParsedShortcut,\n event: KeyboardEvent,\n): boolean {\n const mac = isMac();\n const platformMod = mac ? event.metaKey : event.ctrlKey;\n const otherMod = mac ? event.ctrlKey : event.metaKey;\n\n if (parsed.mod !== platformMod) return false;\n if (parsed.altMod !== otherMod) return false;\n if (parsed.shift !== event.shiftKey) return false;\n if (parsed.alt !== event.altKey) return false;\n\n // Normalize the event key. Single-char keys are compared case-insensitively\n // (so `\"mod+K\"` and `\"mod+k\"` both match Shift-less ⌘K). Named keys\n // (Enter, Escape, ArrowUp, …) use their canonical lower-cased name.\n const eventKey = event.key.length === 1 ? event.key.toLowerCase() : event.key.toLowerCase();\n return eventKey === parsed.key;\n}","/**\n * `<Composer />` — the public chatbox component shipped by `composeai`.\n *\n * Design goals:\n * - Internally stateful (no `value`/`onChange` round-trip with the parent).\n * - Plugin-driven: every feature (markdown, attachments, slash, mentions,\n * mermaid, voice, web, ...) is an opt-in plugin behind `features`.\n * - Zero coupling to the host application; safe to publish to npm.\n * - The host only listens via `onSend(payload)` and optionally holds a\n * `ComposerHandle` ref for imperative control.\n *\n * Demos live in `src/showcase/pages/ComposerPage.tsx` and in the example\n * chat app under `src/app/` — neither belongs to the published library.\n */\nimport { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { LexicalComposer } from \"@lexical/react/LexicalComposer\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport type { InitialConfigType } from \"@lexical/react/LexicalComposer\";\nimport type { Klass, LexicalNode } from \"lexical\";\nimport {\n $createParagraphNode,\n $getRoot,\n ParagraphNode,\n} from \"lexical\";\nimport { $seedInitialValue } from \"./internal/insertText\";\nimport { cn } from \"./internal/cn\";\nimport { deriveColorTokens } from \"./internal/color\";\nimport { slotProps, tokensToStyle } from \"./internal/sx\";\nimport { ComposerProvider, useComposerContext } from \"./core/ComposerProvider\";\nimport { EditorShell } from \"./core/EditorShell\";\nimport { composerTheme } from \"./core/theme\";\nimport { MentionNode } from \"./core/nodes/MentionNode\";\nimport { MarkdownTokenNode } from \"./core/nodes/MarkdownTokenNode\";\nimport { BlockParagraphNode } from \"./core/nodes/BlockParagraphNode\";\nimport { LinkTextNode } from \"./core/nodes/LinkTextNode\";\nimport { collectPlainAndMentions, toMarkdown } from \"./core/serializer\";\nimport { KeyboardPlugin } from \"./plugins/KeyboardPlugin\";\nimport { AutoFocusPlugin } from \"./plugins/AutoFocusPlugin\";\nimport { PasteDropPlugin } from \"./plugins/PasteDropPlugin\";\nimport { MarkdownPlugin } from \"./plugins/MarkdownPlugin\";\nimport { MermaidPlugin } from \"./plugins/MermaidPlugin\";\nimport { SlashCommandPlugin } from \"./plugins/SlashCommandPlugin\";\nimport { MentionPlugin } from \"./plugins/MentionPlugin\";\nimport { GhostedAutoCompletePlugin } from \"./plugins/GhostedAutoCompletePlugin\";\nimport { AttachmentTray } from \"./plugins/AttachmentTray\";\nimport { Toolbar } from \"./ui/Toolbar\";\nimport { SendButton } from \"./ui/SendButton\";\nimport { HintBar } from \"./ui/HintBar\";\nimport { QuickPrompts } from \"./ui/QuickPrompts\";\nimport { useComposerHandle } from \"./hooks/useComposerHandle\";\nimport { parseShortcut, matchesShortcut } from \"./internal/shortcut\";\nimport { focusEditor } from \"./internal/focusEditor\";\nimport type { ComposerHandle, ComposerProps, ComposerSubmitPayload } from \"./types\";\n\n/**\n * ComposeAI — a Lexical-powered, plugin-driven rich input designed for\n * chat / AI assistant interfaces. Internally stateful: parents only listen via\n * `onSend` and (optionally) hold an imperative `ref`.\n */\nexport const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer(\n props,\n ref,\n) {\n const {\n placeholder = \"Send a message…\",\n onSend,\n onStop,\n isStreaming,\n autoFocus,\n refocusOnSubmit = true,\n focusShortcut = \"mod+/\",\n initialValue,\n className,\n classNames,\n sx,\n style,\n tokens,\n color,\n hint = true,\n features,\n toolbarExtras,\n closeMenusOnOutsideClick = true,\n mode = \"markdown\",\n multiline = true,\n submitOnEnter = true,\n smartNewline = true,\n icons,\n slots,\n renderDiagram,\n prompts,\n attachmentOptions,\n dir,\n } = props;\n\n // `color` is a brand-colour shorthand: derive primary/accent/ring from\n // a single value, then layer the consumer's explicit `tokens` on top so\n // they always win.\n const tokenStyle = useMemo(() => {\n const derived = color ? deriveColorTokens(color) : null;\n if (!derived && !tokens) return undefined;\n return tokensToStyle({ ...derived, ...tokens });\n }, [color, tokens]);\n const root = slotProps(\"root\", \"space-y-2\", classNames, sx);\n const rootStyle = useMemo(\n () => ({ ...tokenStyle, ...root.style, ...style }),\n [tokenStyle, root.style, style],\n );\n\n return (\n <ComposerProvider\n features={features}\n isStreaming={isStreaming}\n closeMenusOnOutsideClick={closeMenusOnOutsideClick}\n attachmentOptions={attachmentOptions}\n mode={mode}\n multiline={multiline}\n submitOnEnter={submitOnEnter}\n smartNewline={smartNewline}\n focusShortcut={focusShortcut}\n icons={icons}\n slots={slots}\n renderDiagram={renderDiagram}\n dir={dir}\n classNames={classNames}\n sx={sx}\n tokenStyle={tokenStyle}\n >\n <div\n dir={dir}\n className={cn(root.className, className)}\n style={Object.keys(rootStyle).length ? rootStyle : undefined}\n >\n {prompts && prompts.items.length > 0 ? (\n <QuickPrompts prompts={prompts} />\n ) : null}\n <ComposerCard\n placeholder={placeholder}\n initialValue={initialValue}\n handleRef={ref}\n onSend={onSend}\n onStop={onStop}\n autoFocus={autoFocus}\n refocusOnSubmit={refocusOnSubmit}\n focusShortcut={focusShortcut}\n isStreaming={!!isStreaming}\n toolbarExtras={toolbarExtras}\n mode={mode}\n multiline={multiline}\n />\n <HintBar hint={hint} />\n </div>\n </ComposerProvider>\n );\n});\n\ninterface CardProps {\n placeholder: string;\n initialValue?: string;\n handleRef: React.ForwardedRef<ComposerHandle>;\n onSend?: ComposerProps[\"onSend\"];\n onStop?: ComposerProps[\"onStop\"];\n autoFocus?: boolean;\n refocusOnSubmit: boolean;\n focusShortcut: ComposerProps[\"focusShortcut\"];\n isStreaming: boolean;\n toolbarExtras: ComposerProps[\"toolbarExtras\"];\n mode: NonNullable<ComposerProps[\"mode\"]>;\n /** `false` switches the card to the single-line / inline layout. */\n multiline: boolean;\n}\n\n// Slack-style: every visible block is a styled paragraph. In `live` markdown\n// mode the paragraph also remembers a hidden block marker (e.g. `\"# \"`) via\n// `BlockParagraphNode` — registered as a node-replacement so any\n// `$createParagraphNode()` (called by Lexical's internals and our own code)\n// mints our subclass instead.\nconst BLOCK_PARAGRAPH_REPLACEMENT = {\n replace: ParagraphNode,\n with: () => new BlockParagraphNode(),\n withKlass: BlockParagraphNode,\n};\nconst RICH_NODES: InitialConfigType[\"nodes\"] = [\n MentionNode,\n MarkdownTokenNode,\n BlockParagraphNode,\n LinkTextNode,\n BLOCK_PARAGRAPH_REPLACEMENT,\n];\n// Plain-text mode only needs paragraphs (built-in) and mentions — the rest is\n// intentionally absent so pasted rich content collapses to plain text.\nconst PLAIN_NODES: Array<Klass<LexicalNode>> = [MentionNode];\n\nfunction ComposerCard({\n placeholder,\n initialValue,\n handleRef,\n onSend,\n onStop,\n autoFocus,\n refocusOnSubmit,\n focusShortcut,\n isStreaming,\n toolbarExtras,\n mode,\n multiline,\n}: CardProps) {\n const { webEnabled, isDraggingFiles, classNames, sx } = useComposerContext();\n const card = slotProps(\n \"card\",\n [\n \"group relative border border-border bg-card shadow-soft transition-all focus-within:border-primary/40 focus-within:shadow-glow\",\n webEnabled && \"ring-1 ring-primary/20\",\n isDraggingFiles && \"ring-2 ring-primary/60\",\n ],\n classNames,\n sx,\n );\n\n // LexicalComposer must wrap everything that touches editor state, including\n // the toolbar and send button (so they can `useLexicalComposerContext()`).\n // Living here — one level above EditorShell — also means the inline layout\n // can place those siblings into the same flex row as the editor block.\n const initialConfig: InitialConfigType = useMemo(\n () => ({\n namespace: \"composeai\",\n theme: composerTheme,\n onError: (error) => {\n console.error(\"[Composer]\", error);\n },\n nodes: mode === \"markdown\" ? RICH_NODES : PLAIN_NODES,\n editorState: initialValue ? undefined : null,\n }),\n [mode, initialValue],\n );\n\n return (\n <div\n data-composer-root=\"\"\n data-composer-inline={multiline ? undefined : \"\"}\n {...card}\n >\n <div\n aria-hidden\n data-composer-overlay=\"\"\n className=\"pointer-events-none absolute inset-0 opacity-0 transition-opacity group-focus-within:opacity-100\"\n style={{\n background:\n \"linear-gradient(135deg, hsl(var(--primary)/0.08) 0%, transparent 40%, hsl(var(--primary)/0.06) 100%)\",\n }}\n />\n {isDraggingFiles && (\n <div\n aria-hidden\n data-composer-overlay=\"\"\n className=\"pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-primary/5 text-sm font-medium text-primary backdrop-blur-[1px]\"\n >\n Drop to attach\n </div>\n )}\n <LexicalComposer initialConfig={initialConfig}>\n <ComposerInner\n placeholder={placeholder}\n mode={mode}\n multiline={multiline}\n handleRef={handleRef}\n onSend={onSend}\n onStop={onStop}\n autoFocus={autoFocus}\n refocusOnSubmit={refocusOnSubmit}\n focusShortcut={focusShortcut}\n isStreaming={isStreaming}\n toolbarExtras={toolbarExtras}\n initialValue={initialValue}\n />\n </LexicalComposer>\n </div>\n );\n}\n\ninterface InnerProps {\n placeholder: string;\n mode: NonNullable<ComposerProps[\"mode\"]>;\n multiline: boolean;\n handleRef: React.ForwardedRef<ComposerHandle>;\n onSend?: ComposerProps[\"onSend\"];\n onStop?: ComposerProps[\"onStop\"];\n autoFocus?: boolean;\n refocusOnSubmit: boolean;\n focusShortcut: ComposerProps[\"focusShortcut\"];\n isStreaming: boolean;\n toolbarExtras: ComposerProps[\"toolbarExtras\"];\n initialValue?: string;\n}\n\nfunction ComposerInner({\n placeholder,\n mode,\n multiline,\n handleRef,\n onSend,\n onStop,\n autoFocus,\n refocusOnSubmit,\n focusShortcut,\n isStreaming,\n toolbarExtras,\n initialValue,\n}: InnerProps) {\n const [editor] = useLexicalComposerContext();\n const {\n features,\n attachments,\n clearAttachments,\n registerRunPrompt,\n attachmentOptions,\n } = useComposerContext();\n const canSendOnlyAttachment = attachmentOptions.canSendOnlyAttachment !== false;\n const hasUploadingAttachment = attachments.some((a) => a.status === \"uploading\");\n const hasFailedAttachment = attachments.some((a) => a.status === \"failed\");\n const uploadsBlocking = hasUploadingAttachment || hasFailedAttachment;\n const markdownEnabled = mode === \"markdown\" && features.markdown;\n const [hasText, setHasText] = useState<boolean>(\n !!initialValue && initialValue.trim().length > 0,\n );\n\n const onSendRef = useRef(onSend);\n onSendRef.current = onSend;\n const refocusOnSubmitRef = useRef(refocusOnSubmit);\n refocusOnSubmitRef.current = refocusOnSubmit;\n\n const submit = useCallback(() => {\n if (isStreaming) return;\n // Block while uploads are pending or have failed — the user has visible\n // chips telling them what's going on; sending mid-flight would lose the\n // attachments. Failed chips also block until the user removes them\n // (re-attaching the same file is the retry path).\n if (uploadsBlocking) return;\n let payload: ComposerSubmitPayload | null = null;\n editor.getEditorState().read(() => {\n const { text, mentions } = collectPlainAndMentions(editor);\n const markdown = toMarkdown(editor);\n const trimmed = text.trim();\n // Always require *something* to send. Attachments-only is allowed by\n // default; `canSendOnlyAttachment: false` flips that off — the user\n // must write at least one character even if files are attached.\n if (!trimmed) {\n if (attachments.length === 0) return;\n if (!canSendOnlyAttachment) return;\n }\n payload = {\n text: trimmed,\n markdown,\n attachments: [...attachments],\n mentions,\n };\n });\n if (!payload) return;\n onSendRef.current?.(payload);\n // Focus management is bundled INTO the editor.update via `onUpdate`,\n // which fires after Lexical commits the mutation AND its reconciler\n // has applied selection. If we ran focus/blur before then (as a\n // sibling statement after `editor.update`), the selection\n // restoration on the freshly-cleared root would resurrect focus on\n // the contenteditable and silently undo a blur we just performed.\n //\n // Reads are via refs so prop changes don't churn this callback:\n // - `refocusOnSubmit: true` → explicitly focus the editor. Covers\n // Send-button clicks, `sendValue` quick-prompts, and imperative\n // `ref.submit()`. Keyboard sends already keep focus implicitly,\n // so the call is a harmless no-op for them.\n // - `refocusOnSubmit: false` → explicitly BLUR the root element so\n // the prop is symmetric across triggers: clicking Send leaves\n // focus where it naturally went (the button), and pressing Enter\n // removes focus from the editor instead of letting it linger.\n editor.update(\n () => {\n const root = $getRoot();\n root.clear();\n root.append($createParagraphNode());\n },\n {\n onUpdate: () => {\n if (refocusOnSubmitRef.current) {\n focusEditor(editor);\n } else {\n const root = editor.getRootElement();\n if (root) root.blur();\n }\n },\n },\n );\n clearAttachments();\n }, [\n editor,\n attachments,\n clearAttachments,\n isStreaming,\n canSendOnlyAttachment,\n uploadsBlocking,\n ]);\n\n useComposerHandle(handleRef, submit);\n\n // Global focus shortcut (Cmd/Ctrl+/ by default). Configurable via\n // `focusShortcut`; pass `false` / `null` / `\"\"` to disable entirely.\n // Registered on `window` because the whole point is to grab focus from\n // anywhere on the page — including from inside other inputs that don't\n // know about us.\n useEffect(() => {\n if (!focusShortcut) return;\n const parsed = parseShortcut(focusShortcut);\n if (!parsed) return;\n const onKey = (e: KeyboardEvent) => {\n if (!matchesShortcut(parsed, e)) return;\n // `defaultPrevented` lets a more-local handler (e.g. a popover) win\n // when both are bound to the same combo. We never compete with a\n // child that already consumed the key.\n if (e.defaultPrevented) return;\n e.preventDefault();\n focusEditor(editor);\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [editor, focusShortcut]);\n\n // Seed initial value once on mount. Splits on `\\n` so each line becomes\n // its own paragraph — required for the per-paragraph markdown / mermaid\n // detectors to recognise multi-line blocks (e.g. a ```mermaid fence).\n const seededRef = useRef(false);\n useEffect(() => {\n if (seededRef.current) return;\n seededRef.current = true;\n if (!initialValue) return;\n editor.update(() => {\n $seedInitialValue(initialValue);\n });\n }, [editor, initialValue]);\n\n useEffect(() => {\n return editor.registerUpdateListener(() => {\n editor.getEditorState().read(() => {\n const text = $getRoot().getTextContent().trim();\n setHasText(text.length > 0);\n });\n });\n }, [editor]);\n\n // Quick-prompts bridge: the chip row lives above the editor so it doesn't\n // own the editor state or the submit function. It pipes its clicks through\n // the provider; we subscribe here to do the actual work. We deliberately\n // *replace* whatever is in the editor — `initValue` means \"use this as the\n // starting point\", which is unambiguous (and matches every other quick-\n // prompt UX I've seen).\n useEffect(() => {\n return registerRunPrompt((prompt, behavior) => {\n editor.update(() => {\n $seedInitialValue(prompt);\n });\n if (behavior === \"sendValue\") {\n // Defer to the next microtask so Lexical commits the update above\n // before `submit` reads the editor state. Without this, `submit`\n // would serialize the *previous* state and ignore the prompt.\n queueMicrotask(() => submit());\n } else {\n focusEditor(editor);\n }\n });\n }, [editor, registerRunPrompt, submit]);\n\n const toolbarSlot = <Toolbar extras={toolbarExtras} />;\n const sendButtonSlot = (\n <SendButton\n canSend={\n // Same gate as `submit`, kept in sync so the disabled state is\n // never out of step with what would actually happen on click.\n !uploadsBlocking &&\n (hasText || (attachments.length > 0 && canSendOnlyAttachment))\n }\n isStreaming={isStreaming}\n onSend={submit}\n onStop={onStop}\n />\n );\n\n return (\n <>\n <EditorShell\n placeholder={placeholder}\n mode={mode}\n multiline={multiline}\n header={<AttachmentTray />}\n toolbar={toolbarSlot}\n sendButton={sendButtonSlot}\n // Inline mode can't form a ```mermaid fence (no newlines), so we\n // skip the slot entirely — saves a mount and a `<MermaidPlugin>`\n // subscription, and keeps the card visually a single bar.\n footer={multiline ? <MermaidSlot /> : null}\n />\n\n <KeyboardPlugin onSubmit={submit} />\n <AutoFocusPlugin enabled={!!autoFocus} />\n <PasteDropPlugin />\n {markdownEnabled && <MarkdownPlugin />}\n {features.slashCommands && (\n <SlashCommandPlugin\n config={features.slashCommands}\n onSubmit={submit}\n />\n )}\n {features.mentions && <MentionPlugin config={features.mentions} />}\n {features.ghostedAutoComplete && (\n <GhostedAutoCompletePlugin config={features.ghostedAutoComplete} />\n )}\n </>\n );\n}\n\nfunction MermaidSlot() {\n const { features, mode } = useComposerContext();\n if (mode !== \"markdown\" || !features.mermaid) return null;\n return <MermaidPlugin />;\n}","import { cn } from \"../internal/cn\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\nexport interface SuggestionRowProps {\n /** Suggestion labels. Clicking one calls `onSelect` with that string. */\n items: string[];\n onSelect: (value: string) => void;\n className?: string;\n}\n\nexport function SuggestionRow({ items, onSelect, className }: SuggestionRowProps) {\n const { icons } = useComposerContext();\n const { sparkle: SparkleIcon } = icons;\n return (\n <div className={cn(\"flex flex-wrap justify-center gap-2\", className)}>\n {items.map((s) => (\n <button\n key={s}\n type=\"button\"\n onClick={() => onSelect(s)}\n className=\"group inline-flex items-center gap-1.5 rounded-full border border-border bg-card/60 px-3.5 py-1.5 text-xs text-muted-foreground backdrop-blur transition-all hover:-translate-y-px hover:border-primary/40 hover:bg-card hover:text-foreground hover:shadow-sm\"\n >\n <SparkleIcon className=\"h-3 w-3 text-primary opacity-70 group-hover:opacity-100\" />\n {s}\n </button>\n ))}\n </div>\n );\n}"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/insertText.ts","../src/internal/cn.ts","../src/internal/color.ts","../src/internal/sx.ts","../src/internal/icons.tsx","../src/core/ComposerProvider.tsx","../src/core/EditorShell.tsx","../src/core/theme.ts","../src/core/nodes/MentionNode.tsx","../src/core/nodes/MarkdownTokenNode.ts","../src/core/nodes/BlockParagraphNode.ts","../src/core/nodes/LinkTextNode.ts","../src/plugins/markdown-blocks.ts","../src/core/serializer.ts","../src/plugins/KeyboardPlugin.tsx","../src/internal/focusEditor.ts","../src/plugins/AutoFocusPlugin.tsx","../src/plugins/PasteDropPlugin.tsx","../src/plugins/markdown-tokenizer.ts","../src/plugins/MarkdownPlugin.tsx","../src/internal/Portal.tsx","../src/ui/ImageLightbox.tsx","../src/plugins/MermaidPlugin.tsx","../src/ui/SlashMenu.tsx","../src/ui/SmartPopover.tsx","../src/hooks/useOutsideClickDismiss.ts","../src/plugins/SlashCommandPlugin.tsx","../src/internal/Avatar.tsx","../src/ui/MentionMenu.tsx","../src/plugins/MentionPlugin.tsx","../src/plugins/GhostedAutoCompletePlugin.tsx","../src/ui/AttachmentChip.tsx","../src/plugins/AttachmentTray.tsx","../src/internal/Tooltip.tsx","../src/plugins/VoicePlugin.tsx","../src/ui/AttachmentTypePicker.tsx","../src/ui/Toolbar.tsx","../src/ui/SendButton.tsx","../src/ui/HintBar.tsx","../src/ui/QuickPrompts.tsx","../src/hooks/useComposerHandle.ts","../src/internal/shortcut.ts","../src/Composer.tsx","../src/ui/SuggestionRow.tsx"],"names":["$getSelection","$isRangeSelection","$getRoot","$createParagraphNode","$createTextNode","jsx","jsxs","Fragment","createContext","useMemo","useState","useRef","useCallback","useContext","ContentEditable","RichTextPlugin","LexicalErrorBoundary","PlainTextPlugin","HistoryPlugin","ElementNode","$applyNodeReplacement","TextNode","addClassNamesToElement","ParagraphNode","$isParagraphNode","$isElementNode","$isLineBreakNode","$isTextNode","offset","useLexicalComposerContext","useEffect","KEY_ENTER_COMMAND","COMMAND_PRIORITY_HIGH","PASTE_COMMAND","KEY_BACKSPACE_COMMAND","COMMAND_PRIORITY_LOW","createPortal","useLayoutEffect","KEY_ESCAPE_COMMAND","MenuOption","useBasicTypeaheadTriggerMatch","LexicalTypeaheadMenuPlugin","isSyncItems","KEY_TAB_COMMAND","chip","useId","isValidElement","cloneElement","forwardRef","Composer","LexicalComposer"],"mappings":";;;;;;;;;;;;;;;;AAgCA,SAAS,UAAU,IAAA,EAAsB;AACvC,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,QAAA,EAAU,IAAI,CAAA;AACpC;AASO,SAAS,+BAA+B,IAAA,EAAoB;AACjE,EAAA,MAAM,KAAA,GAAQ,SAAA,CAAU,IAAI,CAAA,CAAE,MAAM,IAAI,CAAA;AAExC,EAAA,MAAM,UAAU,MAA6B;AAC3C,IAAA,MAAM,IAAIA,qBAAA,EAAc;AACxB,IAAA,OAAOC,yBAAA,CAAkB,CAAC,CAAA,GAAI,CAAA,GAAI,IAAA;AAAA,EACpC,CAAA;AAEA,EAAA,IAAI,MAAM,OAAA,EAAQ;AAClB,EAAA,IAAI,CAAC,GAAA,EAAK;A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A;AAAA,MAEC,IAAA,EAAK,QAAA;AAAA,MACL,OAAA,EAAS,MAAM,QAAA,CAAS,CAAC,CAAA;AAAA,MACzB,SAAA,EAAU,qBAAA;AAAA,MAEV,QAAA,EAAA;AAAA,wBAAAD,eAAC,WAAA,EAAA,EAAY,CAAA;AAAA,QACZ;AAAA;AAAA,KAAA;AAAA,IANI;AAAA,GAQR,CAAA,EACH,CAAA;AAEJ","file":"index.cjs","sourcesContent":["/**\n * Helpers for inserting/seeding multi-line text into the editor.\n *\n * Why this exists:\n * The Slack-style markdown detector in `markdown-blocks.ts` operates on a\n * per-paragraph basis (each `ParagraphNode` IS one block: heading, quote,\n * code-line, etc.) and uses regexes anchored to the start AND end of the\n * paragraph's text. So multi-line text needs to live as multiple sibling\n * paragraphs for fence detection (and headings, lists, etc.) to work.\n *\n * By default, Lexical's text-paste / `selection.insertText` / our previous\n * `initialValue` seeding all stuffed multi-line content into a single\n * paragraph (with `LineBreakNode` children, or with embedded `\\n` chars).\n * That meant pasting or seeding a ```mermaid block silently produced no\n * diagram, because the fence never matched.\n *\n * These helpers convert each `\\n` into a real paragraph break so the\n * detector sees what it needs to see.\n *\n * All `$`-prefixed functions MUST be called inside an `editor.update(...)`\n * (or `getEditorState().read(...)` where noted) scope.\n */\nimport {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isRangeSelection,\n type RangeSelection,\n} from \"lexical\";\n\n/** Normalize CRLF / CR to LF so we never end up with stray `\\r` in nodes. */\nfunction normalize(text: string): string {\n return text.replace(/\\r\\n?/g, \"\\n\");\n}\n\n/**\n * Insert `text` at the current selection. Each `\\n` becomes a paragraph\n * break (via `selection.insertParagraph()`). Single-line input is a plain\n * `insertText` — no extra paragraph splitting.\n *\n * The caller must be inside an `editor.update(...)` scope.\n */\nexport function $insertTextWithParagraphBreaks(text: string): void {\n const lines = normalize(text).split(\"\\n\");\n\n const current = (): RangeSelection | null => {\n const s = $getSelection();\n return $isRangeSelection(s) ? s : null;\n };\n\n let sel = current();\n if (!sel) {\n // No live selection — typically because the editor has never been\n // focused (auto-demos, scripted ref.insert() calls, restoring drafts\n // before mount, etc.). Drop a caret at the end of the document so the\n // text actually lands somewhere instead of being silently swallowed.\n const root = $getRoot();\n const last = root.getLastChild();\n if (last && \"selectEnd\" in last && typeof last.selectEnd === \"function\") {\n (last as { selectEnd: () => void }).selectEnd();\n } else {\n root.selectEnd();\n }\n sel = current();\n if (!sel) return;\n }\n\n // Replace any currently-selected range before inserting.\n if (!sel.isCollapsed()) {\n sel.removeText();\n sel = current();\n if (!sel) return;\n }\n\n for (let i = 0; i < lines.length; i++) {\n if (i > 0) {\n sel.insertParagraph();\n sel = current();\n if (!sel) return;\n }\n if (lines[i].length > 0) {\n sel.insertText(lines[i]);\n sel = current();\n if (!sel) return;\n }\n }\n}\n\n/**\n * Seed the editor root with `text`, one `ParagraphNode` per `\\n`-delimited\n * line. Clears any existing content first. Used by `<Composer initialValue>`.\n *\n * Leaves the caret at the end of the seeded content so that subsequent\n * imperative `insert()` calls (which delegate to\n * `$insertTextWithParagraphBreaks`) land where the user / script expects.\n * Without this, a never-focused editor would silently swallow follow-up\n * inserts because `$getSelection()` returns null.\n *\n * The caller must be inside an `editor.update(...)` scope.\n */\nexport function $seedInitialValue(text: string): void {\n const root = $getRoot();\n root.clear();\n const lines = normalize(text).split(\"\\n\");\n if (lines.length === 0) {\n const para = $createParagraphNode();\n root.append(para);\n para.selectEnd();\n return;\n }\n let last: ReturnType<typeof $createParagraphNode> | null = null;\n for (const line of lines) {\n const para = $createParagraphNode();\n if (line.length > 0) para.append($createTextNode(line));\n root.append(para);\n last = para;\n }\n last?.selectEnd();\n}","/**\n * Tiny class-name combiner used internally by the composer.\n *\n * Replacement for `clsx` + `tailwind-merge`. We don't need full Tailwind\n * conflict-resolution because the composer ships plain CSS — utility-class\n * collisions are vanishingly rare inside the library. Last-wins via natural\n * CSS cascade order is sufficient.\n *\n * Accepts the same loose shapes `clsx` did:\n * - string → included if truthy\n * - number → converted to string\n * - false / null / undefined / 0 → dropped\n * - array → flattened recursively\n * - object → keys whose values are truthy are included\n */\nexport type ClassValue =\n | string\n | number\n | boolean\n | null\n | undefined\n | ClassValue[]\n | { [key: string]: unknown };\n\nexport function cn(...inputs: ClassValue[]): string {\n const out: string[] = [];\n walk(inputs, out);\n return out.join(\" \");\n}\n\nfunction walk(value: ClassValue, out: string[]): void {\n if (!value) return;\n if (typeof value === \"string\") {\n if (value.length > 0) out.push(value);\n return;\n }\n if (typeof value === \"number\") {\n out.push(String(value));\n return;\n }\n if (Array.isArray(value)) {\n for (const v of value) walk(v, out);\n return;\n }\n if (typeof value === \"object\") {\n for (const key in value) {\n if (value[key]) out.push(key);\n }\n }\n}","/**\n * Tiny color parser used by the `<Composer color=\"…\" />` shorthand.\n *\n * The composer's CSS variables store HSL components without the `hsl(...)`\n * wrapper — e.g. `--primary: 258 90% 62%` — so opacity composition like\n * `hsl(var(--primary) / 0.1)` keeps working. This helper accepts whatever\n * the consumer hands us (hex, rgb, hsl, or already-formatted components)\n * and normalises it to that shape.\n *\n * Returns `null` for inputs we can't parse — the caller silently falls\n * back to the default theme rather than throwing on a typo.\n */\nexport interface HslTriple {\n h: number;\n s: number;\n l: number;\n}\n\nconst COMPONENT_RE =\n /^\\s*(\\d+(?:\\.\\d+)?)\\s+(\\d+(?:\\.\\d+)?)%\\s+(\\d+(?:\\.\\d+)?)%\\s*$/;\nconst HSL_FN_RE =\n /^\\s*hsla?\\(\\s*(\\d+(?:\\.\\d+)?)(?:deg)?\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)%\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)%/i;\nconst HEX_RE = /^\\s*#([0-9a-f]{3}|[0-9a-f]{6})\\s*$/i;\nconst RGB_FN_RE =\n /^\\s*rgba?\\(\\s*(\\d+(?:\\.\\d+)?)\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)\\s*[,\\s]\\s*(\\d+(?:\\.\\d+)?)/i;\n\nexport function parseToHsl(value: string): HslTriple | null {\n if (typeof value !== \"string\") return null;\n\n const components = value.match(COMPONENT_RE);\n if (components) {\n return {\n h: parseFloat(components[1]),\n s: parseFloat(components[2]),\n l: parseFloat(components[3]),\n };\n }\n\n const hslFn = value.match(HSL_FN_RE);\n if (hslFn) {\n return {\n h: parseFloat(hslFn[1]),\n s: parseFloat(hslFn[2]),\n l: parseFloat(hslFn[3]),\n };\n }\n\n const hex = value.match(HEX_RE);\n if (hex) {\n let h = hex[1];\n if (h.length === 3) {\n h = h\n .split(\"\")\n .map((c) => c + c)\n .join(\"\");\n }\n const r = parseInt(h.slice(0, 2), 16) / 255;\n const g = parseInt(h.slice(2, 4), 16) / 255;\n const b = parseInt(h.slice(4, 6), 16) / 255;\n return rgbToHsl(r, g, b);\n }\n\n const rgbFn = value.match(RGB_FN_RE);\n if (rgbFn) {\n return rgbToHsl(\n clamp01(parseFloat(rgbFn[1]) / 255),\n clamp01(parseFloat(rgbFn[2]) / 255),\n clamp01(parseFloat(rgbFn[3]) / 255),\n );\n }\n\n return null;\n}\n\nfunction clamp01(n: number): number {\n return Math.min(1, Math.max(0, n));\n}\n\nfunction clampPct(n: number): number {\n return Math.min(100, Math.max(0, n));\n}\n\nfunction rgbToHsl(r: number, g: number, b: number): HslTriple {\n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n let h = 0;\n let s = 0;\n if (max !== min) {\n const d = max - min;\n s = l > 0.5 ? d / (2 - max - min) : d / (max + min);\n switch (max) {\n case r:\n h = (g - b) / d + (g < b ? 6 : 0);\n break;\n case g:\n h = (b - r) / d + 2;\n break;\n case b:\n h = (r - g) / d + 4;\n break;\n }\n h /= 6;\n }\n return {\n h: Math.round(h * 360),\n s: Math.round(s * 100),\n l: Math.round(l * 100),\n };\n}\n\n/** Format an HslTriple as the components-only string the composer's CSS expects. */\nexport function formatHslComponents(triple: HslTriple): string {\n return `${triple.h} ${triple.s}% ${triple.l}%`;\n}\n\n/**\n * Derive the full set of brand-coloured tokens from a single base color.\n *\n * Mapping rules — chosen so the brand color tints every \"live\" surface\n * without making text unreadable:\n *\n * --primary = base (web pill, mention chip, focus ring, mention avatar text)\n * --primary-foreground = base with very high/low L (text painted on top of --primary fills)\n * --accent = base hue, soft saturation, very light L (hover bg, selected menu row bg)\n * --accent-foreground = base hue, normal saturation, dark L (text on --accent surfaces)\n * --ring = base\n *\n * Other tokens (`--card`, `--background`, `--border`, …) are deliberately\n * left alone so the composer keeps its neutral chrome and only the hot\n * colour-bearing surfaces light up.\n */\nexport interface DerivedColorTokens {\n primary: string;\n primaryForeground: string;\n accent: string;\n accentForeground: string;\n ring: string;\n}\n\nexport function deriveColorTokens(value: string): DerivedColorTokens | null {\n const base = parseToHsl(value);\n if (!base) return null;\n\n const isLightBase = base.l >= 50;\n\n const primary = formatHslComponents(base);\n\n // Foreground sitting on top of `--primary`: pick the opposite end of the\n // lightness scale so contrast stays high regardless of where the brand\n // sits on the spectrum.\n const primaryForeground = formatHslComponents({\n h: base.h,\n s: Math.min(base.s, 30),\n l: isLightBase ? 10 : 98,\n });\n\n // Hover/selected backgrounds want a soft tint of the brand colour. Drop\n // saturation a touch so it doesn't fight the editor text.\n const accent = formatHslComponents({\n h: base.h,\n s: clampPct(Math.min(base.s, 70)),\n l: 95,\n });\n\n // Text on `--accent`: same hue, full saturation, sit it deep enough that\n // it reads cleanly on the soft tinted bg above.\n const accentForeground = formatHslComponents({\n h: base.h,\n s: clampPct(Math.max(base.s, 40)),\n l: 30,\n });\n\n return {\n primary,\n primaryForeground,\n accent,\n accentForeground,\n ring: primary,\n };\n}","/**\n * Lightweight `sx` engine for `<Composer />`.\n *\n * Goals:\n * - Zero dependencies. No emotion, no runtime CSS-in-JS.\n * - Predictable: an `sx` object is just a `React.CSSProperties` with a\n * handful of token-aware shortcuts. Anything we don't recognise is\n * passed through verbatim.\n *\n * We deliberately do NOT support:\n * - Pseudo selectors (`&:hover`, `&:focus-within`).\n * - Media queries.\n * - Responsive arrays (`[1, 2, 3]`).\n *\n * Consumers reach for {@link ComposerSlotClassNames} when those are\n * needed — that keeps the package's bundle small and the inline-style\n * surface area small enough to reason about.\n */\nimport type { CSSProperties } from \"react\";\nimport { cn, type ClassValue } from \"./cn\";\nimport type {\n ComposerSlot,\n ComposerSlotClassNames,\n ComposerSxMap,\n ComposerSxValue,\n ComposerTokens,\n} from \"../types\";\n\n/**\n * Token names recognised by the sx engine for color-bearing keys. They\n * mirror the CSS variables defined by the consumer's theme (and shipped in\n * `package/src/composer.css`).\n */\nconst COLOR_TOKENS: Readonly<Record<string, string>> = {\n primary: \"var(--primary)\",\n \"primary-foreground\": \"var(--primary-foreground)\",\n primaryForeground: \"var(--primary-foreground)\",\n accent: \"var(--accent)\",\n \"accent-foreground\": \"var(--accent-foreground)\",\n accentForeground: \"var(--accent-foreground)\",\n background: \"var(--background)\",\n foreground: \"var(--foreground)\",\n card: \"var(--card)\",\n \"card-foreground\": \"var(--card-foreground)\",\n cardForeground: \"var(--card-foreground)\",\n popover: \"var(--popover)\",\n \"popover-foreground\": \"var(--popover-foreground)\",\n popoverForeground: \"var(--popover-foreground)\",\n muted: \"var(--muted)\",\n \"muted-foreground\": \"var(--muted-foreground)\",\n mutedForeground: \"var(--muted-foreground)\",\n border: \"var(--border)\",\n ring: \"var(--ring)\",\n input: \"var(--input)\",\n destructive: \"var(--destructive)\",\n \"destructive-foreground\": \"var(--destructive-foreground)\",\n destructiveForeground: \"var(--destructive-foreground)\",\n success: \"var(--success)\",\n \"success-foreground\": \"var(--success-foreground)\",\n successForeground: \"var(--success-foreground)\",\n warning: \"var(--warning)\",\n \"warning-foreground\": \"var(--warning-foreground)\",\n warningForeground: \"var(--warning-foreground)\",\n};\n\n/** CSS keys we treat as color-bearing — token names expand to `hsl(var(--x))`. */\nconst COLOR_KEYS = new Set<string>([\n \"color\",\n \"backgroundColor\",\n \"borderColor\",\n \"borderTopColor\",\n \"borderRightColor\",\n \"borderBottomColor\",\n \"borderLeftColor\",\n \"outlineColor\",\n \"fill\",\n \"stroke\",\n \"caretColor\",\n \"textDecorationColor\",\n]);\n\nfunction expandColor(value: unknown): unknown {\n if (typeof value !== \"string\") return value;\n const trimmed = value.trim();\n // Anything that already looks like a CSS color (`#`, `rgb`, `hsl`,\n // `var(`, `transparent`, `currentColor`, etc.) passes straight through.\n const tokenVar = COLOR_TOKENS[trimmed];\n if (!tokenVar) return value;\n return `hsl(${tokenVar})`;\n}\n\n/**\n * Convert an {@link ComposerSxValue} to a plain {@link CSSProperties}\n * object. Returns `undefined` when the input is empty so callers can\n * cheaply skip merging.\n */\nexport function resolveSx(value?: ComposerSxValue): CSSProperties | undefined {\n if (!value) return undefined;\n const out: Record<string, unknown> = {};\n for (const key in value) {\n const raw = (value as Record<string, unknown>)[key];\n if (raw === undefined) continue;\n\n // `bg` shorthand → backgroundColor.\n if (key === \"bg\") {\n out.backgroundColor = expandColor(raw);\n continue;\n }\n\n if (COLOR_KEYS.has(key)) {\n out[key] = expandColor(raw);\n continue;\n }\n\n out[key] = raw;\n }\n return out as CSSProperties;\n}\n\ninterface SlotProps {\n className: string;\n style?: CSSProperties;\n}\n\n/**\n * Build the `{ className, style }` overlay for a given slot, given the\n * consumer-supplied per-slot maps. The `base` argument is whatever the\n * package itself wants to apply (utility classes, internal styles); both\n * the consumer's class and resolved sx are layered on top.\n */\nexport function slotProps(\n slot: ComposerSlot,\n base: ClassValue,\n classNames?: ComposerSlotClassNames,\n sx?: ComposerSxMap,\n baseStyle?: CSSProperties,\n): SlotProps {\n const className = cn(base, classNames?.[slot]);\n const resolved = resolveSx(sx?.[slot]);\n if (!resolved && !baseStyle) {\n return { className };\n }\n return {\n className,\n style: { ...baseStyle, ...resolved },\n };\n}\n\nconst COLOR_TOKEN_KEYS: ReadonlyArray<keyof ComposerTokens> = [\n \"primary\",\n \"primaryForeground\",\n \"accent\",\n \"accentForeground\",\n \"background\",\n \"foreground\",\n \"card\",\n \"cardForeground\",\n \"popover\",\n \"popoverForeground\",\n \"muted\",\n \"mutedForeground\",\n \"border\",\n \"ring\",\n \"input\",\n \"destructive\",\n \"destructiveForeground\",\n \"success\",\n \"successForeground\",\n \"warning\",\n \"warningForeground\",\n];\n\nconst COLOR_TOKEN_VAR: Record<string, string> = {\n primary: \"--primary\",\n primaryForeground: \"--primary-foreground\",\n accent: \"--accent\",\n accentForeground: \"--accent-foreground\",\n background: \"--background\",\n foreground: \"--foreground\",\n card: \"--card\",\n cardForeground: \"--card-foreground\",\n popover: \"--popover\",\n popoverForeground: \"--popover-foreground\",\n muted: \"--muted\",\n mutedForeground: \"--muted-foreground\",\n border: \"--border\",\n ring: \"--ring\",\n input: \"--input\",\n destructive: \"--destructive\",\n destructiveForeground: \"--destructive-foreground\",\n success: \"--success\",\n successForeground: \"--success-foreground\",\n warning: \"--warning\",\n warningForeground: \"--warning-foreground\",\n};\n\nfunction asLength(value: number | string): string {\n return typeof value === \"number\" ? `${value}px` : value;\n}\n\n/**\n * Convert a {@link ComposerTokens} map into a `style` object of CSS\n * custom properties suitable for inlining on the composer root. Every\n * `--*` here is read either by the package's CSS or by Tailwind utilities\n * the package uses (`bg-primary`, `text-muted-foreground`, etc.).\n */\nexport function tokensToStyle(tokens?: ComposerTokens): CSSProperties | undefined {\n if (!tokens) return undefined;\n const out: Record<string, string> = {};\n for (const key of COLOR_TOKEN_KEYS) {\n const v = tokens[key];\n if (typeof v === \"string\" && v.length > 0) {\n out[COLOR_TOKEN_VAR[key]] = v;\n }\n }\n if (tokens.radius !== undefined) out[\"--composer-radius\"] = asLength(tokens.radius);\n if (tokens.fontSize !== undefined) out[\"--composer-font-size\"] = asLength(tokens.fontSize);\n if (tokens.fontFamily !== undefined) out[\"--composer-font-family\"] = tokens.fontFamily;\n return Object.keys(out).length ? (out as CSSProperties) : undefined;\n}","/**\n * Built-in icon set for the composer.\n *\n * Why inline instead of `lucide-react`?\n * - Removes the runtime dependency entirely.\n * - Lets consumers override any icon with their own component via the\n * `icons` prop on `<Composer />` — useful for matching a brand kit\n * (Heroicons, Phosphor, Material, etc).\n *\n * The defaults below are 24x24 stroke SVGs drawn in the same visual idiom as\n * lucide so the out-of-the-box composer looks the same as before. Each icon\n * forwards arbitrary SVGProps so callers can pass `className`, `style`,\n * `aria-*`, etc.\n */\nimport type { ComponentType, ReactNode, SVGProps } from \"react\";\n\nexport type IconProps = SVGProps<SVGSVGElement>;\nexport type IconComponent = ComponentType<IconProps>;\n\nfunction makeIcon(displayName: string, paths: ReactNode): IconComponent {\n const Icon: IconComponent = (props) => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth={2}\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n {...props}\n >\n {paths}\n </svg>\n );\n Icon.displayName = displayName;\n return Icon;\n}\n\nexport const IconSend = makeIcon(\n \"IconSend\",\n <>\n <path d=\"M12 5v14\" />\n <path d=\"m19 12-7-7-7 7\" />\n </>,\n);\n\nexport const IconStop = makeIcon(\n \"IconStop\",\n <rect width=\"14\" height=\"14\" x=\"5\" y=\"5\" rx=\"2\" />,\n);\n\nexport const IconAttach = makeIcon(\n \"IconAttach\",\n <>\n <path d=\"M13.234 20.252 21 12.3\" />\n <path d=\"m16 6-8.414 8.586a2 2 0 0 0 0 2.828 2 2 0 0 0 2.828 0l8.414-8.586a4 4 0 0 0 0-5.656 4 4 0 0 0-5.656 0l-8.415 8.585a6 6 0 1 0 8.486 8.486\" />\n </>,\n);\n\nexport const IconImage = makeIcon(\n \"IconImage\",\n <>\n <rect width=\"18\" height=\"18\" x=\"3\" y=\"3\" rx=\"2\" ry=\"2\" />\n <circle cx=\"9\" cy=\"9\" r=\"2\" />\n <path d=\"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21\" />\n </>,\n);\n\nexport const IconVoice = makeIcon(\n \"IconVoice\",\n <>\n <path d=\"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z\" />\n <path d=\"M19 10v2a7 7 0 0 1-14 0v-2\" />\n <line x1=\"12\" x2=\"12\" y1=\"19\" y2=\"22\" />\n </>,\n);\n\nexport const IconVoiceRecording = makeIcon(\n \"IconVoiceRecording\",\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />,\n);\n\nexport const IconWeb = makeIcon(\n \"IconWeb\",\n <>\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\" />\n <path d=\"M2 12h20\" />\n </>,\n);\n\nexport const IconClose = makeIcon(\n \"IconClose\",\n <>\n <path d=\"M18 6 6 18\" />\n <path d=\"m6 6 12 12\" />\n </>,\n);\n\nexport const IconZoom = makeIcon(\n \"IconZoom\",\n <>\n <circle cx=\"11\" cy=\"11\" r=\"8\" />\n <line x1=\"21\" x2=\"16.65\" y1=\"21\" y2=\"16.65\" />\n <line x1=\"11\" x2=\"11\" y1=\"8\" y2=\"14\" />\n <line x1=\"8\" x2=\"14\" y1=\"11\" y2=\"11\" />\n </>,\n);\n\nexport const IconFile = makeIcon(\n \"IconFile\",\n <>\n <path d=\"M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z\" />\n <polyline points=\"14 2 14 8 20 8\" />\n <line x1=\"16\" x2=\"8\" y1=\"13\" y2=\"13\" />\n <line x1=\"16\" x2=\"8\" y1=\"17\" y2=\"17\" />\n <line x1=\"10\" x2=\"8\" y1=\"9\" y2=\"9\" />\n </>,\n);\n\nexport const IconAudio = makeIcon(\n \"IconAudio\",\n <>\n <path d=\"M9 18V5l12-2v13\" />\n <circle cx=\"6\" cy=\"18\" r=\"3\" />\n <circle cx=\"18\" cy=\"16\" r=\"3\" />\n </>,\n);\n\nexport const IconSparkle = makeIcon(\n \"IconSparkle\",\n <>\n <path d=\"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275Z\" />\n <path d=\"M5 3v4\" />\n <path d=\"M19 17v4\" />\n <path d=\"M3 5h4\" />\n <path d=\"M17 19h4\" />\n </>,\n);\n\nexport const IconSpinner = makeIcon(\n \"IconSpinner\",\n <path d=\"M21 12a9 9 0 1 1-6.219-8.56\" />,\n);\n\nexport const IconWarning = makeIcon(\n \"IconWarning\",\n <>\n <path d=\"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z\" />\n <path d=\"M12 9v4\" />\n <path d=\"M12 17h.01\" />\n </>,\n);\n\n/**\n * Public icon slot map. Consumers can override any of these via the\n * `icons` prop on `<Composer />`. Anything left unspecified falls back to\n * the built-in lucide-style default above.\n */\nexport interface ComposerIcons {\n /** Submit / send the message. */\n send: IconComponent;\n /** Stop an in-flight streaming response. */\n stop: IconComponent;\n /** Toolbar: attach any file. */\n attach: IconComponent;\n /** Toolbar: pick an image. */\n image: IconComponent;\n /** Voice plugin: start recording. */\n voice: IconComponent;\n /** Voice plugin: transcription in progress. */\n voiceRecording: IconComponent;\n /** Toolbar: enable web search. */\n web: IconComponent;\n /** Close / dismiss (e.g. lightbox, chip remove). */\n close: IconComponent;\n /** Zoom into an attachment / diagram. */\n zoom: IconComponent;\n /** Generic file (PDF, doc, etc) attachment. */\n file: IconComponent;\n /** Audio attachment. */\n audio: IconComponent;\n /** Decorative sparkle (suggestions, diagram preview header). */\n sparkle: IconComponent;\n /** Generic loading spinner (used on attachment chips during upload). */\n spinner: IconComponent;\n /** Generic warning / failure badge (used on failed-upload chips). */\n warning: IconComponent;\n}\n\nexport const DEFAULT_ICONS: ComposerIcons = {\n send: IconSend,\n stop: IconStop,\n attach: IconAttach,\n image: IconImage,\n voice: IconVoice,\n voiceRecording: IconVoiceRecording,\n web: IconWeb,\n close: IconClose,\n zoom: IconZoom,\n file: IconFile,\n audio: IconAudio,\n sparkle: IconSparkle,\n spinner: IconSpinner,\n warning: IconWarning,\n};\n\n/** Merge consumer-provided overrides with the built-in defaults. */\nexport function resolveIcons(\n overrides?: Partial<ComposerIcons>,\n): ComposerIcons {\n if (!overrides) return DEFAULT_ICONS;\n return { ...DEFAULT_ICONS, ...overrides };\n}","import {\n createContext,\n useCallback,\n useContext,\n useMemo,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n} from \"react\";\nimport type {\n Attachment,\n AttachmentOptions,\n AttachmentsConfig,\n ComposerFeatures,\n ComposerPromptBehavior,\n ComposerProps,\n ComposerSlotClassNames,\n ComposerSlots,\n ComposerSxMap,\n DiagramRenderer,\n MarkdownMode,\n} from \"../types\";\nimport { resolveIcons, type ComposerIcons } from \"../internal/icons\";\n\ntype ComposerMode = NonNullable<ComposerProps[\"mode\"]>;\n\ntype SubmitCallback = () => void;\ntype AddFilesCallback = (files: File[]) => void;\ntype RunPromptCallback = (\n prompt: string,\n behavior: ComposerPromptBehavior,\n) => void;\n\ninterface ComposerContextValue {\n features: Required<ComposerFeatures>;\n attachmentsConfig: AttachmentsConfig;\n attachments: Attachment[];\n addFiles: AddFilesCallback;\n removeAttachment: (id: string) => void;\n clearAttachments: () => void;\n registerAddFiles: (cb: AddFilesCallback) => () => void;\n /** Stream of submit requests; plugins can subscribe (e.g. SlashMenu intercepts Enter). */\n registerSubmit: (cb: SubmitCallback) => () => void;\n triggerSubmit: () => void;\n /**\n * Quick-prompts channel. The chip-row UI calls `runPrompt(text, behavior)`;\n * the inner editor (which owns the editor state and the submit function)\n * subscribes via `registerRunPrompt` and performs the actual insert /\n * insert-and-submit.\n */\n registerRunPrompt: (cb: RunPromptCallback) => () => void;\n runPrompt: RunPromptCallback;\n webEnabled: boolean;\n toggleWeb: () => void;\n isStreaming: boolean;\n isDraggingFiles: boolean;\n setIsDraggingFiles: (v: boolean) => void;\n closeMenusOnOutsideClick: boolean;\n /** See {@link AttachmentOptions}. Normalized so all sub-flags have defaults. */\n attachmentOptions: AttachmentOptions;\n /**\n * Resolved markdown rendering mode. Derived from `features.markdown`:\n * - `markdown: true` / `markdown: undefined` → `\"hybrid\"`\n * - `markdown: false` → `\"hybrid\"` (unused — plugin off)\n * - `markdown: { mode }` → that mode\n *\n * Read by MarkdownPlugin to decide whether to emit visible token spans\n * (`hybrid`) or to consume markers in place once they match (`live`).\n * Read by the serializer to know whether the document text IS the\n * markdown source (`hybrid`) or needs reconstructing from format flags\n * (`live`).\n */\n markdownMode: MarkdownMode;\n mode: ComposerMode;\n /** See `ComposerProps.multiline`. */\n multiline: boolean;\n /** See `ComposerProps.submitOnEnter`. */\n submitOnEnter: boolean;\n /** See `ComposerProps.smartNewline`. Only meaningful when `multiline` is true. */\n smartNewline: boolean;\n /** See `ComposerProps.focusShortcut`. `null` when the consumer disabled it\n * so HintBar / docs can skip rendering the shortcut. */\n focusShortcut: string | null;\n /** Resolved icon set (consumer overrides merged with the built-in defaults). */\n icons: ComposerIcons;\n /** Component-level slot overrides (currently sendButton / stopButton).\n * Internal components check this before rendering their default chrome. */\n slots: ComposerSlots;\n /** Consumer-supplied diagram renderer for ```mermaid (or any other) fences. */\n renderDiagram?: DiagramRenderer;\n /**\n * Writing direction explicitly set by the consumer (see\n * `ComposerProps.dir`). Plugins / popovers that escape the composer's\n * subtree (e.g. portaled menus) read this so they can mirror their layout\n * even when their portal target has a different direction than the\n * composer root.\n */\n dir?: \"ltr\" | \"rtl\" | \"auto\";\n /** Per-slot className overrides forwarded to every internal component. */\n classNames?: ComposerSlotClassNames;\n /** Per-slot `sx` overrides forwarded to every internal component. */\n sx?: ComposerSxMap;\n /**\n * Resolved token CSS custom properties (e.g. `{ \"--primary\": \"270 91% 65%\" }`)\n * that we re-apply on every portaled popover / overlay so the brand colour\n * cascades into UI that escapes `[data-composer-root]`. Computed once in\n * `<Composer />` and forwarded here so popups don't need to re-resolve it.\n */\n tokenStyle?: CSSProperties;\n}\n\nconst ComposerContext = createContext<ComposerContextValue | null>(null);\n\nconst DEFAULT_FEATURES: Required<ComposerFeatures> = {\n markdown: true,\n attachments: true,\n mentions: false,\n slashCommands: false,\n voice: true,\n mermaid: true,\n web: true,\n // Off by default — ghost autocomplete is an opt-in input affordance that\n // only makes sense when the consumer has a curated list of completions.\n ghostedAutoComplete: false,\n};\n\nconst DEFAULT_ATTACHMENTS: Required<AttachmentsConfig> = {\n // Show only the generic paperclip by default — its `accept` string already\n // includes images, so users can still attach photos via the OS dialog.\n // The dedicated image button is opt-in (`attachments: { image: true }`),\n // primarily for chat-heavy apps where jumping straight to the mobile\n // camera-roll picker is a UX win worth the second button.\n file: true,\n image: false,\n accept: \"image/*,application/pdf,text/*,audio/*,video/*\",\n // No type-picker popover by default — the paperclip opens the OS file\n // picker directly. When the consumer supplies a non-empty `types` list,\n // the paperclip flips into a small dropdown that lets the user pick a\n // category first, scoping the OS dialog to that type's `accept`.\n types: [],\n maxSize: 25 * 1024 * 1024,\n maxCount: 10,\n};\n\nfunction normalizeFeatures(features?: ComposerFeatures): Required<ComposerFeatures> {\n if (!features) return DEFAULT_FEATURES;\n return {\n markdown: features.markdown ?? DEFAULT_FEATURES.markdown,\n attachments: features.attachments ?? DEFAULT_FEATURES.attachments,\n mentions: features.mentions ?? DEFAULT_FEATURES.mentions,\n slashCommands: features.slashCommands ?? DEFAULT_FEATURES.slashCommands,\n voice: features.voice ?? DEFAULT_FEATURES.voice,\n mermaid: features.mermaid ?? DEFAULT_FEATURES.mermaid,\n web: features.web ?? DEFAULT_FEATURES.web,\n ghostedAutoComplete:\n features.ghostedAutoComplete ?? DEFAULT_FEATURES.ghostedAutoComplete,\n };\n}\n\nfunction detectKind(file: File): Attachment[\"kind\"] {\n if (file.type.startsWith(\"image/\")) return \"image\";\n if (file.type.startsWith(\"audio/\")) return \"audio\";\n return \"file\";\n}\n\n// Stable reference for the default (empty) slots object — using a fresh `{}`\n// on every render would invalidate the context memo and force every consumer\n// to re-render even when no slots are configured.\nconst EMPTY_SLOTS: ComposerSlots = Object.freeze({});\n\ninterface ProviderProps {\n features?: ComposerFeatures;\n isStreaming?: boolean;\n closeMenusOnOutsideClick?: boolean;\n attachmentOptions?: AttachmentOptions;\n mode?: ComposerMode;\n multiline?: boolean;\n submitOnEnter?: boolean;\n smartNewline?: boolean;\n focusShortcut?: string | false | null;\n icons?: Partial<ComposerIcons>;\n slots?: ComposerSlots;\n renderDiagram?: DiagramRenderer;\n dir?: \"ltr\" | \"rtl\" | \"auto\";\n classNames?: ComposerSlotClassNames;\n sx?: ComposerSxMap;\n tokenStyle?: CSSProperties;\n children: ReactNode;\n}\n\nexport function ComposerProvider({\n features,\n isStreaming,\n closeMenusOnOutsideClick = true,\n attachmentOptions,\n mode = \"markdown\",\n multiline = true,\n submitOnEnter = true,\n smartNewline = true,\n focusShortcut = \"mod+/\",\n icons,\n slots,\n renderDiagram,\n dir,\n classNames,\n sx,\n tokenStyle,\n children,\n}: ProviderProps) {\n const resolvedIcons = useMemo(() => resolveIcons(icons), [icons]);\n const normalizedFeatures = useMemo(() => normalizeFeatures(features), [features]);\n // Resolve markdown sub-config exactly once. We pre-collapse all the\n // shorthand cases (`true`, `false`, `{ mode }`) here so every consumer\n // (plugin, serializer, downstream UI) can just read `markdownMode`\n // without re-doing the boolean/object dance.\n const markdownMode = useMemo<MarkdownMode>(() => {\n const md = normalizedFeatures.markdown;\n if (typeof md === \"object\" && md.mode) return md.mode;\n return \"hybrid\";\n }, [normalizedFeatures.markdown]);\n const attachmentsConfig: AttachmentsConfig = useMemo(() => {\n if (typeof normalizedFeatures.attachments === \"object\") {\n return { ...DEFAULT_ATTACHMENTS, ...normalizedFeatures.attachments };\n }\n return DEFAULT_ATTACHMENTS;\n }, [normalizedFeatures.attachments]);\n\n const [attachments, setAttachments] = useState<Attachment[]>([]);\n const [webEnabled, setWebEnabled] = useState(false);\n const [isDraggingFiles, setIsDraggingFiles] = useState(false);\n\n const submitSubsRef = useRef(new Set<SubmitCallback>());\n const addFilesSubsRef = useRef(new Set<AddFilesCallback>());\n const runPromptSubsRef = useRef(new Set<RunPromptCallback>());\n\n // Normalize attachment-options with defaults. We expose this through the\n // context value, but the actual `addFiles` reads the upload handler via a\n // ref so we don't have to rebuild it (and tear down every paste/drop\n // subscriber) every time the consumer's callback identity changes.\n const normalizedAttachmentOptions = useMemo<AttachmentOptions>(\n () => ({\n uploadFirst: !!attachmentOptions?.uploadFirst,\n onUpload: attachmentOptions?.onUpload,\n canSendOnlyAttachment: attachmentOptions?.canSendOnlyAttachment ?? true,\n }),\n [\n attachmentOptions?.uploadFirst,\n attachmentOptions?.onUpload,\n attachmentOptions?.canSendOnlyAttachment,\n ],\n );\n const uploadHandlerRef = useRef<AttachmentOptions[\"onUpload\"]>(\n attachmentOptions?.onUpload,\n );\n uploadHandlerRef.current = attachmentOptions?.onUpload;\n const uploadFirstRef = useRef<boolean>(\n !!attachmentOptions?.uploadFirst,\n );\n uploadFirstRef.current = !!attachmentOptions?.uploadFirst;\n\n const removeAttachment = useCallback((id: string) => {\n setAttachments((prev) => {\n const next = prev.filter((a) => a.id !== id);\n const removed = prev.find((a) => a.id === id);\n if (removed?.previewUrl) URL.revokeObjectURL(removed.previewUrl);\n return next;\n });\n }, []);\n\n const clearAttachments = useCallback(() => {\n setAttachments((prev) => {\n prev.forEach((a) => a.previewUrl && URL.revokeObjectURL(a.previewUrl));\n return [];\n });\n }, []);\n\n // We read the latest `attachments.length` via a ref so this callback can\n // enforce `maxCount` correctly without re-creating itself on every list\n // change (which would invalidate every paste/drop subscriber that captured\n // it). The functional setAttachments below is the source of truth — the\n // ref-based count is just used to short-circuit before building objects.\n const attachmentsCountRef = useRef(0);\n attachmentsCountRef.current = attachments.length;\n\n const addFiles = useCallback<AddFilesCallback>(\n (files) => {\n if (files.length === 0) return;\n const enabled = !!normalizedFeatures.attachments;\n if (!enabled) return;\n\n // Build the accepted list out here so we know exactly which\n // attachments to start uploads for (we can't easily recover that\n // from inside the functional setter).\n const accepted: Attachment[] = [];\n let remaining =\n (attachmentsConfig.maxCount ?? Infinity) - attachmentsCountRef.current;\n const shouldUpload = uploadFirstRef.current && !!uploadHandlerRef.current;\n for (const file of files) {\n if (remaining <= 0) break;\n if (file.size > (attachmentsConfig.maxSize ?? Infinity)) continue;\n const kind = detectKind(file);\n accepted.push({\n id: `att-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n kind,\n name: file.name || `attachment.${kind}`,\n mimeType: file.type,\n size: file.size,\n file,\n previewUrl:\n kind === \"image\" || kind === \"audio\"\n ? URL.createObjectURL(file)\n : undefined,\n status: shouldUpload ? \"uploading\" : undefined,\n });\n remaining -= 1;\n }\n if (accepted.length === 0) return;\n\n setAttachments((prev) => [...prev, ...accepted]);\n addFilesSubsRef.current.forEach((cb) => cb(files));\n\n // Kick off uploads in parallel. Results land via setAttachments\n // updaters keyed on the attachment id, so a chip the user has already\n // removed simply gets skipped (the .map produces an unchanged array).\n if (shouldUpload) {\n const handler = uploadHandlerRef.current!;\n for (const att of accepted) {\n Promise.resolve()\n .then(() => handler(att.file))\n .then((ok) => {\n setAttachments((prev) =>\n prev.map((a) =>\n a.id === att.id\n ? {\n ...a,\n status: ok ? \"uploaded\" : \"failed\",\n error: ok ? undefined : \"Upload failed\",\n }\n : a,\n ),\n );\n })\n .catch((err: unknown) => {\n const message =\n err instanceof Error ? err.message : String(err ?? \"Upload failed\");\n setAttachments((prev) =>\n prev.map((a) =>\n a.id === att.id\n ? { ...a, status: \"failed\", error: message }\n : a,\n ),\n );\n });\n }\n }\n },\n [\n attachmentsConfig.maxCount,\n attachmentsConfig.maxSize,\n normalizedFeatures.attachments,\n ],\n );\n\n const registerAddFiles = useCallback<ComposerContextValue[\"registerAddFiles\"]>(\n (cb) => {\n addFilesSubsRef.current.add(cb);\n return () => {\n addFilesSubsRef.current.delete(cb);\n };\n },\n [],\n );\n\n const registerSubmit = useCallback<ComposerContextValue[\"registerSubmit\"]>(\n (cb) => {\n submitSubsRef.current.add(cb);\n return () => {\n submitSubsRef.current.delete(cb);\n };\n },\n [],\n );\n\n const triggerSubmit = useCallback(() => {\n submitSubsRef.current.forEach((cb) => cb());\n }, []);\n\n const registerRunPrompt = useCallback<\n ComposerContextValue[\"registerRunPrompt\"]\n >((cb) => {\n runPromptSubsRef.current.add(cb);\n return () => {\n runPromptSubsRef.current.delete(cb);\n };\n }, []);\n\n const runPrompt = useCallback<RunPromptCallback>((prompt, behavior) => {\n runPromptSubsRef.current.forEach((cb) => cb(prompt, behavior));\n }, []);\n\n const toggleWeb = useCallback(() => setWebEnabled((w) => !w), []);\n\n const value = useMemo<ComposerContextValue>(\n () => ({\n features: normalizedFeatures,\n attachmentsConfig,\n attachments,\n addFiles,\n removeAttachment,\n clearAttachments,\n registerAddFiles,\n registerSubmit,\n triggerSubmit,\n registerRunPrompt,\n runPrompt,\n webEnabled,\n toggleWeb,\n isStreaming: !!isStreaming,\n isDraggingFiles,\n setIsDraggingFiles,\n closeMenusOnOutsideClick,\n attachmentOptions: normalizedAttachmentOptions,\n markdownMode,\n mode,\n multiline,\n submitOnEnter,\n smartNewline,\n focusShortcut: focusShortcut || null,\n icons: resolvedIcons,\n slots: slots ?? EMPTY_SLOTS,\n renderDiagram,\n dir,\n classNames,\n sx,\n tokenStyle,\n }),\n [\n normalizedFeatures,\n attachmentsConfig,\n attachments,\n addFiles,\n removeAttachment,\n clearAttachments,\n registerAddFiles,\n registerSubmit,\n triggerSubmit,\n registerRunPrompt,\n runPrompt,\n webEnabled,\n toggleWeb,\n isStreaming,\n isDraggingFiles,\n closeMenusOnOutsideClick,\n normalizedAttachmentOptions,\n markdownMode,\n mode,\n multiline,\n submitOnEnter,\n smartNewline,\n focusShortcut,\n resolvedIcons,\n slots,\n renderDiagram,\n dir,\n classNames,\n sx,\n tokenStyle,\n ],\n );\n\n return <ComposerContext.Provider value={value}>{children}</ComposerContext.Provider>;\n}\n\nexport function useComposerContext(): ComposerContextValue {\n const ctx = useContext(ComposerContext);\n if (!ctx) {\n throw new Error(\"useComposerContext must be used inside <ComposerProvider>\");\n }\n return ctx;\n}","/**\n * EditorShell — slot-based layout for the composer card.\n *\n * The Lexical `<LexicalComposer>` lives one level up (in `ComposerCard`)\n * so that every consumer of editor state — including the toolbar / send\n * button — can sit as a sibling of the editor itself. That lets the\n * `multiline === false` (\"inline\") variant collapse toolbar, editor and\n * send into a single horizontal row without the toolbar/send having to\n * portal in from a deeper subtree.\n *\n * Two layouts are supported, picked via `multiline`:\n *\n * ┌───────────────────────── multiline (default) ─────────────────────────┐\n * │ header (attachment tray) │\n * │ editor (multi-line, max-h, vertical scroll) │\n * │ toolbar ─────────────────────────────────────────────────── send btn │\n * │ footer (mermaid preview) │\n * └───────────────────────────────────────────────────────────────────────┘\n *\n * ┌─────────────────────── multiline === false (inline) ──────────────────┐\n * │ header (attachment tray) │\n * │ toolbar │ editor (single-line, horizontal scroll) │ send btn │\n * │ footer (NOT rendered — mermaid can't form without newlines anyway) │\n * └───────────────────────────────────────────────────────────────────────┘\n */\nimport { RichTextPlugin } from \"@lexical/react/LexicalRichTextPlugin\";\nimport { PlainTextPlugin } from \"@lexical/react/LexicalPlainTextPlugin\";\nimport { ContentEditable } from \"@lexical/react/LexicalContentEditable\";\nimport { LexicalErrorBoundary } from \"@lexical/react/LexicalErrorBoundary\";\nimport { HistoryPlugin } from \"@lexical/react/LexicalHistoryPlugin\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { useComposerContext } from \"./ComposerProvider\";\nimport { resolveSx, slotProps } from \"../internal/sx\";\nimport type { ComposerProps } from \"../types\";\n\ntype Mode = NonNullable<ComposerProps[\"mode\"]>;\n\ninterface EditorShellProps {\n placeholder: string;\n mode: Mode;\n /**\n * `false` switches the shell into the inline / single-line layout\n * described above. Mirrors `ComposerProps.multiline`.\n */\n multiline: boolean;\n /** Rendered above the editor (attachment tray). */\n header?: ReactNode;\n /** Toolbar contents — rendered below the editor (multiline) or to its\n * start (inline). Toolbar omits a wrapping div so we can position it\n * via grid placement in either layout. */\n toolbar?: ReactNode;\n /** Send button — rendered to the right of the toolbar (multiline) or to\n * the end of the editor row (inline). */\n sendButton?: ReactNode;\n /** Rendered below the toolbar row (mermaid preview). Skipped in inline\n * mode by the caller — single-line input can't form a mermaid fence. */\n footer?: ReactNode;\n}\n\nexport function EditorShell({\n placeholder,\n mode,\n multiline,\n header,\n toolbar,\n sendButton,\n footer,\n}: EditorShellProps) {\n const { classNames, sx, dir } = useComposerContext();\n const isMarkdown = mode === \"markdown\";\n\n // Editor padding differs per layout:\n // multiline: roomy vertical padding for multi-line writing.\n // inline: no vertical padding (height drives the size); horizontal\n // padding hugs the editor between toolbar and send so the\n // caret never bumps into them.\n const editorClass = multiline\n ? \"composer-editor composer-editor--multiline\"\n : \"composer-editor composer-editor--inline\";\n\n const editor = slotProps(\"editor\", editorClass, classNames, sx);\n\n // Placeholder mirrors editor padding/typography so the placeholder text\n // sits exactly where the caret will land. In inline mode the placeholder\n // also gets `leading-9` (1.75rem) to vertically center within the 36px row.\n const editorResolved = resolveSx(sx?.editor);\n const placeholderBase = mirrorEditorPadding(editorResolved);\n const placeholderClass = multiline\n ? \"composer-placeholder composer-placeholder--multiline\"\n : \"composer-placeholder composer-placeholder--inline\";\n const placeholderProps = slotProps(\n \"placeholder\",\n placeholderClass,\n classNames,\n sx,\n placeholderBase,\n );\n\n const contentEditable = (\n <ContentEditable {...editor} aria-label=\"Message\" spellCheck dir={dir} />\n );\n const placeholderEl = (\n <div {...placeholderProps} dir={dir}>\n {placeholder}\n </div>\n );\n\n const editorBlock = (\n <div\n className={cn(\n \"composer-editor-block\",\n // Inline: the editor block is the flex child that fills the row.\n !multiline && \"composer-editor-block--inline\",\n )}\n >\n {isMarkdown ? (\n <RichTextPlugin\n contentEditable={contentEditable}\n placeholder={placeholderEl}\n ErrorBoundary={LexicalErrorBoundary}\n />\n ) : (\n <PlainTextPlugin\n contentEditable={contentEditable}\n placeholder={placeholderEl}\n ErrorBoundary={LexicalErrorBoundary}\n />\n )}\n </div>\n );\n\n if (!multiline) {\n // Inline layout — header above, then a single horizontal row of\n // [toolbar | editor | send]. We don't render `footer` here because the\n // caller already opts out of <MermaidSlot /> when multiline is false\n // (no newlines means no fences can ever form).\n return (\n <>\n {header}\n <div className=\"composer-inline-row\">\n {toolbar && (\n <div className=\"composer-inline-toolbar\">{toolbar}</div>\n )}\n {editorBlock}\n {sendButton && (\n <div className=\"composer-inline-send\">{sendButton}</div>\n )}\n </div>\n <HistoryPlugin />\n </>\n );\n }\n\n // Multi-line layout — header, editor, toolbar+send row (justify-between),\n // footer. Matches the historical structure exactly.\n return (\n <>\n {header}\n {editorBlock}\n {(toolbar || sendButton) && (\n <div className=\"composer-toolbar-row\">\n {toolbar ?? <span />}\n {sendButton}\n </div>\n )}\n <HistoryPlugin />\n {footer}\n </>\n );\n}\n\n// Keys we copy from `sx.editor` onto the placeholder so the placeholder text\n// stays aligned with the editor's caret/text origin when the consumer\n// customises the editor's padding or typography.\nconst PLACEHOLDER_MIRROR_KEYS: ReadonlyArray<keyof CSSProperties> = [\n \"padding\",\n \"paddingInline\",\n \"paddingInlineStart\",\n \"paddingInlineEnd\",\n \"paddingBlock\",\n \"paddingBlockStart\",\n \"paddingTop\",\n \"paddingLeft\",\n \"paddingRight\",\n \"fontSize\",\n \"fontFamily\",\n \"lineHeight\",\n \"letterSpacing\",\n];\n\nfunction mirrorEditorPadding(\n editorStyle: CSSProperties | undefined,\n): CSSProperties | undefined {\n if (!editorStyle) return undefined;\n const out: Record<string, unknown> = {};\n for (const key of PLACEHOLDER_MIRROR_KEYS) {\n const v = (editorStyle as Record<string, unknown>)[key as string];\n if (v !== undefined) out[key as string] = v;\n }\n return Object.keys(out).length ? (out as CSSProperties) : undefined;\n}","import type { EditorThemeClasses } from \"lexical\";\n\nexport const composerTheme: EditorThemeClasses = {\n paragraph: \"composer-paragraph\",\n quote: \"composer-quote\",\n heading: {\n h1: \"composer-h1\",\n h2: \"composer-h2\",\n h3: \"composer-h3\",\n h4: \"composer-h4\",\n h5: \"composer-h5\",\n h6: \"composer-h6\",\n },\n list: {\n ul: \"composer-ul\",\n ol: \"composer-ol\",\n listitem: \"composer-li\",\n nested: {\n listitem: \"composer-li-nested\",\n },\n },\n text: {\n bold: \"composer-bold\",\n italic: \"composer-italic\",\n underline: \"composer-underline\",\n strikethrough: \"composer-strike\",\n underlineStrikethrough: \"composer-underline composer-strike\",\n code: \"composer-code\",\n },\n code: \"composer-code-block\",\n codeHighlight: {\n atrule: \"composer-token-attr\",\n attr: \"composer-token-attr\",\n boolean: \"composer-token-property\",\n builtin: \"composer-token-selector\",\n cdata: \"composer-token-comment\",\n char: \"composer-token-selector\",\n class: \"composer-token-function\",\n \"class-name\": \"composer-token-function\",\n comment: \"composer-token-comment\",\n constant: \"composer-token-property\",\n deleted: \"composer-token-property\",\n doctype: \"composer-token-comment\",\n entity: \"composer-token-operator\",\n function: \"composer-token-function\",\n important: \"composer-token-variable\",\n inserted: \"composer-token-selector\",\n keyword: \"composer-token-attr\",\n namespace: \"composer-token-variable\",\n number: \"composer-token-property\",\n operator: \"composer-token-operator\",\n prolog: \"composer-token-comment\",\n property: \"composer-token-property\",\n punctuation: \"composer-token-punctuation\",\n regex: \"composer-token-variable\",\n selector: \"composer-token-selector\",\n string: \"composer-token-selector\",\n symbol: \"composer-token-property\",\n tag: \"composer-token-property\",\n url: \"composer-token-operator\",\n variable: \"composer-token-variable\",\n },\n link: \"composer-link\",\n};","/**\n * MentionNode — an inline ElementNode that wraps an editable `TextNode`\n * containing the mention's label. The chip carries the mention's stable\n * `id` and its trigger character (`@`, `#`, …) on the wrapping element so\n * the user can backspace through the label one character at a time and\n * the ID stays glued to whatever is left.\n *\n * Why ElementNode (not DecoratorNode)?\n * - The old DecoratorNode chip was atomic: one backspace removed the\n * entire mention, even when the label was \"First Last\" with a space.\n * - As an ElementNode the chip's children are real TextNodes, so the\n * caret traverses them naturally; backspace, selection, IME, and\n * paste all \"just work\".\n *\n * The trigger character (`@`/`#`/…) is rendered via a CSS `::before`\n * pseudo-element keyed off `data-mention-prefix`, so it's visible but\n * NOT part of the editable text content. That guarantees the user can\n * never backspace the prefix away — they can only shorten the label\n * itself. When the label becomes empty the entire chip is removed by\n * Lexical (`canBeEmpty() = false`).\n */\nimport {\n $applyNodeReplacement,\n $createTextNode,\n ElementNode,\n type DOMConversionMap,\n type DOMExportOutput,\n type EditorConfig,\n type LexicalNode,\n type NodeKey,\n type SerializedElementNode,\n type Spread,\n} from \"lexical\";\n\nexport type SerializedMentionNode = Spread<\n {\n mentionId: string;\n mentionPrefix: string;\n },\n SerializedElementNode\n>;\n\nexport class MentionNode extends ElementNode {\n /** Stable identifier supplied by the consumer's MentionItem. */\n __id: string;\n /** Trigger character shown via CSS `::before` (e.g. \"@\" or \"#\"). */\n __prefix: string;\n\n static getType(): string {\n return \"composeai-mention\";\n }\n\n static clone(node: MentionNode): MentionNode {\n return new MentionNode(node.__id, node.__prefix, node.__key);\n }\n\n constructor(id: string, prefix: string = \"@\", key?: NodeKey) {\n super(key);\n this.__id = id;\n this.__prefix = prefix;\n }\n\n // ── Stable accessors ────────────────────────────────────────────────\n getMentionId(): string {\n return this.__id;\n }\n\n getMentionPrefix(): string {\n return this.__prefix;\n }\n\n /**\n * The current label text. Reflects user edits — if the user backspaced\n * \"@John Doe\" down to \"@John\", this returns \"John\".\n */\n getMentionLabel(): string {\n return this.getTextContent();\n }\n\n // ── Behavior flags ──────────────────────────────────────────────────\n isInline(): boolean {\n return true;\n }\n\n /**\n * Returning false makes Lexical auto-remove the element as soon as its\n * children collection becomes empty. That implements \"delete the whole\n * mention when I remove all the text\" with zero plugin code.\n */\n canBeEmpty(): boolean {\n return false;\n }\n\n /**\n * Prevent adjacent text outside the chip from accidentally merging\n * INTO the chip — typing \"x\" right after a mention should produce\n * \"@John|x\", not \"@Johnx\".\n */\n canInsertTextBefore(): boolean {\n return false;\n }\n\n canInsertTextAfter(): boolean {\n return false;\n }\n\n // ── DOM ─────────────────────────────────────────────────────────────\n createDOM(_config: EditorConfig): HTMLElement {\n const span = document.createElement(\"span\");\n span.className = \"composer-mention\";\n span.setAttribute(\"data-mention-id\", this.__id);\n span.setAttribute(\"data-mention-prefix\", this.__prefix);\n return span;\n }\n\n updateDOM(prev: MentionNode, dom: HTMLElement): boolean {\n // Keep the data attributes in sync if id/prefix ever change. Children\n // are reconciled by Lexical, so we return false to keep the existing\n // DOM element.\n if (prev.__id !== this.__id) dom.setAttribute(\"data-mention-id\", this.__id);\n if (prev.__prefix !== this.__prefix) {\n dom.setAttribute(\"data-mention-prefix\", this.__prefix);\n }\n return false;\n }\n\n exportDOM(): DOMExportOutput {\n const el = document.createElement(\"span\");\n el.setAttribute(\"data-mention-id\", this.__id);\n el.setAttribute(\"data-mention-prefix\", this.__prefix);\n // For the exported DOM we inline the prefix into the text so the\n // mention survives copy/paste into apps that don't load our CSS.\n el.textContent = `${this.__prefix}${this.getTextContent()}`;\n return { element: el };\n }\n\n static importDOM(): DOMConversionMap | null {\n return {\n span: (node: HTMLElement) => {\n if (!node.hasAttribute(\"data-mention-id\")) return null;\n return {\n conversion: () => {\n const id = node.getAttribute(\"data-mention-id\") ?? \"\";\n const prefix = node.getAttribute(\"data-mention-prefix\") ?? \"@\";\n const rawText = node.textContent ?? \"\";\n // Strip the prefix we may have inlined during exportDOM.\n const label = rawText.startsWith(prefix)\n ? rawText.slice(prefix.length)\n : rawText;\n const mention = $createMentionNode(id, prefix);\n if (label) {\n mention.append($createTextNode(label));\n }\n return { node: mention };\n },\n priority: 1,\n };\n },\n };\n }\n\n // ── JSON ────────────────────────────────────────────────────────────\n exportJSON(): SerializedMentionNode {\n return {\n ...super.exportJSON(),\n type: MentionNode.getType(),\n version: 1,\n mentionId: this.__id,\n mentionPrefix: this.__prefix,\n };\n }\n\n static importJSON(json: SerializedMentionNode): MentionNode {\n // Children (the label TextNode) are restored by Lexical's default\n // ElementNode JSON handling — we only need to recover id + prefix.\n return $createMentionNode(json.mentionId, json.mentionPrefix ?? \"@\");\n }\n}\n\nexport function $createMentionNode(\n id: string,\n prefix: string = \"@\",\n): MentionNode {\n return $applyNodeReplacement(new MentionNode(id, prefix));\n}\n\nexport function $isMentionNode(\n node: LexicalNode | null | undefined,\n): node is MentionNode {\n return node instanceof MentionNode;\n}","import {\n $applyNodeReplacement,\n TextNode,\n addClassNamesToElement,\n type EditorConfig,\n type LexicalNode,\n type LexicalUpdateJSON,\n type NodeKey,\n type SerializedTextNode,\n} from \"lexical\";\n\nexport type SerializedMarkdownTokenNode = SerializedTextNode;\n\nconst TOKEN_CLASS = \"composer-md-token\";\n\n/**\n * A muted-styled TextNode used to render markdown markers (asterisks,\n * underscores, backticks, tildes) while keeping them part of the source.\n * The caret traverses these characters naturally like normal text.\n */\nexport class MarkdownTokenNode extends TextNode {\n static getType(): string {\n return \"composeai-md-token\";\n }\n\n static clone(node: MarkdownTokenNode): MarkdownTokenNode {\n return new MarkdownTokenNode(node.__text, node.__key);\n }\n\n constructor(text: string = \"\", key?: NodeKey) {\n super(text, key);\n }\n\n createDOM(config: EditorConfig): HTMLElement {\n const dom = super.createDOM(config);\n addClassNamesToElement(dom, TOKEN_CLASS);\n return dom;\n }\n\n static importJSON(\n serializedNode: SerializedMarkdownTokenNode,\n ): MarkdownTokenNode {\n return $createMarkdownTokenNode().updateFromJSON(serializedNode);\n }\n\n updateFromJSON(\n serializedNode: LexicalUpdateJSON<SerializedMarkdownTokenNode>,\n ): this {\n return super.updateFromJSON(serializedNode);\n }\n\n exportJSON(): SerializedMarkdownTokenNode {\n return {\n ...super.exportJSON(),\n type: MarkdownTokenNode.getType(),\n version: 1,\n };\n }\n}\n\nexport function $createMarkdownTokenNode(text: string = \"\"): MarkdownTokenNode {\n return $applyNodeReplacement(new MarkdownTokenNode(text));\n}\n\nexport function $isMarkdownTokenNode(\n node: LexicalNode | null | undefined,\n): node is MarkdownTokenNode {\n return node instanceof MarkdownTokenNode;\n}","/**\n * A drop-in replacement for Lexical's `ParagraphNode` that remembers the\n * markdown block marker (e.g. `\"# \"`, `\"## \"`, `\"> \"`, `` \"```ts\" ``) that\n * was originally on the paragraph but has been hidden from the visible text\n * in `live` markdown mode.\n *\n * Why we need this:\n * --------------------------------------------------------------------------\n * In hybrid mode the block marker is part of the paragraph's text content\n * (rendered as a muted `MarkdownTokenNode`). The block kind is detected\n * from the text on every restyle pass via `detectBlock()`. The serializer\n * just emits the visible text verbatim.\n *\n * In `live` mode we drop the marker chars so the user sees `# Title` as\n * \"Title\" — Notion-style. The block kind is no longer recoverable from\n * the visible text (the leading `# ` is gone) so we stash the original\n * marker string on the paragraph node itself. The detector then prefers\n * that marker, and the serializer reconstructs `# Title` for the submit\n * payload.\n *\n * Keeping the marker as a property (rather than as a hidden TextNode child)\n * sidesteps a bunch of caret-navigation footguns: the paragraph's\n * `getTextContent()` cleanly equals the visible text, so existing offset /\n * selection math in the markdown plugin and the rest of the editor needs\n * no changes.\n *\n * Lifecycle:\n * - Registered as `{replace: ParagraphNode, with: () => new BlockParagraphNode()}`\n * so every `$createParagraphNode()` actually mints a BlockParagraphNode.\n * - `__blockMarker` defaults to `\"\"` (regular paragraph).\n * - `insertNewAfter()` is overridden to return a fresh BlockParagraphNode\n * with NO marker — pressing Enter at the end of a `# Heading` line\n * creates a plain paragraph below, the expected behavior.\n * - `clone()` and `exportJSON()` persist `__blockMarker` across\n * reconciler clones and editor-state serialisation.\n */\n\nimport {\n $applyNodeReplacement,\n ParagraphNode,\n type LexicalUpdateJSON,\n type NodeKey,\n type RangeSelection,\n type SerializedParagraphNode,\n type Spread,\n} from \"lexical\";\n\nexport type SerializedBlockParagraphNode = Spread<\n { blockMarker: string },\n SerializedParagraphNode\n>;\n\nexport class BlockParagraphNode extends ParagraphNode {\n __blockMarker: string;\n\n constructor(key?: NodeKey) {\n super(key);\n this.__blockMarker = \"\";\n }\n\n static getType(): string {\n return \"composeai-block-paragraph\";\n }\n\n static clone(node: BlockParagraphNode): BlockParagraphNode {\n const next = new BlockParagraphNode(node.__key);\n next.__blockMarker = node.__blockMarker;\n return next;\n }\n\n static importJSON(\n serializedNode: SerializedBlockParagraphNode,\n ): BlockParagraphNode {\n return $createBlockParagraphNode().updateFromJSON(serializedNode);\n }\n\n updateFromJSON(\n serializedNode: LexicalUpdateJSON<SerializedBlockParagraphNode>,\n ): this {\n super.updateFromJSON(serializedNode);\n const writable = this.getWritable() as this;\n writable.__blockMarker = serializedNode.blockMarker ?? \"\";\n return writable;\n }\n\n exportJSON(): SerializedBlockParagraphNode {\n return {\n ...super.exportJSON(),\n type: BlockParagraphNode.getType(),\n version: 1,\n blockMarker: this.getBlockMarker(),\n };\n }\n\n getBlockMarker(): string {\n return this.getLatest().__blockMarker;\n }\n\n setBlockMarker(marker: string): this {\n const writable = this.getWritable();\n writable.__blockMarker = marker;\n return writable;\n }\n\n hasBlockMarker(): boolean {\n return this.getLatest().__blockMarker.length > 0;\n }\n\n // Enter inside a block paragraph should start a clean paragraph below —\n // headings, quotes, lists, fences etc. don't bleed into the next line.\n insertNewAfter(\n rangeSelection: RangeSelection,\n restoreSelection: boolean = false,\n ): ParagraphNode {\n const next = super.insertNewAfter(rangeSelection, restoreSelection);\n // `super.insertNewAfter()` calls `$createParagraphNode()` which the\n // node-replacement machinery turns into a BlockParagraphNode with\n // empty marker. Defensive: explicitly clear it in case future Lexical\n // versions bypass the replacement here.\n if (next instanceof BlockParagraphNode) {\n next.setBlockMarker(\"\");\n }\n return next;\n }\n}\n\nexport function $createBlockParagraphNode(): BlockParagraphNode {\n return $applyNodeReplacement(new BlockParagraphNode());\n}\n\nexport function $isBlockParagraphNode(\n node: unknown,\n): node is BlockParagraphNode {\n return node instanceof BlockParagraphNode;\n}","/**\n * A TextNode subclass used in `live` markdown mode to represent the\n * VISIBLE label of a link while remembering the (hidden) URL on the side.\n *\n * Why a custom node rather than Lexical's `@lexical/link` LinkNode:\n * - LinkNode is an ElementNode that wraps a TextNode child, adding a\n * real `<a>` wrapper. That works, but it complicates the plugin's\n * children-equality / per-char format map (which assumes inline =\n * TextNode and bails on element children) and pulls in another\n * package dependency. Our needs are minimal — paint as a link, hold\n * a string `url` — so a TextNode subclass keeps the rest of the\n * plugin code unchanged.\n *\n * In hybrid mode the markers `[`, `](`, `)` AND the URL all stay in the\n * visible text (rendered as muted tokens via MarkdownTokenNode). No\n * LinkTextNode is created.\n *\n * In live mode the markers + URL are removed from the visible text; the\n * URL is stashed on this node so the serializer can reconstruct\n * `[label](url)` on submit.\n */\n\nimport {\n $applyNodeReplacement,\n TextNode,\n addClassNamesToElement,\n type EditorConfig,\n type LexicalNode,\n type LexicalUpdateJSON,\n type NodeKey,\n type SerializedTextNode,\n type Spread,\n} from \"lexical\";\n\nexport type SerializedLinkTextNode = Spread<\n { url: string },\n SerializedTextNode\n>;\n\nconst LINK_CLASS = \"composer-link\";\n\nexport class LinkTextNode extends TextNode {\n __url: string;\n\n constructor(text: string = \"\", url: string = \"\", key?: NodeKey) {\n super(text, key);\n this.__url = url;\n }\n\n static getType(): string {\n return \"composeai-link-text\";\n }\n\n static clone(node: LinkTextNode): LinkTextNode {\n return new LinkTextNode(node.__text, node.__url, node.__key);\n }\n\n createDOM(config: EditorConfig): HTMLElement {\n const dom = super.createDOM(config);\n addClassNamesToElement(dom, LINK_CLASS);\n // We deliberately render as a span (the super's element type) with a\n // class rather than an actual `<a>`. The composer is an input — the\n // user can't navigate away from it by clicking — and a real anchor\n // would steal focus on click in some browsers. The CSS already\n // matches `<a>` styling closely; the URL is reachable from the\n // serialized markdown on submit.\n if (this.__url) dom.setAttribute(\"data-url\", this.__url);\n return dom;\n }\n\n updateDOM(\n prevNode: this,\n dom: HTMLElement,\n config: EditorConfig,\n ): boolean {\n const updated = super.updateDOM(prevNode, dom, config);\n if (prevNode.__url !== this.__url) {\n if (this.__url) dom.setAttribute(\"data-url\", this.__url);\n else dom.removeAttribute(\"data-url\");\n }\n return updated;\n }\n\n static importJSON(serializedNode: SerializedLinkTextNode): LinkTextNode {\n return $createLinkTextNode(\"\", \"\").updateFromJSON(serializedNode);\n }\n\n updateFromJSON(\n serializedNode: LexicalUpdateJSON<SerializedLinkTextNode>,\n ): this {\n super.updateFromJSON(serializedNode);\n const writable = this.getWritable() as this;\n writable.__url = serializedNode.url ?? \"\";\n return writable;\n }\n\n exportJSON(): SerializedLinkTextNode {\n return {\n ...super.exportJSON(),\n type: LinkTextNode.getType(),\n version: 1,\n url: this.getUrl(),\n };\n }\n\n getUrl(): string {\n return this.getLatest().__url;\n }\n\n setUrl(url: string): this {\n const writable = this.getWritable();\n writable.__url = url;\n return writable;\n }\n\n // Typing at the boundary of the link should NOT extend the link — the\n // user wants their next char to be plain text, not \"part of the link\n // label\". Lexical honours these by creating a new sibling TextNode for\n // boundary insertions. Internal edits (cursor between chars) still go\n // into this node, which keeps label editing natural.\n canInsertTextBefore(): boolean {\n return false;\n }\n\n canInsertTextAfter(): boolean {\n return false;\n }\n}\n\nexport function $createLinkTextNode(\n text: string = \"\",\n url: string = \"\",\n): LinkTextNode {\n return $applyNodeReplacement(new LinkTextNode(text, url));\n}\n\nexport function $isLinkTextNode(\n node: LexicalNode | null | undefined,\n): node is LinkTextNode {\n return node instanceof LinkTextNode;\n}","/**\n * Block-level markdown detector. Operates on a single paragraph's text and\n * (when relevant) the running \"are we inside a fenced code block\" state of\n * the previous paragraphs.\n *\n * Block kinds supported:\n * - paragraph — default; no special block\n * - heading 1..6 — `# `, `## `, … `###### `\n * - quote — `> `\n * - list-bullet — `- `, `* `, `+ `\n * - list-numbered — `1. `, `42. `, etc.\n * - hr — `---`, `***`, `___` alone on a line\n * - code-fence-open — `` ``` `` or ` ```lang ` alone on a line\n * - code-fence-close — `` ``` `` alone on a line, when currently inside\n * - code-line — any paragraph that lives between an open and close\n * fence\n *\n * The detector is *line-conservative*: a block kind is only returned when\n * the marker is at the very start of the paragraph (after optional leading\n * whitespace) and the rest of the line is shaped correctly. This avoids\n * false-positive promotion of mid-sentence `## sharps`.\n */\n\nimport { $getRoot, $isParagraphNode, type ParagraphNode } from \"lexical\";\nimport { $isBlockParagraphNode } from \"../core/nodes/BlockParagraphNode\";\n\nexport type BlockKind =\n | \"paragraph\"\n | \"heading-1\"\n | \"heading-2\"\n | \"heading-3\"\n | \"heading-4\"\n | \"heading-5\"\n | \"heading-6\"\n | \"quote\"\n | \"list-bullet\"\n | \"list-numbered\"\n | \"hr\"\n | \"code-fence-open\"\n | \"code-fence-close\"\n | \"code-line\";\n\nexport interface BlockInfo {\n kind: BlockKind;\n /** Length of the leading marker (e.g. `## ` = 3). 0 for paragraph / hr / code-line. */\n markerLen: number;\n /** For fence opens, the language tag if any (`mermaid`, `ts`, …). */\n lang?: string;\n}\n\nconst HEADING_RE = /^(#{1,6}) /;\nconst QUOTE_RE = /^> /;\nconst BULLET_RE = /^[-*+] /;\nconst NUMBERED_RE = /^\\d+\\. /;\nconst HR_RE = /^(?:---|\\*\\*\\*|___)\\s*$/;\n// Opener: three backticks, optional language tag, then anything (GFM\n// \"info string\" — we accept trailing comments etc).\nconst FENCE_OPEN_RE = /^```([A-Za-z0-9_-]*)(?:\\s.*)?$/;\n// Closer: three backticks with nothing meaningful after (strict so we don't\n// confuse a new fence opener with a close).\nconst FENCE_CLOSE_RE = /^```\\s*$/;\n\nconst PLAIN: BlockInfo = { kind: \"paragraph\", markerLen: 0 };\n\n/**\n * Resolve a BlockInfo from a hidden marker stashed on a `BlockParagraphNode`\n * (live mode). The marker contains the same chars that would have been in\n * the visible text in hybrid mode, so we can run them through the regular\n * detector instead of duplicating the lookup table.\n *\n * Returns `null` if the marker doesn't decode — caller falls back to\n * text-based detection.\n */\nfunction detectFromMarker(marker: string): BlockInfo | null {\n if (marker.length === 0) return null;\n // The marker is by definition a syntactically valid block prefix, so\n // dropping a sentinel char to feed the detector is safe. (E.g. `\"# \"` →\n // detect heading on `\"# x\"`.) Code fences are a special case because the\n // open-fence detector requires the whole line to match the regex; we\n // pass the marker as-is — `\"```ts\"` matches the FENCE_OPEN_RE.\n if (FENCE_OPEN_RE.test(marker)) {\n const m = marker.match(FENCE_OPEN_RE);\n return {\n kind: \"code-fence-open\",\n markerLen: 0,\n lang: (m && m[1]) || undefined,\n };\n }\n if (FENCE_CLOSE_RE.test(marker)) {\n return { kind: \"code-fence-close\", markerLen: 0 };\n }\n const probed = detectBlock(`${marker}x`, false);\n if (probed.kind === \"paragraph\") return null;\n // Live mode: marker chars are NOT in the visible text, so markerLen\n // should be reported as 0. The plugin keeps its own copy via the\n // stashed marker for serialization.\n return { ...probed, markerLen: 0 };\n}\n\nexport function detectBlock(text: string, insideCode: boolean): BlockInfo {\n // Inside a fenced block, only the closing fence escapes; everything else\n // is treated as a code line so its content is left untouched.\n if (insideCode) {\n if (FENCE_CLOSE_RE.test(text)) {\n return { kind: \"code-fence-close\", markerLen: 0 };\n }\n return { kind: \"code-line\", markerLen: 0 };\n }\n\n const openMatch = text.match(FENCE_OPEN_RE);\n if (openMatch) {\n return { kind: \"code-fence-open\", markerLen: 0, lang: openMatch[1] || undefined };\n }\n\n if (text.length === 0) return PLAIN;\n\n const h = text.match(HEADING_RE);\n if (h) {\n const level = h[1].length as 1 | 2 | 3 | 4 | 5 | 6;\n return { kind: (`heading-${level}` as BlockKind), markerLen: h[0].length };\n }\n\n if (QUOTE_RE.test(text)) {\n return { kind: \"quote\", markerLen: 2 };\n }\n\n if (BULLET_RE.test(text)) {\n return { kind: \"list-bullet\", markerLen: 2 };\n }\n\n const num = text.match(NUMBERED_RE);\n if (num) {\n return { kind: \"list-numbered\", markerLen: num[0].length };\n }\n\n if (HR_RE.test(text)) {\n return { kind: \"hr\", markerLen: 0 };\n }\n\n return PLAIN;\n}\n\n/**\n * Resolve a single paragraph's BlockInfo, taking into account both the\n * stashed marker (live mode) and the visible text (hybrid mode).\n * Code-line detection still requires knowing the running fence state, so\n * callers pass `insideCode` separately.\n */\nfunction $resolveBlockFor(\n paragraph: ParagraphNode,\n insideCode: boolean,\n): BlockInfo {\n if ($isBlockParagraphNode(paragraph) && paragraph.hasBlockMarker()) {\n const fromMarker = detectFromMarker(paragraph.getBlockMarker());\n if (fromMarker !== null) {\n // Inside a fence the stashed marker for the close line is also a\n // fence; we still honour the running state for correctness.\n if (insideCode && fromMarker.kind !== \"code-fence-close\") {\n return { kind: \"code-line\", markerLen: 0 };\n }\n return fromMarker;\n }\n }\n return detectBlock(paragraph.getTextContent(), insideCode);\n}\n\n/** Map paragraph NodeKey → resolved BlockInfo, computed in document order\n * so fence parity is honoured across siblings. Run inside an editor read. */\nexport function $computeBlockMap(): Map<string, BlockInfo> {\n const map = new Map<string, BlockInfo>();\n const root = $getRoot();\n let insideCode = false;\n\n for (const child of root.getChildren()) {\n if (!$isParagraphNode(child)) continue;\n const info = $resolveBlockFor(child, insideCode);\n map.set(child.getKey(), info);\n if (info.kind === \"code-fence-open\") insideCode = true;\n else if (info.kind === \"code-fence-close\") insideCode = false;\n }\n return map;\n}\n\n/** Cheap point-lookup: is this specific paragraph inside an open code fence? */\nexport function $isParagraphInsideCodeFence(paragraph: ParagraphNode): boolean {\n const root = paragraph.getParent();\n if (!root) return false;\n\n let inside = false;\n for (const child of root.getChildren()) {\n if (child === paragraph) return inside;\n if (!$isParagraphNode(child)) continue;\n // Honour both stashed markers (live mode) and visible markers (hybrid).\n if ($isBlockParagraphNode(child) && child.hasBlockMarker()) {\n const marker = child.getBlockMarker();\n if (inside) {\n if (FENCE_CLOSE_RE.test(marker)) inside = false;\n } else {\n if (FENCE_OPEN_RE.test(marker)) inside = true;\n }\n continue;\n }\n const text = child.getTextContent();\n if (inside) {\n if (FENCE_CLOSE_RE.test(text)) inside = false;\n } else {\n if (FENCE_OPEN_RE.test(text)) inside = true;\n }\n }\n return inside;\n}\n\n/** Returns the BlockInfo for a single paragraph in context (walks earlier\n * siblings to determine fence parity). */\nexport function $detectBlockFor(paragraph: ParagraphNode): BlockInfo {\n const inside = $isParagraphInsideCodeFence(paragraph);\n return $resolveBlockFor(paragraph, inside);\n}","import {\n $getRoot,\n $isElementNode,\n $isLineBreakNode,\n $isParagraphNode,\n $isTextNode,\n type LexicalEditor,\n type LexicalNode,\n} from \"lexical\";\nimport type { MentionRef } from \"../types\";\nimport { $isMentionNode } from \"./nodes/MentionNode\";\nimport { $isMarkdownTokenNode } from \"./nodes/MarkdownTokenNode\";\nimport { $isBlockParagraphNode } from \"./nodes/BlockParagraphNode\";\nimport { $isLinkTextNode } from \"./nodes/LinkTextNode\";\nimport { detectBlock, type BlockKind } from \"../plugins/markdown-blocks\";\n\n/**\n * Walks the editor tree and produces:\n * - text: plain text (chips collapse to `@label`, markdown tokens dropped).\n * - mentions: discovered MentionNodes in document order.\n *\n * \"Plain text\" means what the user *intended* to write — markers like `**`\n * around `bold` are stripped, leaving just `bold`.\n */\nexport function collectPlainAndMentions(editor: LexicalEditor): {\n text: string;\n mentions: MentionRef[];\n} {\n return editor.getEditorState().read(() => {\n const root = $getRoot();\n const mentions: MentionRef[] = [];\n\n const walkInline = (parent: LexicalNode): string => {\n if (!$isElementNode(parent)) return \"\";\n let out = \"\";\n for (const child of parent.getChildren()) {\n if ($isMentionNode(child)) {\n // Label reflects any edits the user made (e.g. backspacing\n // \"John Doe\" down to \"John\"). The id is the stable handle\n // assigned when the chip was first inserted.\n const label = child.getMentionLabel();\n mentions.push({\n id: child.getMentionId(),\n label,\n });\n out += `${child.getMentionPrefix()}${label}`;\n continue;\n }\n if ($isMarkdownTokenNode(child)) continue;\n if ($isLineBreakNode(child)) {\n out += \"\\n\";\n continue;\n }\n if ($isTextNode(child)) {\n out += child.getTextContent();\n continue;\n }\n if ($isElementNode(child)) {\n out += walkInline(child);\n }\n }\n return out;\n };\n\n const blocks: string[] = [];\n for (const child of root.getChildren()) {\n if ($isElementNode(child)) {\n blocks.push(walkInline(child));\n } else if ($isTextNode(child)) {\n blocks.push(child.getTextContent());\n }\n }\n\n return { text: blocks.join(\"\\n\").replace(/\\n+$/g, \"\"), mentions };\n });\n}\n\n/**\n * Lexical format-flag bits we care about for serialization. Mirrors\n * `FORMAT_FLAGS` in MarkdownPlugin so the two stay in lockstep — if you\n * touch one, touch the other.\n */\nconst FORMAT_BIT = {\n bold: 1,\n italic: 2,\n strike: 4,\n // underline (8) — no widely-supported markdown syntax; we drop it on\n // serialize rather than invent one.\n code: 16,\n} as const;\n\n/**\n * Wrap text with markdown markers based on its Lexical format flags. Used\n * by the serializer when running against a `live`-mode document where the\n * markers were stripped out of the editor source and need to be\n * reconstructed at submit time.\n *\n * In `hybrid` mode the markers are already in the document text (carried\n * by `MarkdownTokenNode`s), so this helper isn't called.\n *\n * Order matters: code wraps innermost (backticks shouldn't be confused\n * with surrounding bold/italic), then bold (`**`), italic (`*`), strike\n * (`~~`). Combining bold + italic produces `***text***` — CommonMark\n * accepts it; renderers that don't fall back to plain bold which is fine.\n */\nfunction wrapByFormat(text: string, format: number): string {\n if (!text) return text;\n let out = text;\n if (format & FORMAT_BIT.code) out = `\\`${out}\\``;\n if (format & FORMAT_BIT.bold) out = `**${out}**`;\n if (format & FORMAT_BIT.italic) out = `*${out}*`;\n if (format & FORMAT_BIT.strike) out = `~~${out}~~`;\n return out;\n}\n\n/**\n * Serializes the editor to markdown.\n *\n * Two paths, picked by whether the document contains any\n * `MarkdownTokenNode` children (which only the `hybrid`-mode plugin\n * produces — so the presence of one is a reliable mode-detector that\n * doesn't require threading the mode through every call site):\n *\n * - HYBRID: the document text IS the markdown source. Markers from\n * `MarkdownTokenNode` + body from `TextNode` are concatenated\n * verbatim. No format-flag inspection needed.\n *\n * - LIVE: the document text is the *rendered* state — inline markers\n * were consumed by the plugin and only the Lexical format flag on\n * each TextNode remembers that \"foo\" was bold. We rebuild the\n * markers by wrapping each TextNode according to its format.\n *\n * Inter-paragraph separator: see {@link joinWithCommonMarkSpacing}.\n */\nexport function toMarkdown(editor: LexicalEditor): string {\n return editor.getEditorState().read(() => {\n const root = $getRoot();\n\n // Detect mode by content. A live-mode document never contains\n // MarkdownTokenNodes for inline markers; a hybrid-mode document\n // emits them on every formatted span. (Block markers still live as\n // tokens in both modes — see the comment in MarkdownPlugin — so\n // checking specifically for *inline* format-flag-bearing siblings\n // isn't necessary; presence of any non-leading token is enough.)\n let usingLive = true;\n const scan = (node: LexicalNode): void => {\n if ($isMarkdownTokenNode(node)) {\n const prev = node.getPreviousSibling();\n // Leading-token-of-paragraph = block marker; ignore. Any other\n // token is an inline marker → hybrid mode.\n if (prev !== null) usingLive = false;\n } else if ($isElementNode(node)) {\n for (const child of node.getChildren()) {\n if (!usingLive) return; // early-out\n scan(child);\n }\n }\n };\n for (const child of root.getChildren()) {\n if (!usingLive) break;\n scan(child);\n }\n\n const lines: string[] = [];\n\n const serializeParagraph = (paragraph: LexicalNode): string => {\n if (!$isElementNode(paragraph)) return \"\";\n let out = \"\";\n for (const child of paragraph.getChildren()) {\n if ($isMentionNode(child)) {\n out += `${child.getMentionPrefix()}${child.getMentionLabel()}`;\n continue;\n }\n if ($isLineBreakNode(child)) {\n out += \"\\n\";\n continue;\n }\n if ($isMarkdownTokenNode(child)) {\n // Tokens are markdown markers verbatim (hybrid mode), or block\n // markers (both modes). Either way, just emit the text.\n out += child.getTextContent();\n continue;\n }\n if ($isLinkTextNode(child)) {\n // Live-mode link node: visible label + stashed URL → `[label](url)`.\n // If the URL happens to be empty (shouldn't normally happen)\n // we fall back to the bare label so the user sees their text.\n const label = child.getTextContent();\n const url = child.getUrl();\n out += url ? `[${label}](${url})` : label;\n continue;\n }\n if ($isTextNode(child)) {\n const text = child.getTextContent();\n if (usingLive) {\n out += wrapByFormat(text, child.getFormat());\n } else {\n out += text;\n }\n continue;\n }\n if ($isElementNode(child)) {\n out += serializeParagraph(child);\n }\n }\n return out;\n };\n\n for (const child of root.getChildren()) {\n if ($isParagraphNode(child)) {\n const body = serializeParagraph(child);\n // Live-mode paragraphs may carry the block marker (`# `, ` ```ts `,\n // `> ` etc.) as a stashed prop on the BlockParagraphNode. Prepend\n // it here so the rendered markdown matches what the user typed\n // even though those chars never appeared in the editor's visible\n // text. Hybrid-mode paragraphs always have empty stash.\n if ($isBlockParagraphNode(child) && child.hasBlockMarker()) {\n lines.push(child.getBlockMarker() + body);\n } else {\n lines.push(body);\n }\n } else if ($isTextNode(child)) {\n lines.push(child.getTextContent());\n }\n }\n\n return joinWithCommonMarkSpacing(lines).trim();\n });\n}\n\n/**\n * Block kinds whose paragraphs continue across un-blanked following lines\n * in CommonMark (the \"lazy continuation\" rule). When one of these is\n * immediately followed by a plain paragraph in the editor, we must emit a\n * blank line in the markdown so the next paragraph doesn't get sucked\n * into the list item / block quote.\n */\nfunction isLazyContinuationBlock(kind: BlockKind): boolean {\n return kind === \"list-bullet\" || kind === \"list-numbered\" || kind === \"quote\";\n}\n\nfunction joinWithCommonMarkSpacing(lines: string[]): string {\n if (lines.length === 0) return \"\";\n\n // Walk the document in order so fence parity (we're inside a ``` block\n // or not) is computed correctly — block detection is fence-sensitive.\n let insideCode = false;\n const blocks = lines.map((line) => {\n const info = detectBlock(line, insideCode);\n if (info.kind === \"code-fence-open\") insideCode = true;\n else if (info.kind === \"code-fence-close\") insideCode = false;\n return info;\n });\n\n let out = lines[0];\n for (let i = 1; i < lines.length; i++) {\n const prev = blocks[i - 1];\n const next = blocks[i];\n const nextText = lines[i];\n\n // Only \"plain paragraph\" follow-ups trigger lazy continuation —\n // empty lines already produce a blank in the join, and other block\n // markers (`-`, `#`, `>`, fences, hr) terminate the list/quote on\n // their own and don't need an extra separator.\n const needsBlankSeparator =\n isLazyContinuationBlock(prev.kind) &&\n next.kind === \"paragraph\" &&\n nextText.length > 0;\n\n out += needsBlankSeparator ? \"\\n\\n\" : \"\\n\";\n out += nextText;\n }\n return out;\n}","import { useEffect } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $getRoot,\n $getSelection,\n $isParagraphNode,\n $isRangeSelection,\n COMMAND_PRIORITY_HIGH,\n KEY_ENTER_COMMAND,\n type ParagraphNode,\n type Point,\n} from \"lexical\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { $detectBlockFor, type BlockInfo } from \"./markdown-blocks\";\n\ninterface Props {\n onSubmit: () => void;\n}\n\n/**\n * Returns true when the cursor is positioned somewhere where Enter should\n * mean \"structural newline\" rather than \"submit the message\".\n *\n * In Slack-style markdown, every block is a styled paragraph and Enter is\n * the user's natural submit affordance — so we only defer in one place:\n * inside (or on the opener of) a fenced code block, where pressing Enter\n * is overwhelmingly likely to mean \"add another code line\" not \"send\".\n * Everywhere else, Shift+Enter is the way to insert a soft line break.\n *\n * Run inside a `editor.getEditorState().read(...)` callback.\n */\nfunction $isInsideCodeFence(): boolean {\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return false;\n\n const anchorNode = selection.anchor.getNode();\n const top = anchorNode.getTopLevelElement();\n if (!top || !$isParagraphNode(top)) return false;\n\n const block = $detectBlockFor(top);\n return block.kind === \"code-line\" || block.kind === \"code-fence-open\";\n}\n\n/**\n * Whether the editor currently holds more than one line of content —\n * either multiple top-level paragraphs or a single paragraph with one\n * or more soft line breaks. Used by the smart-newline behavior to\n * decide whether plain Enter should submit or insert a line break.\n *\n * Run inside a `editor.getEditorState().read(...)` callback.\n */\nfunction $hasMultiLineContent(): boolean {\n const root = $getRoot();\n if (root.getChildrenSize() > 1) return true;\n return root.getTextContent().includes(\"\\n\");\n}\n\n/**\n * Plain-text offset of `point` measured from the start of `paragraph`.\n * Walks children in order so the result is comparable against\n * `BlockInfo.markerLen` (which is expressed in plain-text characters).\n *\n * Run inside an editor read or update.\n */\nfunction $offsetWithinParagraph(paragraph: ParagraphNode, point: Point): number {\n if (point.type === \"element\") {\n const children = paragraph.getChildren();\n let offset = 0;\n const limit = Math.min(point.offset, children.length);\n for (let i = 0; i < limit; i++) {\n offset += children[i].getTextContentSize();\n }\n return offset;\n }\n const anchorKey = point.getNode().getKey();\n let offset = 0;\n for (const child of paragraph.getChildren()) {\n if (child.getKey() === anchorKey) return offset + point.offset;\n offset += child.getTextContentSize();\n }\n return offset + point.offset;\n}\n\n/**\n * Smart list-continuation. When the cursor sits inside a markdown bullet\n * (`- `, `* `, `+ `) or numbered (`N. `) paragraph and the user presses\n * Enter, we either:\n *\n * - Exit the list — when the current item is empty (only the marker),\n * the marker is cleared in place so the user lands in a plain\n * paragraph ready for regular prose.\n * - Continue the list — split the paragraph at the cursor and seed\n * the new paragraph with the next marker. Bullet character is\n * preserved (`-`/`*`/`+`); numbered items auto-increment.\n *\n * Returns `true` when we handled the Enter and the caller should\n * `return true` from the command (skipping submit + Lexical's default).\n * Returns `false` to fall through to the regular Enter logic — used\n * when the cursor is in/before the marker itself, where splitting would\n * yield a confusing \"- - foo\" double-marker.\n *\n * Run inside an editor update.\n */\nfunction $handleListContinuation(): boolean {\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return false;\n if (!selection.isCollapsed()) return false;\n\n const anchorNode = selection.anchor.getNode();\n const top = anchorNode.getTopLevelElement();\n if (!top || !$isParagraphNode(top)) return false;\n\n const block: BlockInfo = $detectBlockFor(top);\n if (block.kind !== \"list-bullet\" && block.kind !== \"list-numbered\") {\n return false;\n }\n\n const text = top.getTextContent();\n const contentAfterMarker = text.slice(block.markerLen);\n const cursorOffset = $offsetWithinParagraph(top, selection.anchor);\n\n // Cursor in or before the marker — let Lexical do a vanilla split so\n // we don't accidentally produce \"- - foo\".\n if (cursorOffset < block.markerLen) return false;\n\n // Empty list item: exit the list by clearing the marker. The (now\n // empty) paragraph stays in place and the markdown plugin will\n // re-style it as plain on its next update tick.\n if (contentAfterMarker.length === 0) {\n top.clear();\n top.select(0, 0);\n return true;\n }\n\n // Continue the list. Bullet markers preserve their character (`-`,\n // `*`, `+`); numbered markers increment by one based on the current\n // line's number.\n let nextMarker: string;\n if (block.kind === \"list-bullet\") {\n const ch = text.charAt(0) || \"-\";\n nextMarker = `${ch} `;\n } else {\n const numMatch = text.match(/^(\\d+)/);\n const n = numMatch ? parseInt(numMatch[1], 10) + 1 : 2;\n nextMarker = `${n}. `;\n }\n\n selection.insertParagraph();\n const newSelection = $getSelection();\n if ($isRangeSelection(newSelection)) {\n newSelection.insertText(nextMarker);\n }\n return true;\n}\n\n/**\n * Handles Enter / Shift+Enter / Cmd|Ctrl+Enter with the rules described\n * by the `multiline`, `submitOnEnter`, and `smartNewline` props on\n * `<Composer />`. The behavior matrix, with all three defaulting to\n * `true`:\n *\n * - Cmd/Ctrl+Enter: always submit (when `submitOnEnter` is on or the\n * editor is configured to never submit on Enter — the modifier is\n * the universal \"force send\" gesture).\n * - Shift+Enter: insert a hard paragraph break (NOT a soft\n * `LineBreakNode`) so the markdown plugin can tokenize each line\n * independently. Swallowed when `multiline` is false.\n * - Inside an open code fence: defer to Lexical so Enter splits the\n * paragraph into a new code line — unless `multiline` is false.\n * - Plain Enter, `multiline` false: submit when `submitOnEnter`, else\n * swallow (single-line input with no submit affordance).\n * - Plain Enter, `multiline` true, `smartNewline` true: insert a\n * newline once the editor already holds more than one line;\n * otherwise submit (when `submitOnEnter`). When the cursor sits in\n * a markdown list paragraph (`- `, `* `, `+ `, `N. `) the list is\n * continued instead (next marker auto-inserted, double-Enter exits)\n * — this fires before any submit decision so a single bullet line\n * can be extended without an accidental send.\n * - Plain Enter, `multiline` true, `smartNewline` false: submit when\n * `submitOnEnter`, else insert a newline (Lexical default). List\n * continuation is intentionally off in this mode.\n *\n * Slash/mention menus still get first refusal via the\n * `data-composer-popover=\"open\"` marker.\n */\nexport function KeyboardPlugin({ onSubmit }: Props) {\n const [editor] = useLexicalComposerContext();\n const {\n triggerSubmit,\n multiline,\n submitOnEnter,\n smartNewline,\n mode,\n } = useComposerContext();\n\n useEffect(() => {\n const trySubmit = (event: KeyboardEvent) => {\n event.preventDefault();\n triggerSubmit();\n onSubmit();\n return true;\n };\n\n return editor.registerCommand(\n KEY_ENTER_COMMAND,\n (event) => {\n if (!event) return false;\n\n // If a typeahead popover (slash, mentions) is open, yield to its\n // own KEY_ENTER_COMMAND handler at COMMAND_PRIORITY_LOW so the\n // highlighted option is selected. We MUST NOT call\n // event.preventDefault() or return true here — both would steal\n // the keystroke before the typeahead ever sees it.\n if (document.querySelector('[data-composer-popover=\"open\"]')) {\n return false;\n }\n\n const isModEnter = event.metaKey || event.ctrlKey;\n const isShiftEnter = event.shiftKey;\n\n // Cmd/Ctrl+Enter is the universal \"force submit\" gesture — it\n // always wins regardless of the other props.\n if (isModEnter) return trySubmit(event);\n\n // Shift+Enter: insert a new paragraph, NOT a soft-break\n // `LineBreakNode`. The Slack-style markdown stack\n // (`markdown-blocks.ts`, `MarkdownPlugin`, `serializer.ts`,\n // `insertText.ts`) operates strictly per-paragraph — block kind\n // (heading, list, quote, code-fence, …) is detected from the\n // paragraph's text, styling is applied per `<p>` via\n // `data-md-block`, and CSS for headings uses `::first-line`.\n // A `LineBreakNode` inside a paragraph would leave any line\n // after the break untokenized in the editor (e.g. `# foo`\n // styled as a heading, the `# bar` line after Shift+Enter\n // unstyled) even though the serialized markdown still produces\n // two real headings — so the editor view silently disagrees\n // with the rendered bubble. Treating Shift+Enter as a hard\n // paragraph break (the same gesture Slack, Discord, ChatGPT\n // and Claude all use) restores per-line consistency and\n // matches how pasted/initial multi-line text is already\n // ingested by this composer.\n if (isShiftEnter) {\n if (!multiline) {\n event.preventDefault();\n return true;\n }\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return false;\n selection.insertParagraph();\n event.preventDefault();\n return true;\n }\n\n // Inside a fenced code block we always want a new code line,\n // unless multi-line content is disallowed entirely.\n let inCodeFence = false;\n let hasMultiLine = false;\n editor.getEditorState().read(() => {\n inCodeFence = $isInsideCodeFence();\n hasMultiLine = $hasMultiLineContent();\n });\n if (inCodeFence) {\n if (!multiline) {\n event.preventDefault();\n return true;\n }\n return false;\n }\n\n // Single-line composer: Enter submits or is a no-op.\n if (!multiline) {\n if (!submitOnEnter) {\n event.preventDefault();\n return true;\n }\n return trySubmit(event);\n }\n\n // Smart list continuation: when typing a markdown bullet or\n // numbered item, Enter continues the list (auto-incrementing\n // numbers, preserving the bullet character) and Enter on an\n // empty item exits the list. Runs before the submit / smart\n // newline branches so a single-line bullet doesn't get sent\n // when the user clearly meant to add a second item.\n //\n // NB: we call `$handleListContinuation` directly, NOT via\n // `editor.update(...)`. Lexical dispatches KEY_ENTER_COMMAND\n // from inside its own `updateEditor` wrapper, so we're already\n // in a writable context. A nested `editor.update` would be\n // queued and run AFTER this command returns — by which point\n // we'd have already submitted, which is exactly the bug we're\n // trying to avoid.\n if (smartNewline && mode === \"markdown\") {\n if ($handleListContinuation()) {\n event.preventDefault();\n return true;\n }\n }\n\n // Smart newline: once the editor holds >1 line, plain Enter\n // adds a newline instead of submitting. Cmd/Ctrl+Enter (handled\n // above) is the way to send. This protects long drafts from\n // accidental submission.\n if (smartNewline && hasMultiLine) return false;\n\n if (!submitOnEnter) return false;\n\n return trySubmit(event);\n },\n COMMAND_PRIORITY_HIGH,\n );\n }, [\n editor,\n onSubmit,\n triggerSubmit,\n multiline,\n submitOnEnter,\n smartNewline,\n mode,\n ]);\n\n return null;\n}","import type { LexicalEditor } from \"lexical\";\n\n/**\n * Robustly focus a Lexical editor — used by `AutoFocusPlugin`, the\n * `focusShortcut` window handler, and the `refocusOnSubmit` branch.\n *\n * Why this isn't just `editor.focus()`:\n * A bare `editor.focus()` restores the Lexical *selection* and dispatches\n * the FOCUS_COMMAND, which is enough when the contenteditable already has\n * DOM focus (e.g. the user just pressed Enter to send — the editor was\n * the active element, so refocusing is a no-op-ish). It is NOT enough\n * when DOM focus lives elsewhere — body, a sidebar button, an\n * EmptyState description, etc. In that case the Lexical selection moves\n * but the browser never actually focuses the contenteditable, so the\n * visible caret never appears and keystrokes still hit whatever element\n * originally held focus.\n *\n * The fix mirrors `@lexical/react/LexicalAutoFocusPlugin`: pass a\n * callback into `editor.focus(cb, opts)` that, AFTER Lexical's own\n * focus attempt, manually `rootElement.focus({preventScroll: true})`\n * when the contenteditable still isn't part of `document.activeElement`.\n * `preventScroll` keeps the page from jumping when the composer sits\n * below the fold.\n *\n * `defaultSelection: \"rootEnd\"` lands the caret at the end of any seeded\n * `initialValue`, which is the natural \"ready to keep typing\" position\n * for a chat composer.\n */\nexport function focusEditor(editor: LexicalEditor): void {\n editor.focus(\n () => {\n const active = document.activeElement;\n const root = editor.getRootElement();\n if (root !== null && (active === null || !root.contains(active))) {\n root.focus({ preventScroll: true });\n }\n },\n { defaultSelection: \"rootEnd\" },\n );\n}","import { useEffect } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { focusEditor } from \"../internal/focusEditor\";\n\ninterface Props {\n enabled?: boolean;\n}\n\n/**\n * Lexical doesn't ship a plain `autoFocus` boolean, so we wrap\n * `editor.focus()` ourselves. See `internal/focusEditor.ts` for the full\n * story on why a bare `editor.focus()` isn't enough.\n *\n * Previously this plugin wrapped `editor.focus()` in a single\n * `requestAnimationFrame`, which raced with React's commit phase and\n * occasionally let the click-target keep focus instead.\n */\nexport function AutoFocusPlugin({ enabled }: Props) {\n const [editor] = useLexicalComposerContext();\n useEffect(() => {\n if (!enabled) return;\n focusEditor(editor);\n }, [editor, enabled]);\n return null;\n}","/**\n * PasteDropPlugin — intercepts clipboard paste and drag/drop on the editor.\n *\n * - Pasted images / files become attachment chips in the tray (Phase 2).\n * - Pasted plain text is split on `\\n` into one paragraph per line so the\n * markdown / mermaid block detectors can actually see fence boundaries\n * (the per-paragraph detectors can't recognise a ```mermaid block that\n * landed inside a single paragraph as line breaks).\n * - Drag-over shows a soft overlay so users know the target accepts files.\n *\n * Paste handling lives on `PASTE_COMMAND` (Lexical) rather than a native DOM\n * listener so we don't fight RichTextPlugin's own paste handler for\n * ordering. Drag/drop stays on native DOM events because they aren't\n * surfaced as Lexical commands.\n */\nimport { useEffect } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { COMMAND_PRIORITY_HIGH, PASTE_COMMAND } from \"lexical\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { $insertTextWithParagraphBreaks } from \"../internal/insertText\";\n\nexport function PasteDropPlugin() {\n const [editor] = useLexicalComposerContext();\n const { addFiles, features, multiline, setIsDraggingFiles } =\n useComposerContext();\n\n // ── Paste: files → attachments, text → paragraph-aware insertion ────\n useEffect(() => {\n return editor.registerCommand(\n PASTE_COMMAND,\n (event) => {\n if (!(event instanceof ClipboardEvent)) return false;\n const clipboard = event.clipboardData;\n if (!clipboard) return false;\n\n // 1. Files (only when attachments are enabled).\n if (features.attachments) {\n const files: File[] = [];\n for (const item of clipboard.items) {\n if (item.kind === \"file\") {\n const file = item.getAsFile();\n if (file) files.push(file);\n }\n }\n if (files.length > 0) {\n event.preventDefault();\n addFiles(files);\n return true;\n }\n }\n\n const text = clipboard.getData(\"text/plain\");\n if (!text) return false;\n\n // 2a. Inline / single-line mode — paragraph breaks are meaningless\n // here (the user can't even hit Enter), so flatten newlines to\n // spaces and let Lexical's default handler do the insert. If\n // the paste is already single-line we don't preventDefault and\n // just let the default path run.\n if (!multiline) {\n if (!text.includes(\"\\n\") && !text.includes(\"\\r\")) return false;\n event.preventDefault();\n const flat = text.replace(/\\r\\n?|\\n/g, \" \").replace(/\\s+/g, \" \");\n editor.update(() => {\n $insertTextWithParagraphBreaks(flat);\n });\n return true;\n }\n\n // 2b. Multi-line text — split on `\\n` so each line becomes its own\n // paragraph (required for fence / heading / list detection).\n // Single-line text falls through to Lexical's default handler\n // which already does the right thing.\n if (!text.includes(\"\\n\")) return false;\n event.preventDefault();\n editor.update(() => {\n $insertTextWithParagraphBreaks(text);\n });\n return true;\n },\n COMMAND_PRIORITY_HIGH,\n );\n }, [editor, features.attachments, multiline, addFiles]);\n\n // ── Drag / drop: native DOM events (no Lexical equivalent) ──────────\n useEffect(() => {\n if (!features.attachments) return;\n const root = editor.getRootElement();\n if (!root) return;\n\n let dragDepth = 0;\n const onDragEnter = (event: DragEvent) => {\n if (!event.dataTransfer?.types.includes(\"Files\")) return;\n dragDepth += 1;\n setIsDraggingFiles(true);\n };\n const onDragOver = (event: DragEvent) => {\n if (event.dataTransfer?.types.includes(\"Files\")) {\n event.preventDefault();\n if (event.dataTransfer) event.dataTransfer.dropEffect = \"copy\";\n }\n };\n const onDragLeave = (event: DragEvent) => {\n if (!event.dataTransfer?.types.includes(\"Files\")) return;\n dragDepth = Math.max(0, dragDepth - 1);\n if (dragDepth === 0) setIsDraggingFiles(false);\n };\n const onDrop = (event: DragEvent) => {\n dragDepth = 0;\n setIsDraggingFiles(false);\n const files = event.dataTransfer?.files;\n if (files && files.length > 0) {\n event.preventDefault();\n addFiles(Array.from(files));\n }\n };\n\n root.addEventListener(\"dragenter\", onDragEnter);\n root.addEventListener(\"dragover\", onDragOver);\n root.addEventListener(\"dragleave\", onDragLeave);\n root.addEventListener(\"drop\", onDrop);\n return () => {\n root.removeEventListener(\"dragenter\", onDragEnter);\n root.removeEventListener(\"dragover\", onDragOver);\n root.removeEventListener(\"dragleave\", onDragLeave);\n root.removeEventListener(\"drop\", onDrop);\n };\n }, [editor, addFiles, features.attachments, setIsDraggingFiles]);\n\n return null;\n}","/**\n * Inline-markdown tokenizer used by `MarkdownPlugin`. Produces a flat\n * stream of tokens — markers stay visible (rendered via MarkdownTokenNode)\n * while content carries the matching inline format.\n *\n * Supported inline marks:\n * **bold** __bold__\n * *italic* _italic_\n * ~~strike~~ ~strike~ — CommonMark *and* Slack syntax\n * `code`\n * [label](url) — link\n *  — image (alt text shown like a link)\n *\n * Notes:\n * - Markers are non-greedy and must not have whitespace immediately adjacent\n * to the inner text (matches CommonMark behaviour).\n * - Nested marks are not supported in this first iteration — the outermost\n * match wins and the inner content is treated as plain text.\n * - Newlines never appear inside a single inline mark.\n * - Link / image URLs are rendered as styled (not muted) text and produce\n * an additional `link` format on the URL itself for theming.\n */\n\nexport type InlineFormat =\n | \"bold\"\n | \"italic\"\n | \"underline\"\n | \"code\"\n | \"strike\"\n | \"link\";\n\nexport type Token =\n | { type: \"text\"; text: string }\n | { type: \"marker\"; text: string; format: InlineFormat }\n | { type: \"formatted\"; text: string; format: InlineFormat };\n\ninterface PairedPattern {\n open: string;\n close: string;\n format: InlineFormat;\n}\n\n// Order matters: longer markers must be tried first so `**` is not eaten by `*`,\n// and `~~` is not eaten by single-tilde Slack-style strike.\nconst PAIRED_PATTERNS: PairedPattern[] = [\n { open: \"**\", close: \"**\", format: \"bold\" },\n { open: \"__\", close: \"__\", format: \"bold\" },\n { open: \"~~\", close: \"~~\", format: \"strike\" },\n { open: \"`\", close: \"`\", format: \"code\" },\n { open: \"*\", close: \"*\", format: \"italic\" },\n { open: \"_\", close: \"_\", format: \"italic\" },\n { open: \"~\", close: \"~\", format: \"strike\" }, // Slack-style strike\n];\n\n// `[label](url)` or `` — captured by a single regex anchored at i.\nconst LINK_RE = /^(!?)\\[([^\\]\\n]+)\\]\\(([^)\\n\\s]+)\\)/;\n\nfunction isInvalidInner(inner: string): boolean {\n if (inner.length === 0) return true;\n if (/\\n/.test(inner)) return true;\n if (/^\\s|\\s$/.test(inner)) return true;\n return false;\n}\n\nexport function tokenize(text: string): Token[] {\n const tokens: Token[] = [];\n let i = 0;\n let buf = \"\";\n\n const flushBuf = () => {\n if (buf.length > 0) {\n tokens.push({ type: \"text\", text: buf });\n buf = \"\";\n }\n };\n\n while (i < text.length) {\n // 1) Link / image — matched first because `[` is not a paired marker.\n const ch = text[i];\n if (ch === \"[\" || (ch === \"!\" && text[i + 1] === \"[\")) {\n const m = text.slice(i).match(LINK_RE);\n if (m) {\n const [whole, bang, label, url] = m;\n flushBuf();\n if (bang) {\n tokens.push({ type: \"marker\", text: \"!\", format: \"link\" });\n }\n tokens.push({ type: \"marker\", text: \"[\", format: \"link\" });\n tokens.push({ type: \"formatted\", text: label, format: \"link\" });\n tokens.push({ type: \"marker\", text: \"](\", format: \"link\" });\n tokens.push({ type: \"formatted\", text: url, format: \"code\" });\n tokens.push({ type: \"marker\", text: \")\", format: \"link\" });\n i += whole.length;\n continue;\n }\n }\n\n // 2) Paired inline markers — bold / italic / strike / code.\n let matched = false;\n for (const pat of PAIRED_PATTERNS) {\n if (!text.startsWith(pat.open, i)) continue;\n const searchStart = i + pat.open.length;\n let endIdx = -1;\n let probe = searchStart;\n while (probe < text.length) {\n const candidate = text.indexOf(pat.close, probe);\n if (candidate === -1) break;\n // Reject doubled-marker false positives for single-char patterns.\n if (pat.open.length === 1) {\n const prev = text[candidate - 1];\n const next = text[candidate + 1];\n if (prev === pat.close || next === pat.close) {\n probe = candidate + 1;\n continue;\n }\n }\n endIdx = candidate;\n break;\n }\n if (endIdx === -1) continue;\n const inner = text.slice(searchStart, endIdx);\n if (isInvalidInner(inner)) continue;\n // Don't let single-char `*italic*` / `_italic_` / `~strike~` swallow\n // a half-typed double pair. We check BOTH sides of the open:\n //\n // text[i+1] === open → we're the first of a `**` opener that the\n // user is still typing (`**hello**`).\n // text[i-1] === open → we're the second of a `**` opener that\n // already exists; matching here would eat\n // half the bold marker.\n //\n // The second check matters especially in `live` mode: matching the\n // italic on `**test*` would consume the inner `*`s the moment the\n // 7th char is typed, leaving the closing 8th `*` orphaned — the\n // bold pair could then never form. In hybrid mode the markers stay\n // visible so the next keystroke recovers, but the visual flicker is\n // still unwanted. Both modes benefit from the symmetric guard.\n if (pat.open.length === 1) {\n if (text[i + 1] === pat.open[0]) continue;\n if (text[i - 1] === pat.open[0]) continue;\n }\n flushBuf();\n tokens.push({ type: \"marker\", text: pat.open, format: pat.format });\n tokens.push({ type: \"formatted\", text: inner, format: pat.format });\n tokens.push({ type: \"marker\", text: pat.close, format: pat.format });\n i = endIdx + pat.close.length;\n matched = true;\n break;\n }\n if (matched) continue;\n\n buf += text[i];\n i += 1;\n }\n flushBuf();\n return tokens;\n}\n\n/** Concatenated text length of a token. */\nexport function tokenLength(t: Token): number {\n return t.text.length;\n}","/**\n * Unified Slack-style markdown plugin.\n *\n * Two operating modes, picked via `features.markdown.mode`:\n *\n * - **hybrid** (default): ALL markdown markers stay visible AND apply\n * visual styling. The paragraph's text content IS the markdown source.\n * Nothing is converted to a different Lexical node.\n *\n * - **live**: Notion-style. Markers vanish once matched; the format\n * flags / stashed marker / LinkTextNode become the source of truth.\n * The serializer reconstructs the markdown on submit.\n *\n * Responsibilities (all rolled into one plugin so the rules stay consistent):\n *\n * 1. Inline tokenization\n * `**bold**`, `*italic*`, `_italic_`, `~~strike~~`, `` `code` ``,\n * `[label](url)`, ``. Hybrid: markers rendered as muted\n * `MarkdownTokenNode`s, body picks up format flags. Live: markers\n * dropped from the visible text; format flags / LinkTextNode hold\n * the state needed to rebuild the source.\n *\n * 2. Block-marker tokenization (leading marker of the paragraph)\n * `# `, `> `, `- `, `1. `, ```` ``` ``` `` — hybrid mode emits a\n * muted token; live mode stashes the marker on the\n * `BlockParagraphNode` (via `__blockMarker`) and drops the visible\n * chars so the user sees only the heading / quote / list body.\n *\n * 3. Block styling via DOM attribute\n * Each paragraph DOM element receives `data-md-block=\"<kind>\"` (e.g.\n * `heading-2`, `code-line`, `quote`). CSS does the actual visual work\n * (font sizes, indentation, monospace, left border, etc.). In live\n * mode the kind is resolved from the stashed marker, so styling\n * survives the marker chars being hidden.\n *\n * 4. Backspace-at-start escape (live mode only)\n * Backspace pressed at column 0 of a paragraph with a stashed block\n * marker clears the marker instead of merging up — the only way to\n * remove a heading style when the `# ` chars aren't visible.\n *\n * Re-entrancy: a single tagged `editor.update` is scheduled per real user\n * change and re-styles every paragraph idempotently. This catches \"context\"\n * changes (typing ```` ``` ```` shifts every paragraph below into a code\n * block) without per-paragraph propagation gymnastics.\n */\n\nimport { useEffect, useRef } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $createParagraphNode,\n $createTextNode,\n $getRoot,\n $getSelection,\n $isParagraphNode,\n $isRangeSelection,\n $isTextNode,\n COMMAND_PRIORITY_LOW,\n KEY_BACKSPACE_COMMAND,\n type ParagraphNode,\n} from \"lexical\";\nimport {\n $createMarkdownTokenNode,\n $isMarkdownTokenNode,\n} from \"../core/nodes/MarkdownTokenNode\";\nimport {\n $isBlockParagraphNode,\n type BlockParagraphNode,\n} from \"../core/nodes/BlockParagraphNode\";\nimport {\n $createLinkTextNode,\n $isLinkTextNode,\n} from \"../core/nodes/LinkTextNode\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { MarkdownMode } from \"../types\";\nimport { tokenize, type InlineFormat, type Token } from \"./markdown-tokenizer\";\nimport {\n $computeBlockMap,\n $detectBlockFor,\n type BlockInfo,\n type BlockKind,\n} from \"./markdown-blocks\";\n\n// Lexical format flag bits — using `code` for inline code and reusing it for\n// link URLs so they render with a monospace tint. `link` doesn't map to a\n// native Lexical bit; we surface it via the token coloring instead.\nconst FORMAT_FLAGS: Record<InlineFormat, number> = {\n bold: 1,\n italic: 2,\n strike: 4,\n underline: 8,\n code: 16,\n link: 0,\n};\n\ninterface DesiredNode {\n kind: \"text\" | \"token\" | \"link\";\n text: string;\n format: number;\n /** Populated for `link` kind only — the URL to stash on the LinkTextNode. */\n url?: string;\n}\n\nfunction readCurrentChildren(paragraph: ParagraphNode): DesiredNode[] | null {\n const out: DesiredNode[] = [];\n for (const child of paragraph.getChildren()) {\n // LinkTextNode is also a TextNode subclass — check it BEFORE the\n // generic text branch so its URL gets surfaced in the diff.\n if ($isLinkTextNode(child)) {\n out.push({\n kind: \"link\",\n text: child.getTextContent(),\n format: child.getFormat(),\n url: child.getUrl(),\n });\n } else if ($isMarkdownTokenNode(child)) {\n out.push({ kind: \"token\", text: child.getTextContent(), format: 0 });\n } else if ($isTextNode(child)) {\n out.push({\n kind: \"text\",\n text: child.getTextContent(),\n format: child.getFormat(),\n });\n } else {\n // Mentions / other inlines — bail out so we don't disturb them.\n return null;\n }\n }\n return out;\n}\n\nfunction nodesEqual(a: DesiredNode[], b: DesiredNode[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n const ai = a[i];\n const bi = b[i];\n // `text` and `link` are interchangeable for equality purposes: on a\n // subsequent pass the tokenizer no longer sees the URL (it's hidden\n // on the LinkTextNode) and emits a plain text token. Treating them\n // as equal here prevents a wasteful rewrite that would discard the\n // URL. The writer preserves the LinkTextNode in this case.\n const aKind = ai.kind === \"link\" ? \"text\" : ai.kind;\n const bKind = bi.kind === \"link\" ? \"text\" : bi.kind;\n if (aKind !== bKind) return false;\n if (ai.text !== bi.text) return false;\n if (ai.format !== bi.format) return false;\n }\n return true;\n}\n\nfunction getSelectionOffsetWithin(\n paragraph: ParagraphNode,\n): { anchor: number; focus: number } | null {\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return null;\n\n const measure = (key: string, offset: number): number | null => {\n let acc = 0;\n for (const child of paragraph.getChildren()) {\n if (child.getKey() === key) return acc + offset;\n acc += child.getTextContentSize();\n }\n return null;\n };\n\n const measureNodeOffset = (key: string, offset: number): number | null => {\n if (paragraph.getKey() === key) {\n let acc = 0;\n const children = paragraph.getChildren();\n for (let i = 0; i < Math.min(offset, children.length); i++) {\n acc += children[i].getTextContentSize();\n }\n return acc;\n }\n return measure(key, offset);\n };\n\n const a = measureNodeOffset(selection.anchor.key, selection.anchor.offset);\n const f = measureNodeOffset(selection.focus.key, selection.focus.offset);\n if (a === null || f === null) return null;\n return { anchor: a, focus: f };\n}\n\nfunction setSelectionFromOffsets(\n paragraph: ParagraphNode,\n offsets: { anchor: number; focus: number },\n): void {\n type Point = { key: string; offset: number; type: \"text\" | \"element\" };\n const locate = (target: number): Point | null => {\n const children = paragraph.getChildren();\n if (children.length === 0) {\n // Empty paragraph (e.g. a live-mode heading where the user hasn't\n // typed a body yet, or a hidden code-fence line) — Lexical\n // represents the caret as an element-type point.\n return { key: paragraph.getKey(), offset: 0, type: \"element\" };\n }\n let acc = 0;\n for (const child of children) {\n const size = child.getTextContentSize();\n if (target <= acc + size) {\n return {\n key: child.getKey(),\n offset: Math.max(0, target - acc),\n type: \"text\",\n };\n }\n acc += size;\n }\n const last = children[children.length - 1];\n return {\n key: last.getKey(),\n offset: last.getTextContentSize(),\n type: \"text\",\n };\n };\n\n const a = locate(offsets.anchor);\n const f = locate(offsets.focus);\n if (!a || !f) return;\n const selection = $getSelection();\n if (!$isRangeSelection(selection)) return;\n selection.anchor.set(a.key, a.offset, a.type);\n selection.focus.set(f.key, f.offset, f.type);\n}\n\nfunction isCodeKind(kind: BlockKind): boolean {\n return (\n kind === \"code-line\" ||\n kind === \"code-fence-open\" ||\n kind === \"code-fence-close\"\n );\n}\n\n/**\n * Walk the paragraph's existing children and produce a per-character map of\n * the format flags currently in effect. Used by live-mode `$applyStyling`\n * so plain-text tokens (i.e. text the new tokenizer pass doesn't claim\n * with a marker) keep whatever format they had before — without this we'd\n * lose every previously-applied format on the very next keystroke (the\n * paragraph text no longer contains `**` markers, so the tokenizer just\n * sees plain text and would otherwise reset the format to 0).\n *\n * MarkdownTokenNodes (block-marker leaders) are counted as format=0 even\n * though they're TextNode subclasses; that matches what `$applyStyling`\n * emits for the block prefix in live mode.\n */\nfunction buildCurrentFormatMap(paragraph: ParagraphNode): number[] {\n const out: number[] = [];\n for (const child of paragraph.getChildren()) {\n if (!$isTextNode(child)) continue;\n const text = child.getTextContent();\n const fmt = $isMarkdownTokenNode(child) ? 0 : child.getFormat();\n for (let i = 0; i < text.length; i++) out.push(fmt);\n }\n return out;\n}\n\n/**\n * Build a function that maps a SOURCE-text offset (the paragraph before the\n * rewrite, which still contains every character the user typed) to a TARGET\n * offset (the paragraph after the rewrite, where in `live` mode the inline\n * marker characters have been dropped).\n *\n * In `hybrid` mode the mapping is the identity, so we skip this work\n * entirely and let the caller pass source offsets straight through.\n *\n * In `live` mode only INLINE markers are dropped — block markers stay\n * visible (see `$applyStyling`). So the prefix-sum starts by keeping the\n * leading block-marker chars 1:1 and only marks inline `marker` tokens as\n * dropped. The caret then lands at the end of the visible content — the\n * same place it would have been if the inline markers had been invisible\n * all along.\n */\n/**\n * For each inline token, decide whether its chars stay visible (`true`) or\n * are dropped (`false`) in `live` mode. Markers are always dropped. Most\n * `formatted` tokens are kept. Link sequences are a special case: the\n * label stays visible, the URL is dropped (it's stashed on a LinkTextNode\n * by the desired-children pass).\n */\nfunction buildKeptMask(tokens: Token[]): boolean[] {\n const mask = new Array<boolean>(tokens.length);\n for (let i = 0; i < tokens.length; i++) {\n mask[i] = tokens[i].type !== \"marker\";\n }\n // Walk again to look for link sequences and flip the URL token off.\n // Mirrors the detection in `$applyStyling`'s token loop — keep these\n // in sync.\n for (let i = 0; i < tokens.length; i++) {\n const t = tokens[i];\n if (t.type !== \"marker\") continue;\n if (t.text !== \"[\" && t.text !== \"!\") continue;\n const offset = t.text === \"!\" ? 1 : 0;\n const open = tokens[i + offset];\n const label = tokens[i + offset + 1];\n const mid = tokens[i + offset + 2];\n const url = tokens[i + offset + 3];\n const close = tokens[i + offset + 4];\n if (\n open?.type === \"marker\" &&\n open.text === \"[\" &&\n label?.type === \"formatted\" &&\n label.format === \"link\" &&\n mid?.type === \"marker\" &&\n mid.text === \"](\" &&\n url?.type === \"formatted\" &&\n close?.type === \"marker\" &&\n close.text === \")\"\n ) {\n mask[i + offset + 3] = false; // URL — dropped\n }\n }\n return mask;\n}\n\nfunction buildLiveOffsetMap(\n text: string,\n leadingDrop: number,\n tokens: Token[] | null,\n trailingDrop: number = 0,\n): (srcOffset: number) => number {\n const kept = new Array<number>(text.length + 1);\n kept[0] = 0;\n let cursor = 0;\n // Leading block-marker chars that we just stashed on the paragraph in\n // live mode → dropped (mapped to target offset 0).\n for (let i = 0; i < leadingDrop && cursor < text.length; i++) {\n kept[cursor + 1] = kept[cursor];\n cursor++;\n }\n // Inline body — walk tokens in order. Drop / keep per `buildKeptMask`\n // so link-sequence collapsing (URL → dropped) matches the desired-\n // children pass. (HR / code-line / code-fence paragraphs pass `null`\n // for `tokens` because we don't tokenize inline markers inside them.)\n if (tokens) {\n const mask = buildKeptMask(tokens);\n for (let ti = 0; ti < tokens.length; ti++) {\n const t = tokens[ti];\n const isKept = mask[ti];\n for (let i = 0; i < t.text.length && cursor < text.length; i++) {\n kept[cursor + 1] = kept[cursor] + (isKept ? 1 : 0);\n cursor++;\n }\n }\n }\n // Any chars that aren't covered by leadingDrop or tokens — the trailing\n // run, normally kept verbatim. `trailingDrop` lets the caller mark the\n // last N source chars as dropped (used for code-fence close lines in\n // live mode, where the whole text becomes invisible).\n const trailDropStart = text.length - trailingDrop;\n for (; cursor < text.length; cursor++) {\n const dropped = cursor >= trailDropStart;\n kept[cursor + 1] = kept[cursor] + (dropped ? 0 : 1);\n }\n return (srcOffset: number) =>\n kept[Math.max(0, Math.min(srcOffset, text.length))];\n}\n\nfunction $applyStyling(\n paragraph: ParagraphNode,\n block: BlockInfo,\n mode: MarkdownMode,\n): boolean {\n const text = paragraph.getTextContent();\n\n const current = readCurrentChildren(paragraph);\n if (current === null) return false; // contains non-text inlines\n\n const desired: DesiredNode[] = [];\n const isLive = mode === \"live\";\n\n // Per-character format map of what's CURRENTLY in the paragraph, only\n // needed in live mode. Used so plain-text tokens (text the new\n // tokenizer pass doesn't claim with a marker pair) keep whatever\n // format they had before. Without this, typing any character after a\n // matched `**bold**` re-runs the plugin, the tokenizer sees no\n // markers, and we'd drop bold back to plain text — the regression\n // that triggered this code path.\n const currentFmt = isLive ? buildCurrentFormatMap(paragraph) : null;\n\n // ─── Block marker handling ──────────────────────────────────────────────\n //\n // Hybrid mode: keep the marker chars in the visible text, emit them as a\n // muted MarkdownTokenNode. The user sees `# Heading` with `# ` greyed\n // out, the text content is the markdown source verbatim.\n //\n // Live mode: hide the marker entirely. We stash the marker string on the\n // BlockParagraphNode so the serializer can rebuild `# Heading` on submit,\n // then drop the chars from the visible body.\n //\n // Also handles mode toggling:\n // live → hybrid: a paragraph with a stashed marker has it promoted\n // back to a visible token, and the caret shifts right\n // by markerLen so it stays on the same character.\n // hybrid → live: visible marker chars in the text get stashed and\n // sliced off; caret is mapped via buildLiveOffsetMap.\n const stashedNow =\n $isBlockParagraphNode(paragraph) ? paragraph.getBlockMarker() : \"\";\n let body = text;\n let stashedMarkerForOffsetMap = \"\"; // chars we just sliced off (live-mode pass)\n let hybridPromoteShift = 0; // chars we just put BACK (hybrid promote)\n if (block.markerLen > 0 && text.length >= block.markerLen) {\n const marker = text.slice(0, block.markerLen);\n if (isLive) {\n if (stashedNow !== marker && $isBlockParagraphNode(paragraph)) {\n paragraph.setBlockMarker(marker);\n }\n stashedMarkerForOffsetMap = marker;\n body = text.slice(marker.length);\n } else {\n desired.push({ kind: \"token\", text: marker, format: 0 });\n body = text.slice(marker.length);\n // Hybrid mode shouldn't carry a stale stash from a previous live run.\n if (stashedNow.length > 0 && $isBlockParagraphNode(paragraph)) {\n paragraph.setBlockMarker(\"\");\n }\n }\n } else if (!isLive && stashedNow.length > 0) {\n // Mode toggle: live → hybrid. Surface the hidden marker so the user\n // sees the raw markdown again. Clearing the stash here means\n // subsequent hybrid passes detect it from the (now visible) text.\n desired.push({ kind: \"token\", text: stashedNow, format: 0 });\n hybridPromoteShift = stashedNow.length;\n if ($isBlockParagraphNode(paragraph)) {\n paragraph.setBlockMarker(\"\");\n }\n }\n\n // Track absolute source position as we walk the inline tokens, so plain\n // text tokens can look up their existing format from `currentFmt`. In\n // hybrid mode the block marker contributes `markerLen` chars (the\n // visible muted token), in live-mode case (a) we've sliced them off so\n // srcPos starts at the same offset but the live offset map will\n // collapse them.\n let srcPos = block.markerLen;\n\n // We capture the inline-tokenizer result so the live-mode offset map can\n // see exactly which chars are markers. Code / HR paragraphs skip inline\n // tokenization (their content is rendered verbatim) so they pass null.\n let inlineTokens: Token[] | null = null;\n // Code-fence open/close lines in live mode: their whole text IS the\n // marker (`` ``` `` or ` ```lang `). Stash on the paragraph and drop the\n // visible body so the paragraph renders as an empty styled divider.\n // Tracked separately from `stashedMarkerForOffsetMap` because the source\n // chars here aren't a `markerLen` prefix — they're the entire body.\n let trailingDropForOffsetMap = 0;\n if (isCodeKind(block.kind)) {\n if (\n isLive &&\n (block.kind === \"code-fence-open\" || block.kind === \"code-fence-close\") &&\n body.length > 0 &&\n $isBlockParagraphNode(paragraph)\n ) {\n // The fence line. Stash it and emit nothing; CSS handles the visual.\n if (paragraph.getBlockMarker() !== body) {\n paragraph.setBlockMarker(body);\n }\n trailingDropForOffsetMap = body.length;\n body = \"\";\n } else if (body.length > 0) {\n // Hybrid mode, or code-line content — render verbatim.\n desired.push({ kind: \"text\", text: body, format: 0 });\n }\n } else if (block.kind === \"hr\") {\n // HR is a special case: in hybrid mode the whole line is a token so\n // CSS can paint a rule across it. In live mode we collapse it the\n // same way so the user can still see / edit / delete the `---` they\n // typed — a fully-invisible HR would be undeletable without remembering\n // it's there. (Real Notion-style HRs would need a DecoratorNode, which\n // is more work than this flag merits for v1.)\n if (body.length > 0) {\n desired.push({ kind: \"token\", text: body, format: 0 });\n }\n } else {\n inlineTokens = tokenize(body);\n for (let ti = 0; ti < inlineTokens.length; ti++) {\n const t = inlineTokens[ti];\n const tokenLen = t.text.length;\n\n // ─── Link sequence (live mode collapse) ────────────────────────────\n // Tokens for `[label](url)` come as: marker `[`, formatted label,\n // marker `](`, formatted url (in code format), marker `)`. Image\n // links additionally start with a marker `!`. In live mode we\n // collapse the whole sequence into a single LinkTextNode that\n // shows the label and remembers the URL — the markers + URL\n // vanish from the visible text. Hybrid mode falls through to the\n // regular per-token rendering below.\n if (\n isLive &&\n t.type === \"marker\" &&\n (t.text === \"[\" || t.text === \"!\") &&\n ti + 4 < inlineTokens.length\n ) {\n const offset = t.text === \"!\" ? 1 : 0; // skip the bang for images\n const open = inlineTokens[ti + offset];\n const label = inlineTokens[ti + offset + 1];\n const mid = inlineTokens[ti + offset + 2];\n const url = inlineTokens[ti + offset + 3];\n const close = inlineTokens[ti + offset + 4];\n if (\n open?.type === \"marker\" &&\n open.text === \"[\" &&\n label?.type === \"formatted\" &&\n label.format === \"link\" &&\n mid?.type === \"marker\" &&\n mid.text === \"](\" &&\n url?.type === \"formatted\" &&\n close?.type === \"marker\" &&\n close.text === \")\"\n ) {\n desired.push({\n kind: \"link\",\n text: label.text,\n format: 0,\n url: url.text,\n });\n // Advance srcPos past every consumed token (including the\n // optional leading `!`) so the format map / offset map stay\n // in lockstep with the source text.\n srcPos += t.text.length;\n if (offset === 1) {\n // Already counted the `!` above; advance past the rest.\n srcPos +=\n open.text.length +\n label.text.length +\n mid.text.length +\n url.text.length +\n close.text.length;\n ti += 5;\n } else {\n srcPos +=\n label.text.length +\n mid.text.length +\n url.text.length +\n close.text.length;\n ti += 4;\n }\n continue;\n }\n }\n\n if (t.type === \"marker\") {\n if (!isLive) {\n desired.push({ kind: \"token\", text: t.text, format: 0 });\n }\n // live mode → drop the marker chars from the output\n } else if (t.type === \"formatted\") {\n // Fresh marker pair in the source text — use its format. We\n // deliberately don't OR in the existing format here: the\n // pre-existing chars under this token (in live mode) had a\n // format inherited from typing context, and the user's\n // intent when wrapping with markers is to *set* the new\n // format, not combine it.\n desired.push({\n kind: \"text\",\n text: t.text,\n format: FORMAT_FLAGS[t.format],\n });\n } else if (isLive && currentFmt) {\n // Plain text in live mode — preserve the existing per-char\n // format. Walk the source range, split into runs of equal\n // format so each run becomes its own DesiredNode (Lexical\n // merges them later if formats match adjacent nodes anyway).\n let runStart = 0;\n let runFmt = currentFmt[srcPos] ?? 0;\n for (let i = 1; i < tokenLen; i++) {\n const f = currentFmt[srcPos + i] ?? 0;\n if (f !== runFmt) {\n desired.push({\n kind: \"text\",\n text: t.text.slice(runStart, i),\n format: runFmt,\n });\n runStart = i;\n runFmt = f;\n }\n }\n desired.push({\n kind: \"text\",\n text: t.text.slice(runStart),\n format: runFmt,\n });\n } else {\n // Plain text in hybrid mode — format is always 0; the only way\n // text gets a format in hybrid is via a `formatted` token.\n desired.push({ kind: \"text\", text: t.text, format: 0 });\n }\n srcPos += tokenLen;\n }\n }\n\n if (nodesEqual(current, desired)) return false;\n\n // Snapshot URLs from any existing LinkTextNodes so a rewrite triggered\n // by an unrelated change (e.g. typing after a link) can re-attach them\n // to the rebuilt text nodes. Keyed by visible label — duplicates inside\n // the same paragraph fall back to the first match.\n const preservedLinkUrls = new Map<string, string>();\n for (const child of paragraph.getChildren()) {\n if ($isLinkTextNode(child)) {\n const label = child.getTextContent();\n const url = child.getUrl();\n if (label && url && !preservedLinkUrls.has(label)) {\n preservedLinkUrls.set(label, url);\n }\n }\n }\n\n const srcOffsets = getSelectionOffsetWithin(paragraph);\n for (const child of paragraph.getChildren()) child.remove();\n for (const node of desired) {\n if (node.kind === \"token\") {\n paragraph.append($createMarkdownTokenNode(node.text));\n } else if (node.kind === \"link\") {\n const t = $createLinkTextNode(node.text, node.url ?? \"\");\n if (node.format !== 0) t.setFormat(node.format);\n paragraph.append(t);\n } else {\n // Plain text — but if this label was previously a LinkTextNode, the\n // URL has only been \"hidden\" by the latest tokenizer pass; restore\n // it so the link survives unrelated paragraph edits.\n const preservedUrl = preservedLinkUrls.get(node.text);\n const t = preservedUrl\n ? $createLinkTextNode(node.text, preservedUrl)\n : $createTextNode(node.text);\n if (node.format !== 0) t.setFormat(node.format);\n paragraph.append(t);\n }\n }\n // Caret restoration:\n // live mode — prefix-sum offset map (we just dropped some chars).\n // hybrid mode — identity, except on a `live → hybrid` promotion where\n // we put `hybridPromoteShift` chars BACK at the start of\n // the paragraph and need to push the caret right.\n if (srcOffsets) {\n if (isLive) {\n const map = buildLiveOffsetMap(\n text,\n stashedMarkerForOffsetMap.length,\n inlineTokens,\n trailingDropForOffsetMap,\n );\n setSelectionFromOffsets(paragraph, {\n anchor: map(srcOffsets.anchor),\n focus: map(srcOffsets.focus),\n });\n } else {\n setSelectionFromOffsets(paragraph, {\n anchor: srcOffsets.anchor + hybridPromoteShift,\n focus: srcOffsets.focus + hybridPromoteShift,\n });\n }\n }\n return true;\n}\n\nfunction $restyleAllParagraphs(mode: MarkdownMode): void {\n const root = $getRoot();\n const map = $computeBlockMap();\n for (const child of root.getChildren()) {\n if (!$isParagraphNode(child)) continue;\n const info = map.get(child.getKey()) ?? $detectBlockFor(child);\n $applyStyling(child, info, mode);\n }\n}\n\n/**\n * UX nicety: when a paragraph transitions to `code-fence-close` and is the\n * last block in the document, append an empty paragraph after it and move\n * the caret there. This way typing ```` ``` ```` to close a code block also\n * \"exits\" the block — the user can immediately start typing the next message\n * line (or press Enter to submit). They can still arrow / click back into\n * the close-fence line to edit it.\n *\n * Triggered only on the *transition* into the close kind (tracked via\n * `prevKinds`) so navigating back to the line and re-entering it doesn't\n * keep appending paragraphs.\n */\nfunction $autoEscapeClosedFence(prevKinds: Map<string, BlockKind>): void {\n const map = $computeBlockMap();\n const root = $getRoot();\n\n for (const child of root.getChildren()) {\n if (!$isParagraphNode(child)) continue;\n const key = child.getKey();\n const info = map.get(key);\n if (!info) continue;\n const oldKind = prevKinds.get(key);\n if (\n info.kind === \"code-fence-close\" &&\n oldKind !== \"code-fence-close\" &&\n child.getNextSibling() === null\n ) {\n const next = $createParagraphNode();\n child.insertAfter(next);\n next.select();\n }\n }\n\n prevKinds.clear();\n for (const [k, v] of map) prevKinds.set(k, v.kind);\n}\n\nconst BLOCK_ATTR = \"data-md-block\";\nconst LANG_ATTR = \"data-md-lang\";\n\nfunction syncBlockAttributes(\n editor: ReturnType<typeof useLexicalComposerContext>[0],\n): void {\n editor.getEditorState().read(() => {\n const root = editor.getRootElement();\n if (!root) return;\n\n const seen = new Set<HTMLElement>();\n const map = $computeBlockMap();\n for (const [key, info] of map) {\n const el = editor.getElementByKey(key);\n if (!(el instanceof HTMLElement)) continue;\n seen.add(el);\n if (info.kind === \"paragraph\") {\n if (el.hasAttribute(BLOCK_ATTR)) el.removeAttribute(BLOCK_ATTR);\n } else {\n if (el.getAttribute(BLOCK_ATTR) !== info.kind) {\n el.setAttribute(BLOCK_ATTR, info.kind);\n }\n }\n // Language tag (code-fence-open only) — used by CSS to render a\n // small label since the visible `` ```ts `` chars are hidden in\n // live mode. Cleared for non-fence-open blocks so a paragraph that\n // *was* a fence and is now plain doesn't keep a stale label.\n if (info.kind === \"code-fence-open\" && info.lang) {\n if (el.getAttribute(LANG_ATTR) !== info.lang) {\n el.setAttribute(LANG_ATTR, info.lang);\n }\n } else if (el.hasAttribute(LANG_ATTR)) {\n el.removeAttribute(LANG_ATTR);\n }\n }\n\n // Strip the attribute from any paragraph the reconciler kept around but\n // that we no longer recognise (defensive — e.g. after delete).\n const stale = root.querySelectorAll<HTMLElement>(`[${BLOCK_ATTR}]`);\n stale.forEach((el) => {\n if (!seen.has(el)) {\n el.removeAttribute(BLOCK_ATTR);\n el.removeAttribute(LANG_ATTR);\n }\n });\n });\n}\n\nconst RESTYLE_TAG = \"md-restyle\";\n\nexport function MarkdownPlugin() {\n const [editor] = useLexicalComposerContext();\n const { markdownMode } = useComposerContext();\n const prevKindsRef = useRef<Map<string, BlockKind>>(new Map());\n // Ref-mirror so the long-lived update listener inside the effect always\n // sees the current mode without being torn down on every flag change.\n // (Effect itself depends on `markdownMode` too, so when it actually\n // changes we also re-run the initial restyle pass below.)\n const modeRef = useRef<MarkdownMode>(markdownMode);\n modeRef.current = markdownMode;\n\n useEffect(() => {\n const prevKinds = prevKindsRef.current;\n // Initial pass so any `initialValue` gets styled immediately, AND so\n // toggling between modes at runtime restyles the document end-to-end\n // (collapsing markers when switching to `live`, re-emitting them when\n // switching back to `hybrid`). We seed `prevKinds` with the\n // *post-style* state so the auto-escape doesn't fire on a fence the\n // user pre-loaded as initial content.\n editor.update(\n () => {\n $restyleAllParagraphs(modeRef.current);\n const map = $computeBlockMap();\n prevKinds.clear();\n for (const [k, v] of map) prevKinds.set(k, v.kind);\n },\n { tag: RESTYLE_TAG },\n );\n syncBlockAttributes(editor);\n\n let scheduled = false;\n\n const unregisterUpdate = editor.registerUpdateListener(\n ({ tags, dirtyElements, dirtyLeaves }) => {\n // DOM attributes are pure — sync after every render.\n syncBlockAttributes(editor);\n\n // Re-style content only when something actually changed and the\n // change wasn't our own restyle pass.\n if (tags.has(RESTYLE_TAG)) return;\n if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return;\n if (scheduled) return;\n scheduled = true;\n queueMicrotask(() => {\n scheduled = false;\n editor.update(\n () => {\n $restyleAllParagraphs(modeRef.current);\n $autoEscapeClosedFence(prevKinds);\n },\n { tag: RESTYLE_TAG },\n );\n });\n },\n );\n\n // Backspace at the start of a live-mode paragraph that carries a\n // stashed block marker → clear the marker instead of merging up. This\n // is the only way for the user to \"remove the heading style\" since\n // the `# ` chars aren't in the visible text anymore. Mirrors Notion's\n // behaviour: backspace at the start of a heading converts it to plain.\n const unregisterBackspace = editor.registerCommand(\n KEY_BACKSPACE_COMMAND,\n () => {\n if (modeRef.current !== \"live\") return false;\n const selection = $getSelection();\n if (!$isRangeSelection(selection) || !selection.isCollapsed()) {\n return false;\n }\n if (selection.anchor.offset !== 0) return false;\n\n const anchor = selection.anchor.getNode();\n const top = anchor.getTopLevelElement();\n if (!top || !$isParagraphNode(top)) return false;\n if (!$isBlockParagraphNode(top)) return false;\n if (!(top as BlockParagraphNode).hasBlockMarker()) return false;\n\n // Verify the cursor is at the very start of the visible body\n // (offset 0 in the first child, or element-type at the paragraph).\n if (selection.anchor.type === \"element\") {\n if (selection.anchor.getNode().getKey() !== top.getKey()) {\n return false;\n }\n } else {\n const first = top.getFirstChild();\n if (!first || first.getKey() !== anchor.getKey()) return false;\n }\n\n editor.update(() => {\n const latest = top.getLatest();\n if ($isBlockParagraphNode(latest)) {\n (latest as BlockParagraphNode).setBlockMarker(\"\");\n }\n });\n return true;\n },\n COMMAND_PRIORITY_LOW,\n );\n\n return () => {\n unregisterUpdate();\n unregisterBackspace();\n };\n }, [editor, markdownMode]);\n\n return null;\n}","import { useEffect, useState, type ReactNode } from \"react\";\nimport { createPortal } from \"react-dom\";\n\n/** Internal portal — used by ImageLightbox. Mounts after first effect. */\nexport function Portal({ children }: { children: ReactNode }) {\n const [mounted, setMounted] = useState(false);\n useEffect(() => {\n setMounted(true);\n }, []);\n if (!mounted) return null;\n return createPortal(children, document.body);\n}","import { useEffect } from \"react\";\nimport { Portal } from \"../internal/Portal\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n src: string;\n alt: string;\n onClose: () => void;\n}\n\nexport function ImageLightbox({ src, alt, onClose }: Props) {\n const { icons, tokenStyle } = useComposerContext();\n const { close: CloseIcon } = icons;\n useEffect(() => {\n const onKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\") onClose();\n };\n document.addEventListener(\"keydown\", onKey);\n const prev = document.body.style.overflow;\n document.body.style.overflow = \"hidden\";\n return () => {\n document.removeEventListener(\"keydown\", onKey);\n document.body.style.overflow = prev;\n };\n }, [onClose]);\n\n return (\n <Portal>\n <div\n role=\"dialog\"\n aria-modal=\"true\"\n data-composer-scope=\"\"\n className=\"composer-lightbox\"\n style={tokenStyle}\n >\n <div\n aria-hidden\n className=\"composer-lightbox-backdrop\"\n onClick={onClose}\n />\n <button\n type=\"button\"\n onClick={onClose}\n aria-label=\"Close\"\n className=\"composer-lightbox-close\"\n >\n <CloseIcon />\n </button>\n <img src={src} alt={alt} className=\"composer-lightbox-img\" />\n </div>\n </Portal>\n );\n}","/**\n * MermaidPlugin — detects ```mermaid code blocks inside the editor and shows\n * an inline preview row below the contenteditable surface.\n *\n * Rendering strategy (in priority order):\n * 1. If the consumer supplied a `renderDiagram` prop on <Composer />, every\n * detected diagram is delegated to that callback. The `mermaid` package\n * is never loaded, so consumers who already own a diagram pipeline can\n * omit `mermaid` from their install entirely.\n * 2. Otherwise, the optional `mermaid` peer package is dynamic-imported on\n * first sighting. If the import fails (package not installed), we log\n * one friendly warning and render a small \"install mermaid or pass\n * renderDiagram\" hint in place of the diagram.\n *\n * When `features.mermaid.keepSource === false`, the raw ```mermaid code\n * blocks are visually hidden from the editor (still present in the editor\n * state, so they survive serialization) — only the rendered diagram tiles\n * are shown. Default is `true` so the user keeps seeing the code they\n * authored alongside the live preview.\n */\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { $getRoot, $isParagraphNode } from \"lexical\";\nimport { ImageLightbox } from \"../ui/ImageLightbox\";\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { DiagramRenderer } from \"../types\";\n\ninterface DetectedDiagram {\n /** Stable id — paragraph key of the opening ```mermaid fence. */\n id: string;\n code: string;\n /** Keys of every paragraph that participates in this diagram (open fence,\n * code lines, optional close fence) so we can hide them in `!keepSource`. */\n paragraphKeys: string[];\n}\n\nconst FENCE_OPEN_MERMAID = /^```mermaid(?:\\s.*)?$/;\nconst FENCE_CLOSE = /^```\\s*$/;\n\n// Type-only — the actual module is loaded lazily and is optional.\ntype MermaidModule = {\n initialize: (config: Record<string, unknown>) => void;\n render: (id: string, code: string) => Promise<{ svg: string }>;\n};\n\nlet mermaidPromise: Promise<MermaidModule | null> | null = null;\nlet mermaidInitialized = false;\nlet mermaidMissingWarned = false;\n\nasync function loadMermaid(): Promise<MermaidModule | null> {\n if (!mermaidPromise) {\n // Static string + plain dynamic import so bundlers (Vite, Webpack,\n // Rollup, ...) can statically analyze the dependency and produce a\n // properly resolved code-split chunk. We still catch runtime errors so\n // a transient network failure (chunk 404, CDN hiccup) degrades to the\n // friendly fallback tile instead of throwing into React.\n //\n // If `mermaid` is genuinely not in the consumer's `node_modules`, the\n // *build* fails with a clear \"Could not resolve 'mermaid'\" error and\n // the consumer either `npm install mermaid` or supplies a\n // `renderDiagram` prop (which short-circuits this entire code path).\n mermaidPromise = import(\"mermaid\")\n .then((m) => m.default as MermaidModule)\n .catch((err) => {\n if (!mermaidMissingWarned) {\n mermaidMissingWarned = true;\n // eslint-disable-next-line no-console\n console.warn(\n \"[composeai] Failed to load the `mermaid` package. \" +\n \"Either `npm install mermaid` or pass a `renderDiagram` prop \" +\n \"to <Composer /> to render diagrams yourself.\",\n err,\n );\n }\n return null;\n });\n }\n const mermaid = await mermaidPromise;\n if (mermaid && !mermaidInitialized) {\n mermaid.initialize({\n startOnLoad: false,\n theme: \"default\",\n securityLevel: \"strict\",\n fontFamily: \"inherit\",\n });\n mermaidInitialized = true;\n }\n return mermaid;\n}\n\nfunction svgToDataUri(svg: string): string {\n return `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`;\n}\n\nexport function MermaidPlugin() {\n const [editor] = useLexicalComposerContext();\n const { features, icons, renderDiagram, classNames, sx } = useComposerContext();\n const { sparkle: SparkleIcon } = icons;\n const [diagrams, setDiagrams] = useState<DetectedDiagram[]>([]);\n\n // Default `keepSource` to true (visible) — opt-in to hide.\n const keepSource =\n typeof features.mermaid === \"object\"\n ? features.mermaid.keepSource !== false\n : true;\n\n useEffect(() => {\n const sync = () => {\n editor.getEditorState().read(() => {\n const found: DetectedDiagram[] = [];\n const root = $getRoot();\n const children = root.getChildren();\n\n let i = 0;\n while (i < children.length) {\n const opener = children[i];\n if (!$isParagraphNode(opener) || !FENCE_OPEN_MERMAID.test(opener.getTextContent())) {\n i++;\n continue;\n }\n // Collect every following paragraph until a closing ``` fence or\n // a non-paragraph sibling.\n const paragraphKeys: string[] = [opener.getKey()];\n const codeLines: string[] = [];\n let j = i + 1;\n while (j < children.length) {\n const next = children[j];\n if (!$isParagraphNode(next)) break;\n const text = next.getTextContent();\n paragraphKeys.push(next.getKey());\n if (FENCE_CLOSE.test(text)) {\n j++;\n break;\n }\n codeLines.push(text);\n j++;\n }\n found.push({\n id: opener.getKey(),\n code: codeLines.join(\"\\n\").trim(),\n paragraphKeys,\n });\n i = j;\n }\n\n setDiagrams((prev) => {\n if (\n prev.length === found.length &&\n prev.every(\n (d, idx) =>\n d.id === found[idx].id &&\n d.code === found[idx].code &&\n d.paragraphKeys.length === found[idx].paragraphKeys.length &&\n d.paragraphKeys.every((k, kk) => k === found[idx].paragraphKeys[kk]),\n )\n ) {\n return prev;\n }\n return found;\n });\n });\n };\n sync();\n return editor.registerUpdateListener(sync);\n }, [editor]);\n\n // Hide / re-show the mermaid fence paragraphs based on `keepSource`. We\n // imperatively toggle `display` on the rendered DOM elements — Lexical\n // recreates them on each update so we re-apply after diagrams change.\n // The previously-hidden keys are tracked so we can clean up if a fence\n // is removed or shrunk.\n const hiddenKeysRef = useRef<Set<string>>(new Set());\n useEffect(() => {\n const currentKeys = new Set<string>();\n for (const d of diagrams) for (const k of d.paragraphKeys) currentKeys.add(k);\n\n if (keepSource) {\n for (const key of hiddenKeysRef.current) {\n const el = editor.getElementByKey(key);\n if (el) el.style.removeProperty(\"display\");\n }\n hiddenKeysRef.current.clear();\n return;\n }\n\n for (const key of hiddenKeysRef.current) {\n if (!currentKeys.has(key)) {\n const el = editor.getElementByKey(key);\n if (el) el.style.removeProperty(\"display\");\n }\n }\n for (const key of currentKeys) {\n const el = editor.getElementByKey(key);\n if (el) el.style.display = \"none\";\n }\n hiddenKeysRef.current = currentKeys;\n }, [diagrams, keepSource, editor]);\n\n // On unmount, restore any blocks we hid so a future remount sees the\n // editor's natural rendering.\n useEffect(() => {\n return () => {\n for (const key of hiddenKeysRef.current) {\n const el = editor.getElementByKey(key);\n if (el) el.style.removeProperty(\"display\");\n }\n hiddenKeysRef.current.clear();\n };\n }, [editor]);\n\n if (diagrams.length === 0) return null;\n\n const preview = slotProps(\n \"mermaidPreview\",\n \"composer-mermaid\",\n classNames,\n sx,\n );\n\n return (\n <div {...preview}>\n <div className=\"composer-mermaid-head\">\n <SparkleIcon />\n Diagram preview\n </div>\n <div className=\"composer-mermaid-row\">\n {diagrams.map((d) => (\n <DiagramTile\n key={d.id}\n diagram={d}\n renderDiagram={renderDiagram}\n />\n ))}\n </div>\n </div>\n );\n}\n\ninterface TileProps {\n diagram: DetectedDiagram;\n renderDiagram?: DiagramRenderer;\n}\n\nfunction DiagramTile({ diagram, renderDiagram }: TileProps) {\n if (renderDiagram) {\n return <ConsumerTile diagram={diagram} renderDiagram={renderDiagram} />;\n }\n return <MermaidTile diagram={diagram} />;\n}\n\nfunction ConsumerTile({\n diagram,\n renderDiagram,\n}: {\n diagram: DetectedDiagram;\n renderDiagram: DiagramRenderer;\n}) {\n let content: ReactNode = null;\n try {\n content = renderDiagram({ code: diagram.code, language: \"mermaid\" });\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"[composeai] renderDiagram threw\", err);\n content = (\n <div className=\"composer-mermaid-msg composer-mermaid-msg--error\">\n {err instanceof Error ? err.message.slice(0, 80) : \"Render failed\"}\n </div>\n );\n }\n return <div className=\"composer-mermaid-tile\">{content}</div>;\n}\n\nfunction MermaidTile({ diagram }: { diagram: DetectedDiagram }) {\n const { icons } = useComposerContext();\n const { zoom: ZoomIcon } = icons;\n const [svg, setSvg] = useState<string | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [zoom, setZoom] = useState(false);\n const [mermaidMissing, setMermaidMissing] = useState(false);\n const renderId = useMemo(\n () => `mermaid-${diagram.id}-${Math.random().toString(36).slice(2, 8)}`,\n [diagram.id],\n );\n\n useEffect(() => {\n let cancelled = false;\n if (!diagram.code) {\n setSvg(null);\n return;\n }\n loadMermaid()\n .then((mermaid) => {\n if (cancelled) return null;\n if (!mermaid) {\n setMermaidMissing(true);\n return null;\n }\n return mermaid.render(renderId, diagram.code);\n })\n .then((result) => {\n if (cancelled || !result) return;\n setSvg(result.svg);\n setError(null);\n })\n .catch((err: unknown) => {\n if (cancelled) return;\n const msg = err instanceof Error ? err.message : \"Render failed\";\n setError(msg);\n setSvg(null);\n });\n return () => {\n cancelled = true;\n };\n }, [diagram.code, renderId]);\n\n return (\n <>\n <button\n type=\"button\"\n onClick={() => svg && setZoom(true)}\n aria-label=\"Zoom diagram\"\n className=\"composer-mermaid-tile\"\n >\n {svg ? (\n <>\n <div\n className=\"composer-mermaid-svg\"\n // SVG is generated by mermaid (securityLevel: strict).\n dangerouslySetInnerHTML={{ __html: svg }}\n />\n <span className=\"composer-mermaid-zoom\">\n <ZoomIcon />\n </span>\n </>\n ) : mermaidMissing ? (\n <div className=\"composer-mermaid-msg\">\n <span>\n Install <code className=\"composer-mermaid-code\">mermaid</code> or\n pass <code className=\"composer-mermaid-code\">renderDiagram</code>\n </span>\n </div>\n ) : error ? (\n <div className=\"composer-mermaid-msg composer-mermaid-msg--error\">\n <span>{error.slice(0, 80)}</span>\n </div>\n ) : (\n <div className=\"composer-mermaid-msg\">\n <span>Rendering…</span>\n </div>\n )}\n </button>\n {zoom && svg && (\n <ImageLightbox\n src={svgToDataUri(svg)}\n alt=\"Mermaid diagram\"\n onClose={() => setZoom(false)}\n />\n )}\n </>\n );\n}","import { useEffect, useMemo, useRef } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { resolveSx, slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { SlashCommand } from \"../types\";\n\ninterface Props {\n options: SlashCommand[];\n selectedIndex: number;\n /** Renders skeleton rows while an async fetch is in flight + no items yet. */\n isLoading?: boolean;\n onSelect: (index: number) => void;\n onHover: (index: number) => void;\n}\n\nexport function SlashMenu({\n options,\n selectedIndex,\n isLoading = false,\n onSelect,\n onHover,\n}: Props) {\n const listRef = useRef<HTMLUListElement>(null);\n const { classNames, sx } = useComposerContext();\n\n useEffect(() => {\n const el = listRef.current?.querySelector<HTMLElement>(\n `[data-index=\"${selectedIndex}\"]`,\n );\n if (el) el.scrollIntoView({ block: \"nearest\" });\n }, [selectedIndex]);\n\n const grouped = options.reduce<Record<string, { item: SlashCommand; index: number }[]>>(\n (acc, item, index) => {\n const g = item.group ?? \"Commands\";\n if (!acc[g]) acc[g] = [];\n acc[g].push({ item, index });\n return acc;\n },\n {},\n );\n\n const menu = slotProps(\n \"slashMenu\",\n \"composer-menu composer-menu--slash\",\n classNames,\n sx,\n );\n const itemStyle = useMemo(() => resolveSx(sx?.slashItem), [sx]);\n\n const showSkeleton = isLoading && options.length === 0;\n\n return (\n <div\n data-composer-popover=\"open\"\n role=\"listbox\"\n aria-label=\"Slash commands\"\n aria-busy={isLoading || undefined}\n {...menu}\n >\n <ul ref={listRef} className=\"composer-menu-list\">\n {showSkeleton && <SlashSkeleton rows={4} />}\n {Object.entries(grouped).map(([group, entries]) => (\n <li key={group}>\n <div className=\"composer-menu-group\">{group}</div>\n <ul>\n {entries.map(({ item, index }) => (\n <li\n key={item.id}\n data-index={index}\n role=\"option\"\n aria-selected={selectedIndex === index}\n onMouseDown={(e) => {\n e.preventDefault();\n onSelect(index);\n }}\n onMouseEnter={() => onHover(index)}\n className={cn(\"composer-menu-item\", classNames?.slashItem)}\n style={itemStyle}\n >\n {item.icon && (\n <span className=\"composer-menu-icon\">{item.icon}</span>\n )}\n <span className=\"composer-menu-text\">\n <span className=\"composer-menu-label\">{item.label}</span>\n {item.description && (\n <span className=\"composer-menu-desc\">\n {item.description}\n </span>\n )}\n </span>\n {item.shortcut && (\n <span className=\"composer-menu-shortcut\">\n {item.shortcut}\n </span>\n )}\n </li>\n ))}\n </ul>\n </li>\n ))}\n </ul>\n </div>\n );\n}\n\n/**\n * Shimmer rows shown while an async slash-commands resolver is in flight\n * and we don't yet have any items to display. Mirrors the icon + label +\n * description layout of a real command row.\n */\nfunction SlashSkeleton({ rows = 4 }: { rows?: number }) {\n return (\n <li aria-hidden=\"true\" className=\"composer-skel-row\">\n <span className=\"composer-skel-grouplabel composer-pulse\" />\n <ul className=\"composer-skel-group\">\n {Array.from({ length: rows }).map((_, i) => (\n <li key={i} className=\"composer-skel-line\">\n <span className=\"composer-skel-avatar composer-skel-avatar--square composer-pulse\" />\n <span className=\"composer-skel-text\">\n <span\n className=\"composer-skel-bar composer-pulse\"\n style={{ width: `${50 + ((i * 19) % 35)}%` }}\n />\n <span\n className=\"composer-skel-bar--sm composer-pulse\"\n style={{ width: `${30 + ((i * 13) % 30)}%` }}\n />\n </span>\n </li>\n ))}\n </ul>\n <span className=\"composer-sr-only\">Loading commands…</span>\n </li>\n );\n}","/**\n * SmartPopover — positions a typeahead menu relative to the trigger\n * character (`@`/`/`/`#`/…) that opened it.\n *\n * Two RTL/bidi pitfalls we have to navigate:\n *\n * 1. Chromium resolves `Range#getBoundingClientRect()` for ranges that\n * span more than one bidi run (the caret at a run boundary, or\n * Lexical's `[trigger, caret]` range) against the paragraph's\n * *logical* origin — which can be on the visually opposite side of\n * the line from where the trigger glyph is actually painted. Anchor\n * a menu to that rect and it lands on the far side of the screen.\n *\n * Workaround: walk back from the caret inside its host TextNode,\n * find the single trigger character, build a `Range` over *just\n * that one character*, and use that range's bbox. Single-character\n * ranges always sit wholly inside one bidi run, so their box is\n * the real painted glyph position in every mixed-bidi permutation.\n *\n * 2. Lexical's bidi handling lives at the *paragraph* level (it sets\n * `dir` on the paragraph element based on the first strong char\n * typed). So a `dir=\"rtl\"` composer can perfectly happily contain\n * an `dir=\"ltr\"` paragraph (`test @|`) — the trigger glyph is then\n * laid out left-aligned at the visual *left* of the editor card,\n * even though the surrounding chrome is RTL. If we keyed alignment\n * off the outer composer's `dir` we'd open the menu leftward of an\n * `@` that's already on the left — straight off-screen.\n *\n * Workaround: ask for the resolved CSS `direction` of the trigger\n * character's parent paragraph (the actual element it lives in),\n * not the editor wrapper. The menu opens into the reading flow of\n * the text the user is actually typing, regardless of the outer\n * `dir` setting. The `dir` prop is only used as an explicit\n * override hint for `dir=\"ltr\"` and `dir=\"rtl\"` when we can't\n * locate a paragraph (defensive fallback).\n *\n * Other notes:\n * - We render with `position: fixed` and viewport coordinates.\n * Lexical mounts its typeahead anchor under `<body>` and re-\n * positions it for its own overflow heuristic, so offset-parent-\n * relative positioning is unreliable.\n * - Vertical flip: when there isn't enough room below the trigger we\n * pin the menu's bottom edge just above the entire composer card.\n * - Recomputed on scroll, resize, selection change, anchor resize and\n * self-resize (the menu height changes as the filter narrows).\n */\nimport { useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n children: ReactNode;\n /** Gap between the menu and its anchor (caret or composer edge). */\n gap?: number;\n}\n\ninterface Placement {\n /** Final viewport-x for the menu's left edge. */\n left: number;\n /** Final viewport-y. Either `top` or `bottom` is set, never both. */\n top?: number;\n bottom?: number;\n /**\n * Resolved direction at the trigger character — used to set `dir`\n * on the popover wrapper so the menu's content (avatars, shortcuts,\n * descriptions) flips with the reading flow of the text the user\n * is actually typing.\n */\n rtl: boolean;\n}\n\nconst MARGIN = 8;\n\nfunction findComposerRoot(anchor: HTMLElement | null): HTMLElement | null {\n const active = document.activeElement;\n if (active instanceof HTMLElement) {\n const root = active.closest<HTMLElement>(\"[data-composer-root]\");\n if (root) return root;\n }\n if (anchor) {\n const anchorRect = anchor.getBoundingClientRect();\n const x = anchorRect.left + 1;\n const y = anchorRect.top + 1;\n const el = document.elementFromPoint(x, y);\n if (el instanceof HTMLElement) {\n const root = el.closest<HTMLElement>(\"[data-composer-root]\");\n if (root) return root;\n }\n }\n return document.querySelector<HTMLElement>(\"[data-composer-root]\");\n}\n\ninterface CaretRect {\n left: number;\n right: number;\n top: number;\n bottom: number;\n width: number;\n height: number;\n}\n\ninterface TriggerInfo {\n rect: CaretRect;\n /**\n * Resolved CSS direction of the *paragraph element* that visually\n * contains the trigger character. This is what we key the menu's\n * inline-start alignment off — it reflects the actual reading\n * direction of the text the user is typing, even when it differs\n * from the outer composer `dir`.\n */\n rtl: boolean;\n}\n\nfunction rectFromDom(rect: DOMRect): CaretRect {\n return {\n left: rect.left,\n right: rect.right,\n top: rect.top,\n bottom: rect.bottom,\n width: rect.width,\n height: rect.height,\n };\n}\n\n// Word-class characters across the scripts the composer is most likely\n// to encounter. We treat anything in this set as \"not a trigger\". Latin\n// letters and digits, Hebrew, Arabic, Persian/Urdu, CJK, plus the\n// underscore and any whitespace.\nconst WORD_OR_SPACE = /[A-Za-z0-9_\\s\\u0590-\\u05FF\\u0600-\\u06FF\\u4E00-\\u9FFF]/;\n\n/**\n * Walk up to the closest block-level ancestor that has a `dir`/CSS\n * `direction` we can read. This is typically the Lexical paragraph\n * the trigger character lives in — Lexical sets `dir` on the\n * paragraph element based on the first strong character typed, which\n * is exactly what we want to follow.\n */\nfunction isBlockRtl(node: Node): boolean | null {\n let el: Element | null =\n node.nodeType === Node.ELEMENT_NODE\n ? (node as Element)\n : node.parentElement;\n while (el) {\n // Read the *resolved* direction. Lexical applies `dir` as an\n // attribute on its paragraph element which CSS resolves into\n // `direction`. We don't need to crawl `dir` attributes by hand.\n const display = getComputedStyle(el).display;\n if (display && display !== \"inline\" && display !== \"contents\") {\n return getComputedStyle(el).direction === \"rtl\";\n }\n el = el.parentElement;\n }\n return null;\n}\n\n/**\n * Walk back from the live caret inside its host text node, find the\n * single trigger character (`@`/`/`/`#`/`?`/etc.), and return the\n * bounding rect of *just that character* together with the resolved\n * direction of its containing paragraph.\n *\n * The single-character `Range` trick is what makes this bidi-safe:\n * spanning multiple offsets across a bidi-run boundary (which is what\n * Lexical's anchor range does) gives a bbox the bidi engine resolves\n * against the line's logical origin — often on the opposite visual\n * side from the painted glyph. A range over one character sits wholly\n * inside one bidi run and always reports the real painted position.\n */\nfunction readTriggerInfo(): TriggerInfo | null {\n if (typeof window === \"undefined\") return null;\n const sel = window.getSelection?.();\n if (!sel || sel.rangeCount === 0) return null;\n const range = sel.getRangeAt(0);\n const node = range.startContainer;\n if (node.nodeType !== Node.TEXT_NODE) return null;\n\n const text = (node as Text).data;\n const cursorOffset = range.startOffset;\n\n // Look back at most ~64 chars — the default typeahead match window\n // is 32, so this is more than enough headroom while still bounding\n // the search.\n let triggerOffset = -1;\n const lookbackStart = Math.max(0, cursorOffset - 64);\n for (let i = cursorOffset - 1; i >= lookbackStart; i--) {\n const c = text[i];\n if (WORD_OR_SPACE.test(c)) continue;\n triggerOffset = i;\n break;\n }\n if (triggerOffset < 0) return null;\n\n const triggerRange = document.createRange();\n try {\n triggerRange.setStart(node, triggerOffset);\n triggerRange.setEnd(node, triggerOffset + 1);\n } catch {\n return null;\n }\n const rect = triggerRange.getBoundingClientRect();\n if (rect.height === 0 && rect.width === 0) return null;\n\n return {\n rect: rectFromDom(rect),\n rtl: isBlockRtl(node) ?? false,\n };\n}\n\n/**\n * Last-resort positioning info when we can't pinpoint the trigger\n * character. Falls back to the live caret rect, then to the Lexical\n * anchor element's rect, and infers direction from the editor wrapper.\n */\nfunction readFallbackInfo(\n fallback: HTMLElement,\n dirHint: \"ltr\" | \"rtl\" | \"auto\" | undefined,\n): TriggerInfo {\n const sel = typeof window !== \"undefined\" ? window.getSelection?.() : null;\n let rect: CaretRect;\n if (sel && sel.rangeCount > 0) {\n const r = sel.getRangeAt(0).getBoundingClientRect();\n rect =\n r.height > 0 || r.width > 0\n ? rectFromDom(r)\n : rectFromDom(fallback.getBoundingClientRect());\n const blockRtl =\n sel.rangeCount > 0\n ? isBlockRtl(sel.getRangeAt(0).startContainer)\n : null;\n if (blockRtl !== null) return { rect, rtl: blockRtl };\n } else {\n rect = rectFromDom(fallback.getBoundingClientRect());\n }\n if (dirHint === \"rtl\") return { rect, rtl: true };\n if (dirHint === \"ltr\") return { rect, rtl: false };\n // Last fallback: the editor wrapper's resolved direction.\n const root =\n fallback.closest<HTMLElement>(\"[data-composer-root]\") ??\n document.querySelector<HTMLElement>(\"[data-composer-root]\");\n const editor = root?.querySelector<HTMLElement>(\".composer-editor\");\n const probe = editor ?? root ?? fallback;\n return { rect, rtl: getComputedStyle(probe).direction === \"rtl\" };\n}\n\nexport function SmartPopover({ children, gap = 6 }: Props) {\n const ref = useRef<HTMLDivElement>(null);\n const [placement, setPlacement] = useState<Placement | null>(null);\n // Lexical mounts the typeahead anchor under <body>, escaping the inline\n // CSS variables we set on `[data-composer-root]`. Re-apply them here so\n // the brand-colour tokens reach the menu's children (selected row bg,\n // mention avatar, etc.).\n const { tokenStyle, dir } = useComposerContext();\n\n useLayoutEffect(() => {\n const el = ref.current;\n if (!el) return;\n const anchor = el.parentElement;\n if (!anchor) return;\n\n const update = () => {\n // Find the trigger character's actual painted rect (single-char\n // range — bidi-safe) and the resolved direction of its host\n // paragraph. Fall back to the caret / Lexical anchor rect if we\n // can't locate the trigger (unusual editor state).\n const info = readTriggerInfo() ?? readFallbackInfo(anchor, dir);\n const triggerRect = info.rect;\n\n const menuHeight = el.offsetHeight;\n const menuWidth = el.offsetWidth;\n const viewportH = window.innerHeight;\n const viewportW = window.innerWidth;\n\n // Inline-start alignment, keyed off the *paragraph's* direction\n // (not the outer composer's). In LTR the menu's left edge meets\n // the trigger's left edge; in RTL its right edge meets the\n // trigger's right edge. The popup therefore opens into the line's\n // actual reading flow even when an LTR run lives inside an RTL\n // composer or vice versa.\n const baseLeft = info.rtl\n ? triggerRect.right - menuWidth\n : triggerRect.left;\n\n // Clamp to the viewport so the menu never escapes either edge.\n let left = baseLeft;\n if (left + menuWidth + MARGIN > viewportW) {\n left = viewportW - menuWidth - MARGIN;\n }\n if (left < MARGIN) left = MARGIN;\n\n // Vertical: prefer below, flip above (anchored to the composer's\n // top edge) when the menu would clip the viewport bottom.\n const spaceBelow = viewportH - triggerRect.bottom;\n const spaceAbove = triggerRect.top;\n const wantsAbove =\n spaceBelow < menuHeight + MARGIN && spaceAbove > spaceBelow;\n\n let next: Placement;\n if (wantsAbove) {\n const composerRoot = findComposerRoot(anchor);\n const topEdge = composerRoot\n ? composerRoot.getBoundingClientRect().top\n : triggerRect.top;\n next = {\n left,\n bottom: Math.max(MARGIN, viewportH - topEdge + gap),\n rtl: info.rtl,\n };\n } else {\n next = { left, top: triggerRect.bottom + gap, rtl: info.rtl };\n }\n\n setPlacement((prev) =>\n prev &&\n prev.left === next.left &&\n prev.top === next.top &&\n prev.bottom === next.bottom &&\n prev.rtl === next.rtl\n ? prev\n : next,\n );\n };\n\n update();\n const ro = new ResizeObserver(update);\n ro.observe(el);\n // Lexical re-positions its anchor element as the caret moves. We\n // don't read the anchor's rect anymore, but observing its size still\n // gives us a free reposition signal whenever the typeahead match\n // grows or shrinks — handy because `selectionchange` doesn't fire\n // for typing-only changes inside an already-collapsed selection.\n ro.observe(anchor);\n // Caret-driven repositioning. The selection's range moves under our\n // feet as the user types, arrows around, or clicks elsewhere; this\n // keeps the menu glued to that movement without leaning on Lexical's\n // own (sometimes-misplaced) anchor.\n document.addEventListener(\"selectionchange\", update);\n window.addEventListener(\"resize\", update);\n window.addEventListener(\"scroll\", update, true);\n return () => {\n ro.disconnect();\n document.removeEventListener(\"selectionchange\", update);\n window.removeEventListener(\"resize\", update);\n window.removeEventListener(\"scroll\", update, true);\n };\n }, [children, gap, dir]);\n\n const style: React.CSSProperties =\n placement === null\n ? {\n position: \"fixed\",\n left: 0,\n top: 0,\n visibility: \"hidden\",\n zIndex: 60,\n }\n : {\n position: \"fixed\",\n left: placement.left,\n top: placement.top,\n bottom: placement.bottom,\n zIndex: 60,\n };\n\n // Merge the consumer's token CSS vars first so positioning props (which\n // can be `undefined`) don't blow them away.\n const mergedStyle: React.CSSProperties = tokenStyle\n ? { ...tokenStyle, ...style }\n : style;\n\n return (\n <div\n ref={ref}\n data-composer-scope=\"\"\n data-composer-popover-placement={\n placement?.bottom !== undefined ? \"above-composer\" : \"below\"\n }\n // Match the popover's inline direction to the resolved direction\n // at the trigger character. Children (mention rows, slash items,\n // shortcuts) use logical flexbox + `ms-*`/`me-*` utilities so\n // setting `dir` here is enough to flip avatars to the start side,\n // shortcuts to the end side, and text alignment to follow the\n // language being typed.\n dir={placement?.rtl ? \"rtl\" : \"ltr\"}\n style={mergedStyle}\n >\n {children}\n </div>\n );\n}","/**\n * useOutsideClickDismiss — closes the active typeahead menu of `editor` when\n * the user clicks (or touches) outside the composer root and outside any\n * open popover. Disabled when `enabled` is false; safe to call\n * unconditionally because the listeners are only attached while enabled.\n *\n * \"Outside\" means: the event target is not a descendant of\n * `[data-composer-root]` and not a descendant of an element rendered by\n * `<SmartPopover />` (which carries `data-composer-popover-placement`).\n *\n * Closing is performed by dispatching `KEY_ESCAPE_COMMAND` on the editor —\n * the same path used by Lexical's typeahead plugin when the user presses\n * Escape, so dismissal feels native and triggers `onClose` callbacks.\n */\nimport { useEffect } from \"react\";\nimport { KEY_ESCAPE_COMMAND, type LexicalEditor } from \"lexical\";\n\nexport function useOutsideClickDismiss(\n editor: LexicalEditor,\n enabled: boolean,\n): void {\n useEffect(() => {\n if (!enabled) return;\n\n const dismiss = () => {\n const event = new KeyboardEvent(\"keydown\", { key: \"Escape\" });\n editor.dispatchCommand(KEY_ESCAPE_COMMAND, event);\n };\n\n const isOutside = (target: EventTarget | null): boolean => {\n if (!(target instanceof Node)) return false;\n const popover = document.querySelector(\n \"[data-composer-popover-placement]\",\n );\n if (!popover) return false; // No menu open — nothing to dismiss\n if (popover.contains(target)) return false;\n\n const el =\n target instanceof Element\n ? target\n : (target.parentElement as Element | null);\n if (!el) return true;\n if (el.closest(\"[data-composer-root]\")) return false;\n return true;\n };\n\n const onPointer = (e: MouseEvent | TouchEvent) => {\n const target =\n e instanceof TouchEvent ? e.touches[0]?.target ?? null : e.target;\n if (isOutside(target)) dismiss();\n };\n\n document.addEventListener(\"mousedown\", onPointer, true);\n document.addEventListener(\"touchstart\", onPointer, true);\n return () => {\n document.removeEventListener(\"mousedown\", onPointer, true);\n document.removeEventListener(\"touchstart\", onPointer, true);\n };\n }, [editor, enabled]);\n}","/**\n * SlashCommandPlugin — typeahead menu that opens when the user types `/` at\n * the start of a line (or after whitespace). Consumers feed commands via\n * `features.slashCommands`.\n *\n * Built on Lexical's `LexicalTypeaheadMenuPlugin` so we get IME-safe match\n * detection, keyboard navigation, and caret-anchored positioning for free.\n */\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n LexicalTypeaheadMenuPlugin,\n MenuOption,\n useBasicTypeaheadTriggerMatch,\n} from \"@lexical/react/LexicalTypeaheadMenuPlugin\";\nimport { createPortal } from \"react-dom\";\nimport { $getSelection, $isRangeSelection, type TextNode } from \"lexical\";\nimport type {\n SlashCommand,\n SlashCommandContext,\n SlashConfig,\n} from \"../types\";\nimport { SlashMenu } from \"../ui/SlashMenu\";\nimport { SmartPopover } from \"../ui/SmartPopover\";\nimport { useOutsideClickDismiss } from \"../hooks/useOutsideClickDismiss\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\nclass SlashOption extends MenuOption {\n command: SlashCommand;\n constructor(command: SlashCommand) {\n super(command.id);\n this.command = command;\n }\n}\n\ninterface Props {\n config: SlashConfig;\n onSubmit: () => void;\n}\n\nfunction isSyncItems(\n items: SlashConfig[\"items\"],\n): items is SlashCommand[] {\n return Array.isArray(items);\n}\n\nexport function SlashCommandPlugin({ config, onSubmit }: Props) {\n const [editor] = useLexicalComposerContext();\n const { closeMenusOnOutsideClick } = useComposerContext();\n const [query, setQuery] = useState<string>(\"\");\n const [asyncItems, setAsyncItems] = useState<SlashCommand[] | null>(null);\n const [isLoading, setIsLoading] = useState<boolean>(\n !isSyncItems(config.items),\n );\n\n useOutsideClickDismiss(editor, closeMenusOnOutsideClick);\n\n const triggerFn = useBasicTypeaheadTriggerMatch(\n config.trigger ?? \"/\",\n { minLength: 0, maxLength: 32, allowWhitespace: false },\n );\n\n // Resolve async items when query changes.\n useEffect(() => {\n if (isSyncItems(config.items)) {\n setIsLoading(false);\n return;\n }\n let cancelled = false;\n setIsLoading(true);\n Promise.resolve(config.items(query)).then((res) => {\n if (cancelled) return;\n setAsyncItems(res);\n setIsLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [query, config.items]);\n\n const allItems = useMemo<SlashCommand[]>(() => {\n return isSyncItems(config.items) ? config.items : asyncItems ?? [];\n }, [config.items, asyncItems]);\n\n const options = useMemo(() => {\n const q = query.trim().toLowerCase();\n const max = config.maxItems ?? 8;\n const filtered = q\n ? allItems.filter((it) => {\n const hay = `${it.label} ${it.description ?? \"\"} ${it.group ?? \"\"}`.toLowerCase();\n return hay.includes(q);\n })\n : allItems;\n return filtered.slice(0, max).map((c) => new SlashOption(c));\n }, [allItems, query, config.maxItems]);\n\n const onSelectOption = useCallback(\n (\n selectedOption: SlashOption,\n nodeToReplace: TextNode | null,\n closeMenu: () => void,\n matchingString: string,\n ) => {\n editor.update(() => {\n if (nodeToReplace) nodeToReplace.remove();\n });\n const ctx: SlashCommandContext = {\n insertText: (text) => {\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) sel.insertText(text);\n });\n },\n insertMarkdown: (md) => {\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) sel.insertText(md);\n });\n },\n cancel: () => closeMenu(),\n submit: () => onSubmit(),\n };\n selectedOption.command.onSelect?.(ctx);\n closeMenu();\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n void matchingString;\n },\n [editor, onSubmit],\n );\n\n return (\n <LexicalTypeaheadMenuPlugin<SlashOption>\n onQueryChange={(s) => setQuery(s ?? \"\")}\n onSelectOption={onSelectOption}\n triggerFn={triggerFn}\n options={options}\n menuRenderFn={(anchorElementRef, { selectedIndex, selectOptionAndCleanUp, setHighlightedIndex }) => {\n if (!anchorElementRef.current) return null;\n // Keep the menu open while an async fetch is in flight even without\n // any items so the consumer's SlashMenu can render its skeleton.\n if (options.length === 0 && !isLoading) return null;\n return createPortal(\n <SmartPopover>\n <SlashMenu\n options={options.map((o) => o.command)}\n selectedIndex={selectedIndex ?? 0}\n isLoading={isLoading}\n onSelect={(index) => selectOptionAndCleanUp(options[index])}\n onHover={(index) => setHighlightedIndex(index)}\n />\n </SmartPopover>,\n anchorElementRef.current,\n );\n }}\n />\n );\n}","import { useState } from \"react\";\n\ninterface Props {\n src?: string;\n alt: string;\n size?: number;\n className?: string;\n}\n\n/** Small circular avatar used inside MentionMenu. Falls back to initials. */\nexport function Avatar({ src, alt, size = 28, className }: Props) {\n const [errored, setErrored] = useState(false);\n const showImage = src && !errored;\n const initial = (alt || \"?\").slice(0, 1).toUpperCase();\n return (\n <span\n className={\"composer-avatar\" + (className ? ` ${className}` : \"\")}\n style={{ width: size, height: size }}\n >\n {showImage ? (\n <img\n src={src}\n alt={alt}\n className=\"composer-avatar-img\"\n onError={() => setErrored(true)}\n />\n ) : (\n initial\n )}\n </span>\n );\n}","import { useEffect, useMemo, useRef } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { resolveSx, slotProps } from \"../internal/sx\";\nimport { Avatar } from \"../internal/Avatar\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { MentionItem } from \"../types\";\n\ninterface Props {\n options: MentionItem[];\n selectedIndex: number;\n /** Renders skeleton rows while an async fetch is in flight + no items yet. */\n isLoading?: boolean;\n onSelect: (index: number) => void;\n onHover: (index: number) => void;\n}\n\nexport function MentionMenu({\n options,\n selectedIndex,\n isLoading = false,\n onSelect,\n onHover,\n}: Props) {\n const listRef = useRef<HTMLUListElement>(null);\n const { classNames, sx } = useComposerContext();\n\n useEffect(() => {\n const el = listRef.current?.querySelector<HTMLElement>(\n `[data-index=\"${selectedIndex}\"]`,\n );\n if (el) el.scrollIntoView({ block: \"nearest\" });\n }, [selectedIndex]);\n\n const menu = slotProps(\"mentionMenu\", \"composer-menu\", classNames, sx);\n const itemStyle = useMemo(() => resolveSx(sx?.mentionItem), [sx]);\n\n // Only show skeleton when we genuinely have nothing to display — once\n // we have stale items from a previous query we keep showing them while\n // the next fetch resolves to avoid flicker.\n const showSkeleton = isLoading && options.length === 0;\n\n return (\n <div\n data-composer-popover=\"open\"\n role=\"listbox\"\n aria-label=\"Mentions\"\n aria-busy={isLoading || undefined}\n {...menu}\n >\n <ul ref={listRef} className=\"composer-menu-list\">\n {showSkeleton ? (\n <MentionSkeleton rows={3} />\n ) : null}\n {options.map((item, index) => (\n <li\n key={item.id}\n data-index={index}\n role=\"option\"\n aria-selected={selectedIndex === index}\n onMouseDown={(e) => {\n e.preventDefault();\n onSelect(index);\n }}\n onMouseEnter={() => onHover(index)}\n className={cn(\"composer-menu-item\", classNames?.mentionItem)}\n style={itemStyle}\n >\n {item.avatarUrl ? (\n <Avatar src={item.avatarUrl} alt={item.label} />\n ) : item.icon ? (\n <span className=\"composer-menu-avatar\">{item.icon}</span>\n ) : (\n <span className=\"composer-menu-avatar\">\n {item.label.slice(0, 1).toUpperCase()}\n </span>\n )}\n <span className=\"composer-menu-text\">\n <span className=\"composer-menu-label\">{item.label}</span>\n {item.description && (\n <span className=\"composer-menu-desc\">{item.description}</span>\n )}\n </span>\n </li>\n ))}\n </ul>\n </div>\n );\n}\n\n/**\n * Three-line shimmer placeholder mirroring the avatar + label + description\n * layout of a real mention row. Pure CSS animation via the `composer-pulse`\n * class — no JS keyframes, no layout thrash.\n */\nfunction MentionSkeleton({ rows = 3 }: { rows?: number }) {\n return (\n <li aria-hidden=\"true\" className=\"composer-skel-row\">\n <ul className=\"composer-skel-group\">\n {Array.from({ length: rows }).map((_, i) => (\n <li key={i} className=\"composer-skel-line\">\n <span className=\"composer-skel-avatar composer-pulse\" />\n <span className=\"composer-skel-text\">\n <span\n className=\"composer-skel-bar composer-pulse\"\n style={{ width: `${60 + ((i * 17) % 30)}%` }}\n />\n <span\n className=\"composer-skel-bar--sm composer-pulse\"\n style={{ width: `${35 + ((i * 23) % 25)}%` }}\n />\n </span>\n </li>\n ))}\n </ul>\n <span className=\"composer-sr-only\">Loading suggestions…</span>\n </li>\n );\n}","/**\n * MentionPlugin — typeahead that triggers on `@` and replaces the trigger\n * text with a `MentionNode` chip on select. The chip is atomic (single\n * backspace removes it) and rendered in the theme primary color.\n */\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n LexicalTypeaheadMenuPlugin,\n MenuOption,\n useBasicTypeaheadTriggerMatch,\n} from \"@lexical/react/LexicalTypeaheadMenuPlugin\";\nimport { createPortal } from \"react-dom\";\nimport {\n $createTextNode,\n $getSelection,\n $isRangeSelection,\n type TextNode,\n} from \"lexical\";\nimport type { MentionConfig, MentionItem } from \"../types\";\nimport { $createMentionNode } from \"../core/nodes/MentionNode\";\nimport { MentionMenu } from \"../ui/MentionMenu\";\nimport { SmartPopover } from \"../ui/SmartPopover\";\nimport { useOutsideClickDismiss } from \"../hooks/useOutsideClickDismiss\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\nclass MentionOption extends MenuOption {\n item: MentionItem;\n constructor(item: MentionItem) {\n super(item.id);\n this.item = item;\n }\n}\n\ninterface Props {\n config: MentionConfig;\n}\n\nfunction isSyncItems(\n items: MentionConfig[\"items\"],\n): items is MentionItem[] {\n return Array.isArray(items);\n}\n\nexport function MentionPlugin({ config }: Props) {\n const [editor] = useLexicalComposerContext();\n const { closeMenusOnOutsideClick } = useComposerContext();\n const [query, setQuery] = useState<string>(\"\");\n const [asyncItems, setAsyncItems] = useState<MentionItem[] | null>(null);\n // Initial state: async lists are \"loading\" until the first resolution.\n // Sync arrays are never loading.\n const [isLoading, setIsLoading] = useState<boolean>(\n !isSyncItems(config.items),\n );\n\n useOutsideClickDismiss(editor, closeMenusOnOutsideClick);\n\n const trigger = config.trigger ?? \"@\";\n\n const triggerFn = useBasicTypeaheadTriggerMatch(trigger, {\n minLength: 0,\n maxLength: 32,\n allowWhitespace: false,\n });\n\n useEffect(() => {\n if (isSyncItems(config.items)) {\n setIsLoading(false);\n return;\n }\n let cancelled = false;\n setIsLoading(true);\n Promise.resolve(config.items(query)).then((res) => {\n if (cancelled) return;\n setAsyncItems(res);\n setIsLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [query, config.items]);\n\n const allItems = useMemo<MentionItem[]>(() => {\n return isSyncItems(config.items) ? config.items : asyncItems ?? [];\n }, [config.items, asyncItems]);\n\n const options = useMemo(() => {\n const q = query.trim().toLowerCase();\n const max = config.maxItems ?? 8;\n const filtered = q\n ? allItems.filter((it) =>\n `${it.label} ${it.description ?? \"\"}`.toLowerCase().includes(q),\n )\n : allItems;\n return filtered.slice(0, max).map((c) => new MentionOption(c));\n }, [allItems, query, config.maxItems]);\n\n const onSelectOption = useCallback(\n (\n selectedOption: MentionOption,\n nodeToReplace: TextNode | null,\n closeMenu: () => void,\n ) => {\n editor.update(() => {\n // The chip is an inline ElementNode that contains a TextNode for\n // the label. Storing the label as a real child means the user can\n // backspace through it character-by-character — the ID on the\n // wrapping element stays attached to whatever text remains.\n const chip = $createMentionNode(selectedOption.item.id, trigger);\n chip.append($createTextNode(selectedOption.item.label));\n if (nodeToReplace) {\n nodeToReplace.replace(chip);\n } else {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) sel.insertNodes([chip]);\n }\n // Add a trailing space so the user can keep typing immediately\n // after the chip without their next char being captured inside.\n const space = $createTextNode(\" \");\n chip.insertAfter(space);\n space.select();\n });\n closeMenu();\n },\n [editor, trigger],\n );\n\n return (\n <LexicalTypeaheadMenuPlugin<MentionOption>\n onQueryChange={(s) => setQuery(s ?? \"\")}\n onSelectOption={onSelectOption}\n triggerFn={triggerFn}\n options={options}\n menuRenderFn={(anchorElementRef, { selectedIndex, selectOptionAndCleanUp, setHighlightedIndex }) => {\n if (!anchorElementRef.current) return null;\n // Keep the menu visible while an async fetch is in flight even if\n // we currently have no items — the MentionMenu renders a skeleton\n // in that case so the user gets immediate feedback.\n if (options.length === 0 && !isLoading) return null;\n return createPortal(\n <SmartPopover>\n <MentionMenu\n options={options.map((o) => o.item)}\n selectedIndex={selectedIndex ?? 0}\n isLoading={isLoading}\n onSelect={(index) => selectOptionAndCleanUp(options[index])}\n onHover={(index) => setHighlightedIndex(index)}\n />\n </SmartPopover>,\n anchorElementRef.current,\n );\n }}\n />\n );\n}","/**\n * GhostedAutoCompletePlugin — inline \"ghost text\" autocomplete suggested\n * from a fixed list.\n *\n * UX contract:\n * - Watches the editor's plain-text content. When that text is a prefix\n * of one of the consumer's `suggestions`, the remainder is rendered\n * just after the caret in a muted style — same trick GitHub Copilot,\n * iOS QuickType and shell autocompletion use to nudge users toward\n * the completion without committing to it.\n * - **Tab** accepts the suggestion (the remainder is inserted into the\n * editor and the ghost clears). Escape, a non-matching keystroke, or\n * moving the caret away dismisses it without committing.\n * - The ghost only appears when the caret sits at the END of the\n * document — typing in the middle would render a confusing\n * \"wraparound\" suggestion.\n * - When several suggestions share a prefix, the FIRST match wins. The\n * consumer is expected to order the list by priority.\n *\n * Why ghost-text instead of a dropdown menu? It's the lowest-friction\n * autocomplete UI for a curated, sentence-shaped suggestion list (chat\n * prompts, templated commands, FAQ answers). There's nothing to click\n * through and nothing to dismiss — just keep typing or hit Tab.\n *\n * Why an overlay div instead of decorating the editor itself? Lexical's\n * source-of-truth model means the editor's text content is what we'd\n * eventually serialize on submit; inserting \"soft\" ghost characters into\n * the document would either need a custom non-selectable node (heavy)\n * or risk being captured by serializers / cursor traversal. A sibling\n * overlay positioned over the editor's padding box gives us pixel-perfect\n * alignment with zero risk of leaking into the payload.\n */\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $getRoot,\n $getSelection,\n $isRangeSelection,\n COMMAND_PRIORITY_HIGH,\n COMMAND_PRIORITY_LOW,\n KEY_ESCAPE_COMMAND,\n KEY_TAB_COMMAND,\n} from \"lexical\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { GhostedAutoCompleteConfig } from \"../types\";\n\ninterface Props {\n /**\n * Normalized feature value — either a plain `string[]` shorthand or the\n * full {@link GhostedAutoCompleteConfig} object. Plugin handles both.\n */\n config: string[] | GhostedAutoCompleteConfig;\n}\n\ninterface ResolvedConfig {\n suggestions: string[];\n caseSensitive: boolean;\n minLength: number;\n}\n\nfunction resolveConfig(config: Props[\"config\"]): ResolvedConfig {\n if (Array.isArray(config)) {\n return { suggestions: config, caseSensitive: false, minLength: 1 };\n }\n return {\n suggestions: config.suggestions,\n caseSensitive: !!config.caseSensitive,\n // `1` (not `0`) so the ghost never appears on an empty editor — the\n // placeholder handles that, and showing a ghost there would feel like\n // the composer is auto-typing on its own.\n minLength: Math.max(1, config.minLength ?? 1),\n };\n}\n\n/**\n * Find the first suggestion that starts with `typed` (per `caseSensitive`)\n * and return its UN-typed remainder. Strict-prefix only — if `typed`\n * equals a suggestion exactly, there's nothing to suggest and we return\n * `null`.\n */\nfunction findGhost(\n typed: string,\n suggestions: ReadonlyArray<string>,\n caseSensitive: boolean,\n): string | null {\n if (typed.length === 0) return null;\n const needle = caseSensitive ? typed : typed.toLowerCase();\n for (const candidate of suggestions) {\n if (candidate.length <= typed.length) continue;\n const hay = caseSensitive ? candidate : candidate.toLowerCase();\n if (hay.startsWith(needle)) {\n // Preserve the candidate's casing in the remainder — `typed` already\n // sits in the editor, so we only return what's NOT yet typed.\n return candidate.slice(typed.length);\n }\n }\n return null;\n}\n\n/**\n * Whether the current selection is collapsed at the very end of the\n * document. Run inside a `getEditorState().read(...)` scope.\n *\n * Used as a gating signal: showing a ghost while the caret is parked\n * mid-paragraph would visually claim the user is about to overwrite\n * trailing text, which they aren't.\n */\nfunction $isCaretAtDocumentEnd(): boolean {\n const sel = $getSelection();\n if (!$isRangeSelection(sel) || !sel.isCollapsed()) return false;\n const root = $getRoot();\n const last = root.getLastDescendant();\n if (last === null) {\n // Empty document — `selectEnd` lands on the root element with\n // offset 0; treat that as \"at end\".\n return sel.focus.key === root.getKey();\n }\n if (sel.focus.key !== last.getKey()) return false;\n const size =\n \"getTextContentSize\" in last && typeof last.getTextContentSize === \"function\"\n ? (last as { getTextContentSize: () => number }).getTextContentSize()\n : last.getTextContent().length;\n return sel.focus.offset === size;\n}\n\ninterface GhostState {\n typed: string;\n remainder: string;\n}\n\nexport function GhostedAutoCompletePlugin({ config }: Props) {\n const [editor] = useLexicalComposerContext();\n const { multiline } = useComposerContext();\n const resolved = useMemo(() => resolveConfig(config), [config]);\n\n const [ghost, setGhost] = useState<GhostState | null>(null);\n // Ref mirror so key-command handlers (which need a stable identity\n // across renders) can read the latest ghost without re-subscribing on\n // every state change — re-subscribing churns the command priority\n // stack and racy popovers.\n const ghostRef = useRef<GhostState | null>(null);\n ghostRef.current = ghost;\n\n // Recompute the ghost whenever the editor state changes. We read the\n // plain text (chips collapse to their labels) and the selection, then\n // probe the suggestion list for a strict-prefix match.\n useEffect(() => {\n const compute = () => {\n editor.getEditorState().read(() => {\n if (!$isCaretAtDocumentEnd()) {\n setGhost(null);\n return;\n }\n const typed = $getRoot().getTextContent();\n if (typed.length < resolved.minLength) {\n setGhost(null);\n return;\n }\n const remainder = findGhost(\n typed,\n resolved.suggestions,\n resolved.caseSensitive,\n );\n if (!remainder) {\n setGhost(null);\n return;\n }\n // Only nudge React when something actually changed — avoids\n // overlay flicker for every cursor-move tick Lexical emits.\n setGhost((prev) =>\n prev && prev.typed === typed && prev.remainder === remainder\n ? prev\n : { typed, remainder },\n );\n });\n };\n compute();\n return editor.registerUpdateListener(compute);\n }, [editor, resolved]);\n\n // Tab accepts the ghost. We hijack KEY_TAB_COMMAND at HIGH priority so\n // the keystroke is fully consumed before the browser ever sees it —\n // otherwise focus would jump to the next focusable in the toolbar\n // (Send button, etc.) and the user would lose their composing context.\n // When no ghost is showing we let the key fall through so Tab keeps its\n // normal \"leave the editor\" semantics.\n const acceptGhost = useCallback(() => {\n const current = ghostRef.current;\n if (!current) return false;\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) {\n sel.insertText(current.remainder);\n }\n });\n setGhost(null);\n return true;\n }, [editor]);\n\n useEffect(() => {\n return editor.registerCommand(\n KEY_TAB_COMMAND,\n (event) => {\n if (!ghostRef.current) return false;\n event?.preventDefault();\n return acceptGhost();\n },\n COMMAND_PRIORITY_HIGH,\n );\n }, [editor, acceptGhost]);\n\n // Escape clears the ghost (matches the \"dismiss the suggestion\"\n // gesture in shells / IDEs) but only when there's something to clear —\n // otherwise we'd swallow Escape from anything else that wants it.\n useEffect(() => {\n return editor.registerCommand(\n KEY_ESCAPE_COMMAND,\n () => {\n if (!ghostRef.current) return false;\n setGhost(null);\n return true;\n },\n COMMAND_PRIORITY_LOW,\n );\n }, [editor]);\n\n if (!ghost) return null;\n return (\n <GhostOverlay\n typed={ghost.typed}\n remainder={ghost.remainder}\n multiline={multiline}\n />\n );\n}\n\ninterface OverlayProps {\n typed: string;\n remainder: string;\n multiline: boolean;\n}\n\n/**\n * Renders the ghost text inside the editor's padding box via a portal,\n * so the suggestion floats exactly where the next typed character would\n * land — no measuring, no math.\n *\n * Implementation: we lay an absolutely-positioned, pointer-events:none\n * div over the editor's parent (`.composer-editor-block`) and fill it\n * with `[invisible-typed][muted-remainder]`. The invisible span occupies\n * the same horizontal space as the user's text, so the visible remainder\n * starts precisely at the caret.\n *\n * Limitations (acceptable for the curated-suggestion use case):\n * - Doesn't follow per-paragraph block styling (headings render at\n * larger sizes than this overlay). Ghost autocomplete is most useful\n * in plain prompts / search bars where this isn't a factor.\n * - In multiline mode, if the editor scrolls past its viewport the\n * overlay stays anchored to the box (it doesn't scroll with the\n * content). For multi-paragraph drafts the suggestion will simply\n * be clipped — same as a placeholder hint would be.\n */\nfunction GhostOverlay({ typed, remainder, multiline }: OverlayProps) {\n const [editor] = useLexicalComposerContext();\n const [container, setContainer] = useState<HTMLElement | null>(null);\n\n useEffect(() => {\n const root = editor.getRootElement();\n // The contenteditable is wrapped by the EditorShell's\n // `.composer-editor-block` div, which is `position: relative` —\n // perfect anchor for our absolute overlay.\n const block = root?.closest<HTMLElement>(\".composer-editor-block\") ?? null;\n setContainer(block);\n }, [editor]);\n\n if (!container) return null;\n\n // Mirror the editor's padding / typography so the overlay text lines\n // up exactly with the contenteditable's own text origin. We keep the\n // two padding strings in lock-step with `EditorShell.tsx`'s\n // `editorClass` — when one changes, change both.\n const paddingClass = multiline\n ? \"composer-ghost-overlay--multiline\"\n : \"composer-ghost-overlay--inline\";\n\n return createPortal(\n <div\n aria-hidden\n data-composer-ghost=\"\"\n className={`composer-ghost-overlay ${paddingClass}`}\n >\n <span className=\"composer-ghost-overlay-typed\" aria-hidden>\n {typed}\n </span>\n <span className=\"composer-ghost-suggestion\">{remainder}</span>\n </div>,\n container,\n );\n}","import { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { Attachment } from \"../types\";\n\ninterface Props {\n attachment: Attachment;\n onRemove: () => void;\n onZoom?: () => void;\n}\n\nfunction formatBytes(bytes: number) {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\nexport function AttachmentChip({ attachment, onRemove, onZoom }: Props) {\n const { icons, classNames, sx } = useComposerContext();\n const {\n file: FileIcon,\n audio: AudioIcon,\n close: CloseIcon,\n zoom: ZoomIcon,\n spinner: SpinnerIcon,\n warning: WarningIcon,\n } = icons;\n const isImage = attachment.kind === \"image\" && !!attachment.previewUrl;\n const isUploading = attachment.status === \"uploading\";\n const isFailed = attachment.status === \"failed\";\n // Surface the upload error on hover. Falls back to the file name when\n // nothing's wrong, so the chip is still scannable.\n const titleText = isFailed && attachment.error\n ? `${attachment.name} — ${attachment.error}`\n : attachment.name;\n\n if (isImage) {\n const chip = slotProps(\n \"attachmentChip\",\n \"composer-chip composer-chip--image\",\n classNames,\n sx,\n );\n return (\n <div {...chip} title={titleText}>\n <img\n src={attachment.previewUrl}\n alt={attachment.name}\n className=\"composer-chip-img\"\n />\n {/* Uploading overlay — sits above the image, eats hover events\n below so the user doesn't accidentally trigger zoom mid-upload. */}\n {isUploading && (\n <div\n aria-label=\"Uploading\"\n className=\"composer-chip-overlay composer-chip-overlay--uploading\"\n >\n <SpinnerIcon className=\"composer-spin\" />\n </div>\n )}\n {/* Failed overlay — destructive tint + warning glyph + persistent\n (no hover gating) so the failure stays obvious. */}\n {isFailed && (\n <div\n aria-label=\"Upload failed\"\n className=\"composer-chip-overlay composer-chip-overlay--failed\"\n >\n <WarningIcon />\n </div>\n )}\n {!isUploading && !isFailed && (\n <button\n type=\"button\"\n onClick={onZoom}\n aria-label={`Zoom ${attachment.name}`}\n className=\"composer-chip-zoom\"\n >\n <ZoomIcon />\n </button>\n )}\n <button\n type=\"button\"\n onClick={onRemove}\n aria-label={`Remove ${attachment.name}`}\n // Remove stays available during upload/failure too — clicking it\n // is the user's \"cancel\" / \"retry from scratch\" gesture.\n className=\"composer-chip-remove\"\n data-visible={isUploading || isFailed ? \"\" : undefined}\n >\n <CloseIcon strokeWidth={2.5} />\n </button>\n </div>\n );\n }\n\n const KindIcon = attachment.kind === \"audio\" ? AudioIcon : FileIcon;\n const chip = slotProps(\n \"attachmentChip\",\n \"composer-chip composer-chip--file\",\n classNames,\n sx,\n );\n\n return (\n <div {...chip} data-failed={isFailed ? \"\" : undefined} title={titleText}>\n <span className=\"composer-chip-icon\" data-failed={isFailed ? \"\" : undefined}>\n {isUploading ? (\n <SpinnerIcon className=\"composer-spin\" />\n ) : isFailed ? (\n <WarningIcon />\n ) : (\n <KindIcon />\n )}\n </span>\n <span className=\"composer-chip-text\">\n <span className=\"composer-chip-name\">{attachment.name}</span>\n <span className=\"composer-chip-meta\" data-failed={isFailed ? \"\" : undefined}>\n {isUploading\n ? \"Uploading…\"\n : isFailed\n ? attachment.error || \"Upload failed\"\n : formatBytes(attachment.size)}\n </span>\n </span>\n <button\n type=\"button\"\n onClick={onRemove}\n aria-label={`Remove ${attachment.name}`}\n className=\"composer-chip-remove-inline\"\n >\n <CloseIcon />\n </button>\n </div>\n );\n}","import { useState } from \"react\";\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { AttachmentChip } from \"../ui/AttachmentChip\";\nimport { ImageLightbox } from \"../ui/ImageLightbox\";\nimport type { Attachment } from \"../types\";\n\n/** Renders attachment chips above the editor input. */\nexport function AttachmentTray() {\n const { attachments, removeAttachment, classNames, sx } = useComposerContext();\n const [zoom, setZoom] = useState<Attachment | null>(null);\n\n if (attachments.length === 0) return null;\n\n const tray = slotProps(\n \"attachmentTray\",\n \"composer-attachment-tray\",\n classNames,\n sx,\n );\n\n return (\n <>\n <div {...tray}>\n {attachments.map((att) => (\n <AttachmentChip\n key={att.id}\n attachment={att}\n onRemove={() => removeAttachment(att.id)}\n onZoom={att.kind === \"image\" ? () => setZoom(att) : undefined}\n />\n ))}\n </div>\n {zoom && zoom.previewUrl && (\n <ImageLightbox\n src={zoom.previewUrl}\n alt={zoom.name}\n onClose={() => setZoom(null)}\n />\n )}\n </>\n );\n}","import {\n cloneElement,\n isValidElement,\n useId,\n useRef,\n useState,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport { cn } from \"./cn\";\n\ntype Side = \"top\" | \"right\" | \"bottom\" | \"left\";\n\nexport interface TooltipProps {\n children: ReactNode;\n content: ReactNode;\n side?: Side;\n delay?: number;\n className?: string;\n}\n\n// `left`/`right` are interpreted as inline-start / inline-end so the tooltip\n// flips automatically under `dir=\"rtl\"`. The horizontal centring offsets stay\n// physical (`left-1/2 -translate-x-1/2`) — the result is direction-agnostic\n// because the centre line is the same in either writing mode.\nconst sideClasses: Record<Side, string> = {\n top: \"composer-tooltip--top\",\n bottom: \"composer-tooltip--bottom\",\n left: \"composer-tooltip--left\",\n right: \"composer-tooltip--right\",\n};\n\n/** Minimal tooltip inlined into the composer package. */\nexport function Tooltip({\n children,\n content,\n side = \"top\",\n delay = 150,\n className,\n}: TooltipProps) {\n const [open, setOpen] = useState(false);\n const id = useId();\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const show = () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n timerRef.current = setTimeout(() => setOpen(true), delay);\n };\n const hide = () => {\n if (timerRef.current) clearTimeout(timerRef.current);\n setOpen(false);\n };\n\n const trigger = isValidElement(children) ? (\n cloneElement(children as ReactElement<Record<string, unknown>>, {\n \"aria-describedby\": id,\n onMouseEnter: show,\n onMouseLeave: hide,\n onFocus: show,\n onBlur: hide,\n })\n ) : (\n <span\n tabIndex={0}\n aria-describedby={id}\n onMouseEnter={show}\n onMouseLeave={hide}\n onFocus={show}\n onBlur={hide}\n >\n {children}\n </span>\n );\n\n return (\n <span className=\"composer-tooltip-wrap\">\n {trigger}\n {open && (\n <span\n id={id}\n role=\"tooltip\"\n className={cn(\"composer-tooltip\", sideClasses[side], className)}\n >\n {content}\n </span>\n )}\n </span>\n );\n}","/**\n * VoicePlugin — toolbar mic button that captures voice input. Prefers the\n * Web Speech API for live transcription (Chromium, Safari); falls back to\n * MediaRecorder which posts the recorded clip as an audio attachment.\n *\n * - All capture APIs are accessed lazily — no permissions are requested\n * until the user actually presses the button.\n * - While recording: button shows a pulsing red dot and live elapsed time.\n */\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { Tooltip } from \"../internal/Tooltip\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport {\n $getSelection,\n $isRangeSelection,\n} from \"lexical\";\n\ntype RecState = \"idle\" | \"starting\" | \"recording\" | \"transcribing\";\n\ninterface SpeechRecognitionLike extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n onresult: ((ev: SpeechRecognitionEventLike) => void) | null;\n onerror: ((ev: Event) => void) | null;\n onend: (() => void) | null;\n}\n\ninterface SpeechRecognitionEventLike {\n results: ArrayLike<\n ArrayLike<{ transcript: string }> & { isFinal: boolean }\n >;\n resultIndex: number;\n}\n\nfunction getSpeechRecognition(): (new () => SpeechRecognitionLike) | null {\n const w = window as unknown as {\n SpeechRecognition?: new () => SpeechRecognitionLike;\n webkitSpeechRecognition?: new () => SpeechRecognitionLike;\n };\n return w.SpeechRecognition ?? w.webkitSpeechRecognition ?? null;\n}\n\nfunction formatSeconds(s: number): string {\n const mm = Math.floor(s / 60);\n const ss = s % 60;\n return `${mm}:${ss.toString().padStart(2, \"0\")}`;\n}\n\nexport function VoiceButton() {\n const [editor] = useLexicalComposerContext();\n const { addFiles, icons, classNames } = useComposerContext();\n const { voice: VoiceIcon, voiceRecording: VoiceRecordingIcon } = icons;\n const [state, setState] = useState<RecState>(\"idle\");\n const [elapsed, setElapsed] = useState(0);\n const recognitionRef = useRef<SpeechRecognitionLike | null>(null);\n const mediaRef = useRef<MediaRecorder | null>(null);\n const chunksRef = useRef<Blob[]>([]);\n const startedAtRef = useRef<number>(0);\n const tickerRef = useRef<number | null>(null);\n\n useEffect(() => {\n return () => {\n try {\n recognitionRef.current?.stop();\n } catch {\n // ignore\n }\n try {\n mediaRef.current?.stop();\n } catch {\n // ignore\n }\n if (tickerRef.current) window.clearInterval(tickerRef.current);\n };\n }, []);\n\n const startTicker = () => {\n startedAtRef.current = Date.now();\n setElapsed(0);\n if (tickerRef.current) window.clearInterval(tickerRef.current);\n tickerRef.current = window.setInterval(() => {\n setElapsed(Math.floor((Date.now() - startedAtRef.current) / 1000));\n }, 500);\n };\n\n const stopTicker = () => {\n if (tickerRef.current) {\n window.clearInterval(tickerRef.current);\n tickerRef.current = null;\n }\n };\n\n const insertText = useCallback(\n (text: string) => {\n editor.update(() => {\n const sel = $getSelection();\n if ($isRangeSelection(sel)) {\n sel.insertText(text);\n }\n });\n },\n [editor],\n );\n\n const startSpeech = (Recognition: new () => SpeechRecognitionLike) => {\n const rec = new Recognition();\n rec.continuous = false;\n rec.interimResults = true;\n rec.lang = navigator.language || \"en-US\";\n\n let finalBuffer = \"\";\n rec.onresult = (event) => {\n let interim = \"\";\n for (let i = event.resultIndex; i < event.results.length; i++) {\n const result = event.results[i];\n const transcript = result[0].transcript;\n if ((result as unknown as { isFinal: boolean }).isFinal) {\n finalBuffer += transcript;\n } else {\n interim += transcript;\n }\n }\n if (finalBuffer.trim().length > 0) {\n insertText(finalBuffer + (interim ? \"\" : \" \"));\n finalBuffer = \"\";\n }\n };\n rec.onerror = () => {\n stopTicker();\n setState(\"idle\");\n };\n rec.onend = () => {\n stopTicker();\n setState(\"idle\");\n };\n recognitionRef.current = rec;\n setState(\"recording\");\n startTicker();\n rec.start();\n };\n\n const startMediaRecorder = async () => {\n try {\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n const rec = new MediaRecorder(stream);\n chunksRef.current = [];\n rec.ondataavailable = (e) => {\n if (e.data.size > 0) chunksRef.current.push(e.data);\n };\n rec.onstop = () => {\n const blob = new Blob(chunksRef.current, { type: \"audio/webm\" });\n const file = new File([blob], `voice-${Date.now()}.webm`, {\n type: \"audio/webm\",\n });\n addFiles([file]);\n stream.getTracks().forEach((t) => t.stop());\n stopTicker();\n setState(\"idle\");\n };\n mediaRef.current = rec;\n rec.start();\n setState(\"recording\");\n startTicker();\n } catch {\n stopTicker();\n setState(\"idle\");\n }\n };\n\n const start = async () => {\n setState(\"starting\");\n const Recognition = getSpeechRecognition();\n if (Recognition) {\n try {\n startSpeech(Recognition);\n return;\n } catch {\n // fall through to MediaRecorder fallback\n }\n }\n await startMediaRecorder();\n };\n\n const stop = () => {\n setState(\"transcribing\");\n try {\n recognitionRef.current?.stop();\n } catch {\n // ignore\n }\n try {\n mediaRef.current?.stop();\n } catch {\n // ignore\n }\n };\n\n const isRecording = state === \"recording\" || state === \"starting\";\n\n return (\n <div className=\"composer-voice\">\n <Tooltip\n content={isRecording ? \"Stop recording\" : \"Voice input\"}\n side=\"top\"\n >\n <button\n type=\"button\"\n aria-label={isRecording ? \"Stop voice recording\" : \"Start voice input\"}\n aria-pressed={isRecording}\n onClick={() => (isRecording ? stop() : void start())}\n className={cn(\n \"composer-toolbar-btn composer-voice-btn\",\n classNames?.toolbarButton,\n )}\n >\n {state === \"transcribing\" ? (\n <VoiceRecordingIcon className=\"composer-spin\" />\n ) : (\n <VoiceIcon className={cn(isRecording && \"composer-pulse\")} />\n )}\n </button>\n </Tooltip>\n {isRecording && (\n <span className=\"composer-voice-timer\">\n <span className=\"composer-voice-dot composer-pulse\" />\n {formatSeconds(elapsed)}\n </span>\n )}\n </div>\n );\n}","/**\n * AttachmentTypePicker — the paperclip-as-popover variant of the toolbar's\n * attachment button. Used when the consumer supplies a non-empty\n * `attachments.types` list; otherwise the toolbar renders the plain\n * single-click paperclip instead.\n *\n * Interaction model:\n * - Click paperclip → opens a small dropdown menu listing the types.\n * - Click a type → closes the menu and opens the OS file picker\n * scoped to that type's `accept` value.\n * - Outside click / Escape / second paperclip click → closes the menu.\n * - Arrow keys + Enter / Space navigate and pick (a11y friendly).\n *\n * Positioning: the popover is `position: absolute` anchored to the\n * paperclip's wrapper. The toolbar lives at the bottom of the composer\n * card, so we open *upward* (`bottom-full`). Logical alignment (`start-0`)\n * keeps it on the toolbar side in both LTR and RTL.\n */\nimport { useCallback, useEffect, useId, useRef, useState } from \"react\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { IconComponent } from \"../internal/icons\";\nimport type { AttachmentTypeOption } from \"../types\";\n\ninterface Props {\n types: AttachmentTypeOption[];\n /** Forwarded to the hidden `<input type=file>`. */\n addFiles: (files: File[]) => void;\n /** Resolved className for the trigger button, from the slot system. */\n triggerClassName: string;\n /** Resolved inline style for the trigger button, from the slot system. */\n triggerStyle?: React.CSSProperties;\n /** Icon component the toolbar uses for the paperclip. */\n TriggerIcon: IconComponent;\n}\n\nexport function AttachmentTypePicker({\n types,\n addFiles,\n triggerClassName,\n triggerStyle,\n TriggerIcon,\n}: Props) {\n const { closeMenusOnOutsideClick } = useComposerContext();\n const [open, setOpen] = useState(false);\n const [activeIndex, setActiveIndex] = useState(0);\n\n const triggerRef = useRef<HTMLButtonElement | null>(null);\n const popoverRef = useRef<HTMLDivElement | null>(null);\n const fileInputRef = useRef<HTMLInputElement | null>(null);\n const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);\n\n const menuId = useId();\n\n const close = useCallback(() => setOpen(false), []);\n\n const triggerPicker = useCallback(\n (type: AttachmentTypeOption) => {\n const input = fileInputRef.current;\n if (!input) return;\n // Imperatively set accept so we don't have to round-trip through a\n // React re-render before clicking — keeps the dialog snappy.\n input.accept = type.accept;\n input.click();\n },\n [],\n );\n\n const pick = useCallback(\n (index: number) => {\n const type = types[index];\n if (!type) return;\n close();\n triggerRef.current?.focus();\n triggerPicker(type);\n },\n [types, close, triggerPicker],\n );\n\n // Outside click — honours the same global pref as the typeahead menus.\n useEffect(() => {\n if (!open || !closeMenusOnOutsideClick) return;\n const onPointerDown = (event: PointerEvent) => {\n const target = event.target as Node | null;\n if (!target) return;\n if (popoverRef.current?.contains(target)) return;\n if (triggerRef.current?.contains(target)) return;\n close();\n };\n document.addEventListener(\"pointerdown\", onPointerDown, true);\n return () =>\n document.removeEventListener(\"pointerdown\", onPointerDown, true);\n }, [open, closeMenusOnOutsideClick, close]);\n\n // Escape closes; arrow keys move the active row. We rebind on every open\n // so the listener captures the up-to-date `activeIndex` via the state\n // setter (not via a stale closure).\n useEffect(() => {\n if (!open) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === \"Escape\") {\n event.preventDefault();\n close();\n triggerRef.current?.focus();\n return;\n }\n if (event.key === \"ArrowDown\") {\n event.preventDefault();\n setActiveIndex((i) => (i + 1) % types.length);\n return;\n }\n if (event.key === \"ArrowUp\") {\n event.preventDefault();\n setActiveIndex((i) => (i - 1 + types.length) % types.length);\n return;\n }\n if (event.key === \"Home\") {\n event.preventDefault();\n setActiveIndex(0);\n return;\n }\n if (event.key === \"End\") {\n event.preventDefault();\n setActiveIndex(types.length - 1);\n return;\n }\n if (event.key === \"Enter\" || event.key === \" \") {\n // Only intercept if focus is inside the popover — otherwise the\n // user is typing in the editor and Enter must keep its normal\n // submit semantics.\n if (popoverRef.current?.contains(document.activeElement)) {\n event.preventDefault();\n pick(activeIndex);\n }\n }\n };\n document.addEventListener(\"keydown\", onKeyDown);\n return () => document.removeEventListener(\"keydown\", onKeyDown);\n }, [open, types.length, activeIndex, pick, close]);\n\n // Move keyboard focus onto the active row when the menu opens or the\n // active row changes via arrows. Mouse hover updates activeIndex without\n // stealing focus (we only call focus() when open transitions or on a key\n // event, not on hover).\n useEffect(() => {\n if (!open) return;\n itemRefs.current[activeIndex]?.focus();\n }, [open, activeIndex]);\n\n // When opening, reset to the first row. When closing, drop any picked\n // file off the input so the same file can be selected twice in a row.\n useEffect(() => {\n if (open) setActiveIndex(0);\n }, [open]);\n\n return (\n <div className=\"composer-attach-picker\">\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n hidden\n onChange={(e) => {\n const files = e.target.files;\n if (files && files.length > 0) addFiles(Array.from(files));\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n }}\n />\n <button\n ref={triggerRef}\n type=\"button\"\n aria-label=\"Attach file\"\n aria-haspopup=\"menu\"\n aria-expanded={open}\n aria-controls={open ? menuId : undefined}\n onClick={() => setOpen((o) => !o)}\n className={triggerClassName}\n style={triggerStyle}\n >\n <TriggerIcon />\n </button>\n\n {open && (\n <div\n ref={popoverRef}\n id={menuId}\n role=\"menu\"\n aria-label=\"Attachment types\"\n data-composer-popover=\"open\"\n className=\"composer-popover-in composer-attach-menu\"\n >\n {types.map((type, index) => {\n const active = index === activeIndex;\n return (\n <button\n key={type.id}\n ref={(el) => {\n itemRefs.current[index] = el;\n }}\n role=\"menuitem\"\n type=\"button\"\n tabIndex={active ? 0 : -1}\n data-active={active ? \"\" : undefined}\n onMouseEnter={() => setActiveIndex(index)}\n onClick={() => pick(index)}\n className=\"composer-attach-item\"\n >\n {type.icon ? (\n <span className=\"composer-attach-item-icon\">{type.icon}</span>\n ) : null}\n <span className=\"composer-attach-item-label\">{type.label}</span>\n {type.description ? (\n <span className=\"composer-attach-item-desc\">\n {type.description}\n </span>\n ) : null}\n </button>\n );\n })}\n </div>\n )}\n </div>\n );\n}","import { useRef, type ReactNode } from \"react\";\nimport { cn } from \"../internal/cn\";\nimport { slotProps } from \"../internal/sx\";\nimport { Tooltip } from \"../internal/Tooltip\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport { VoiceButton } from \"../plugins/VoicePlugin\";\nimport { AttachmentTypePicker } from \"./AttachmentTypePicker\";\n\ninterface Props {\n extras?: ReactNode;\n}\n\nconst TOOLBAR_BTN_BASE = \"composer-toolbar-btn\";\n\nexport function Toolbar({ extras }: Props) {\n const {\n features,\n attachmentsConfig,\n addFiles,\n webEnabled,\n toggleWeb,\n icons,\n classNames,\n sx,\n } = useComposerContext();\n const { attach: AttachIcon, image: ImageIcon, web: WebIcon } = icons;\n const fileInputRef = useRef<HTMLInputElement>(null);\n const imageInputRef = useRef<HTMLInputElement>(null);\n\n const attachmentsEnabled = !!features.attachments;\n // Per-picker toggles. `file` defaults to true (one-click paperclip);\n // `image` defaults to false (opt-in mobile camera-roll shortcut). Pass\n // `{ file: false }` to hide the paperclip, `{ image: true }` to add the\n // dedicated image picker.\n const showFileBtn = attachmentsEnabled && attachmentsConfig.file !== false;\n const showImageBtn = attachmentsEnabled && attachmentsConfig.image !== false;\n // When `types` is supplied, the paperclip flips into a popover trigger\n // that lets the user pre-pick the format before the OS dialog opens.\n const hasTypePicker =\n showFileBtn &&\n Array.isArray(attachmentsConfig.types) &&\n attachmentsConfig.types.length > 0;\n\n const toolbar = slotProps(\"toolbar\", \"composer-toolbar\", classNames, sx);\n const toolbarBtn = slotProps(\"toolbarButton\", TOOLBAR_BTN_BASE, classNames, sx);\n\n return (\n <div {...toolbar}>\n {showFileBtn && !hasTypePicker && (\n <>\n <input\n ref={fileInputRef}\n type=\"file\"\n multiple\n accept={attachmentsConfig.accept}\n hidden\n onChange={(e) => {\n const files = e.target.files;\n if (files) addFiles(Array.from(files));\n if (fileInputRef.current) fileInputRef.current.value = \"\";\n }}\n />\n <Tooltip content=\"Attach file\" side=\"top\">\n <button\n type=\"button\"\n aria-label=\"Attach file\"\n onClick={() => fileInputRef.current?.click()}\n {...toolbarBtn}\n >\n <AttachIcon />\n </button>\n </Tooltip>\n </>\n )}\n {hasTypePicker && attachmentsConfig.types && (\n <AttachmentTypePicker\n types={attachmentsConfig.types}\n addFiles={addFiles}\n triggerClassName={toolbarBtn.className ?? \"\"}\n triggerStyle={toolbarBtn.style}\n TriggerIcon={AttachIcon}\n />\n )}\n {showImageBtn && (\n <>\n <input\n ref={imageInputRef}\n type=\"file\"\n multiple\n accept=\"image/*\"\n hidden\n onChange={(e) => {\n const files = e.target.files;\n if (files) addFiles(Array.from(files));\n if (imageInputRef.current) imageInputRef.current.value = \"\";\n }}\n />\n <Tooltip content=\"Add image\" side=\"top\">\n <button\n type=\"button\"\n aria-label=\"Add image\"\n onClick={() => imageInputRef.current?.click()}\n {...toolbarBtn}\n >\n <ImageIcon />\n </button>\n </Tooltip>\n </>\n )}\n {features.voice && <VoiceButton />}\n {features.web && (\n <button\n type=\"button\"\n onClick={toggleWeb}\n aria-pressed={webEnabled}\n className={cn(\"composer-web-btn\", classNames?.toolbarButton)}\n >\n <WebIcon />\n Web\n </button>\n )}\n {extras}\n </div>\n );\n}","/**\n * SendButton — the affordance for \"submit\" and \"stop streaming\".\n *\n * Customization model (loosest → tightest control):\n *\n * 1. `icons.send` / `icons.stop` → swap just the SVG inside the\n * default chrome.\n * 2. `classNames.sendButton` / → append classes to the default\n * `classNames.stopButton` <button> element.\n * 3. `sx.sendButton` / `sx.stopButton` → token-driven inline styles on\n * the default <button>.\n * 4. `slots.sendButton` / → replace the entire element with\n * `slots.stopButton` the consumer's own component.\n * See `ComposerSlots` in types.ts.\n *\n * When a slot is provided, the resolved `className` / `style` from layers\n * 2 and 3 are still passed in — consumers can spread them for \"your DOM,\n * our theme\" or ignore them for a from-scratch design.\n */\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n canSend: boolean;\n isStreaming: boolean;\n onSend: () => void;\n onStop?: () => void;\n}\n\nexport function SendButton({ canSend, isStreaming, onSend, onStop }: Props) {\n const { icons, classNames, sx, slots } = useComposerContext();\n const { send: SendIcon, stop: StopIcon } = icons;\n\n if (isStreaming) {\n const stop = slotProps(\n \"stopButton\",\n \"composer-send-btn composer-send-btn--stop\",\n classNames,\n sx,\n );\n // Custom stop slot — bypass our default chrome entirely. We still\n // forward `onStop` (no-op safe via `?? noop` so the slot signature\n // never has to deal with `undefined`) and the resolved class/style so\n // the consumer can opt in to our theme tokens if they want.\n if (slots.stopButton) {\n const Slot = slots.stopButton;\n return (\n <Slot\n onStop={onStop ?? noop}\n className={stop.className}\n style={stop.style}\n />\n );\n }\n return (\n <button type=\"button\" onClick={onStop} aria-label=\"Stop generating\" {...stop}>\n <StopIcon />\n </button>\n );\n }\n const send = slotProps(\"sendButton\", \"composer-send-btn\", classNames, sx);\n // Custom send slot — same contract as the stop slot above. We pass\n // `canSend` rather than `disabled` so the consumer can use it for both\n // the DOM `disabled` attribute AND any other UI affordance (label\n // change, opacity, tooltip, etc.).\n if (slots.sendButton) {\n const Slot = slots.sendButton;\n return (\n <Slot\n canSend={canSend}\n onSend={onSend}\n className={send.className}\n style={send.style}\n />\n );\n }\n return (\n <button\n type=\"button\"\n onClick={onSend}\n disabled={!canSend}\n aria-label=\"Send message\"\n {...send}\n >\n <SendIcon strokeWidth={2.5} />\n </button>\n );\n}\n\n// Safe fallback so the slot signature doesn't have to make `onStop`\n// optional. `onStop` on `<Composer />` is optional — if the consumer\n// doesn't pass one, a click is a no-op (same as the default button).\nfunction noop() {}","import { useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { slotProps } from \"../internal/sx\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\ninterface Props {\n hint: boolean | ReactNode;\n}\n\nfunction Key({ children }: { children: ReactNode }) {\n return <kbd className=\"composer-kbd\">{children}</kbd>;\n}\n\n/** Render a shortcut spec like `\"mod+/\"` as a `<kbd>` chip the user can\n * recognise: `⌘/Ctrl + /`. Returns `null` if the spec doesn't have a\n * printable key, so the caller can skip the chip entirely. */\nfunction formatShortcut(spec: string): ReactNode {\n const parts = spec\n .split(\"+\")\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean);\n if (parts.length === 0) return null;\n const labels: string[] = [];\n for (const p of parts) {\n switch (p) {\n case \"mod\":\n labels.push(\"⌘/Ctrl\");\n break;\n case \"cmd\":\n case \"command\":\n case \"meta\":\n case \"win\":\n case \"super\":\n labels.push(\"⌘\");\n break;\n case \"ctrl\":\n case \"control\":\n labels.push(\"Ctrl\");\n break;\n case \"alt\":\n case \"option\":\n labels.push(\"Alt\");\n break;\n case \"shift\":\n labels.push(\"Shift\");\n break;\n default:\n labels.push(p.length === 1 ? p.toUpperCase() : p);\n }\n }\n return labels.join(\" + \");\n}\n\nexport function HintBar({ hint }: Props) {\n const {\n multiline,\n submitOnEnter,\n smartNewline,\n focusShortcut,\n classNames,\n sx,\n } = useComposerContext();\n\n // The default hint reflects whichever Enter behavior the composer is\n // actually wired up for, so a smart-newline composer doesn't lie to\n // the user about how to send. Consumers can still pass a custom node\n // via the `hint` prop to override entirely.\n const defaultShortcuts = useMemo(() => {\n if (!multiline) {\n if (!submitOnEnter) return null;\n return (\n <>\n Press <Key>Enter</Key> to send.\n </>\n );\n }\n if (smartNewline && submitOnEnter) {\n return (\n <>\n Press <Key>Enter</Key> to send a single line,{\" \"}\n <Key>⌘/Ctrl + Enter</Key> to send once you've started a new line.\n </>\n );\n }\n if (!submitOnEnter) {\n return (\n <>\n Press <Key>⌘/Ctrl + Enter</Key> to send, <Key>Enter</Key> for newline.\n </>\n );\n }\n return (\n <>\n Press <Key>Enter</Key> to send, <Key>Shift + Enter</Key> for newline.\n </>\n );\n }, [multiline, submitOnEnter, smartNewline]);\n\n const focusHint = useMemo(() => {\n if (!focusShortcut) return null;\n const label = formatShortcut(focusShortcut);\n if (!label) return null;\n return (\n <>\n {\" \"}\n <Key>{label}</Key> to jump back here.\n </>\n );\n }, [focusShortcut]);\n\n if (!hint) return null;\n const hintProps = slotProps(\"hint\", \"composer-hint\", classNames, sx);\n return (\n <p {...hintProps}>\n {hint === true ? (\n <>\n AI can make mistakes — verify important info.\n {defaultShortcuts ? (\n <span className=\"composer-hint-sm\"> {defaultShortcuts}</span>\n ) : null}\n {focusHint ? (\n <span className=\"composer-hint-md\">{focusHint}</span>\n ) : null}\n </>\n ) : (\n hint\n )}\n </p>\n );\n}","/**\n * QuickPrompts — a chip row of \"starter\" prompts rendered above the composer.\n *\n * Each chip click pipes through the provider's `runPrompt` channel; the\n * subscriber (registered by `ComposerInner`, which owns the editor state and\n * the submit function) then either:\n * - inserts the prompt into the editor (`behavior: \"initValue\"`) so the\n * user can edit it before sending, or\n * - inserts AND immediately submits (`behavior: \"sendValue\"`, default).\n *\n * Visible subset selection is stable per mount: with `randomize: true`\n * (default) the picked items are shuffled once via Fisher-Yates and then\n * frozen for the lifetime of the component, so the chips don't reshuffle on\n * every parent re-render.\n */\nimport { useMemo } from \"react\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport type { ComposerPromptsConfig } from \"../types\";\n\nconst DEFAULT_MAX = 3;\nconst HARD_CAP = 5;\n\ninterface Props {\n prompts: ComposerPromptsConfig;\n}\n\nfunction pickDisplay(\n items: string[],\n maxToShow: number | undefined,\n randomize: boolean | undefined,\n): string[] {\n const cleaned = items.filter((s) => typeof s === \"string\" && s.length > 0);\n if (cleaned.length === 0) return [];\n const max = Math.min(Math.max(1, maxToShow ?? DEFAULT_MAX), HARD_CAP);\n if (cleaned.length <= max) return cleaned;\n if (randomize === false) return cleaned.slice(0, max);\n // Fisher-Yates — uses Math.random; fine for UI selection (not security).\n const arr = [...cleaned];\n for (let i = arr.length - 1; i > 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [arr[i], arr[j]] = [arr[j], arr[i]];\n }\n return arr.slice(0, max);\n}\n\nexport function QuickPrompts({ prompts }: Props) {\n const { runPrompt, icons } = useComposerContext();\n const { sparkle: SparkleIcon } = icons;\n\n // Stable per mount. We DO want to re-pick if the consumer hands us a\n // brand-new items array (e.g. after fetching a fresh batch from the\n // server), so the array reference participates in the dep list.\n const display = useMemo(\n () => pickDisplay(prompts.items, prompts.maxToShow, prompts.randomize),\n [prompts.items, prompts.maxToShow, prompts.randomize],\n );\n\n if (display.length === 0) return null;\n\n const behavior = prompts.behavior ?? \"sendValue\";\n\n const handleClick = (prompt: string) => {\n prompts.onSelect?.(prompt);\n runPrompt(prompt, behavior);\n };\n\n return (\n <div role=\"group\" aria-label=\"Quick prompts\" className=\"composer-prompts\">\n {display.map((p) => (\n <button\n key={p}\n type=\"button\"\n onClick={() => handleClick(p)}\n title={p}\n className=\"composer-prompt\"\n >\n <SparkleIcon />\n <span className=\"composer-prompt-text\" style={{ maxWidth: \"32ch\" }}>\n {p}\n </span>\n </button>\n ))}\n </div>\n );\n}","import { useEffect, type Ref } from \"react\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport { $createParagraphNode, $getRoot } from \"lexical\";\nimport type { ComposerHandle } from \"../types\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\nimport {\n $insertTextWithParagraphBreaks,\n $seedInitialValue,\n} from \"../internal/insertText\";\n\nexport function useComposerHandle(\n ref: Ref<ComposerHandle> | undefined,\n onSubmit: () => void,\n) {\n const [editor] = useLexicalComposerContext();\n const { addFiles } = useComposerContext();\n\n useEffect(() => {\n if (!ref) return;\n const handle: ComposerHandle = {\n focus: () => editor.focus(),\n clear: () => {\n editor.update(() => {\n const root = $getRoot();\n root.clear();\n root.append($createParagraphNode());\n });\n },\n insert: (text) => {\n editor.update(() => {\n // Empty editor → seed from scratch so every line becomes its own\n // paragraph. Non-empty editor → insert at the current selection\n // (or end, if selection is detached) with `\\n` → paragraph\n // breaks, so multi-line blobs like a ```mermaid fence keep their\n // structure and the markdown detectors can see them.\n const root = $getRoot();\n const isEmpty =\n root.getChildrenSize() === 0 ||\n (root.getChildrenSize() === 1 &&\n root.getFirstChild()?.getTextContent() === \"\");\n if (isEmpty) {\n $seedInitialValue(text);\n } else {\n $insertTextWithParagraphBreaks(text);\n }\n });\n },\n submit: () => onSubmit(),\n addAttachments: (files) => addFiles(files),\n };\n if (typeof ref === \"function\") {\n ref(handle);\n return () => ref(null);\n }\n (ref as { current: ComposerHandle | null }).current = handle;\n return () => {\n (ref as { current: ComposerHandle | null }).current = null;\n };\n }, [editor, ref, onSubmit, addFiles]);\n}","/**\n * Tiny keyboard-shortcut parser used by `<Composer focusShortcut>` (and a\n * good fit for any future global shortcut the library wants to expose).\n *\n * Why bespoke instead of pulling in a library:\n * - We need ONE thing: parse a string like `\"mod+/\"` once, then test\n * `KeyboardEvent`s against it on every `keydown`. ~30 lines.\n * - Zero deps + zero bundle cost > matching the exact ergonomics of\n * `mousetrap` / `hotkeys-js`.\n *\n * Grammar (case-insensitive):\n * shortcut := segment (\"+\" segment)*\n * segment := modifier | key\n * modifier := \"mod\" | \"cmd\" | \"meta\" | \"ctrl\" | \"control\"\n * | \"alt\" | \"option\" | \"shift\"\n * key := any non-modifier token (single char, \"Enter\", \"Escape\",\n * \"ArrowUp\", \"/\", \"?\", …)\n *\n * `mod` resolves to ⌘ on macOS and Ctrl elsewhere — the \"do what the\n * platform expects\" modifier. `cmd` / `meta` / `ctrl` are explicit and\n * never aliased.\n *\n * Modifier matching is strict: a parsed `\"mod+/\"` only fires when the\n * platform mod IS down AND every other modifier (Shift, Alt, the\n * non-platform one) is NOT — so `Cmd+Shift+/` won't accidentally trigger\n * a `Cmd+/` shortcut.\n */\n\nconst MODIFIERS = new Set([\n \"mod\",\n \"cmd\",\n \"command\",\n \"meta\",\n \"win\",\n \"super\",\n \"ctrl\",\n \"control\",\n \"alt\",\n \"option\",\n \"shift\",\n]);\n\nexport interface ParsedShortcut {\n /** Required modifier flags after platform resolution. */\n mod: boolean; // mod === Cmd on mac, Ctrl elsewhere\n altMod: boolean; // the other one — Ctrl on mac, Cmd on Windows/Linux (only if explicitly named)\n shift: boolean;\n alt: boolean;\n /** Lower-cased key to match. Special keys keep their `KeyboardEvent.key` casing-folded. */\n key: string;\n}\n\nfunction isMac(): boolean {\n if (typeof navigator === \"undefined\") return false;\n // `userAgentData.platform` is the modern path; userAgent is the fallback.\n // We accept either \"macOS\" / \"Mac\" / \"iPhone\" / \"iPad\" so the shortcut\n // works on iPadOS too (where Cmd is still the natural mod).\n const platform =\n (navigator as Navigator & {\n userAgentData?: { platform?: string };\n }).userAgentData?.platform ?? navigator.platform ?? navigator.userAgent;\n return /mac|iphone|ipad|ipod/i.test(platform);\n}\n\n/**\n * Parse a shortcut string into a `ParsedShortcut`, or `null` if the input\n * is empty / invalid (so the caller can simply skip registering it).\n */\nexport function parseShortcut(spec: string): ParsedShortcut | null {\n const segments = spec\n .split(\"+\")\n .map((s) => s.trim().toLowerCase())\n .filter(Boolean);\n if (segments.length === 0) return null;\n\n const mac = isMac();\n let mod = false;\n let altMod = false;\n let shift = false;\n let alt = false;\n let key: string | null = null;\n\n for (const seg of segments) {\n if (MODIFIERS.has(seg)) {\n switch (seg) {\n case \"mod\":\n mod = true;\n break;\n case \"cmd\":\n case \"command\":\n case \"meta\":\n case \"win\":\n case \"super\":\n if (mac) mod = true;\n else altMod = true;\n break;\n case \"ctrl\":\n case \"control\":\n if (mac) altMod = true;\n else mod = true;\n break;\n case \"alt\":\n case \"option\":\n alt = true;\n break;\n case \"shift\":\n shift = true;\n break;\n }\n } else {\n // Last non-modifier wins — keeps `\"mod+/\"` and `\"/+mod\"` equivalent\n // even though only the former is the documented form.\n key = seg;\n }\n }\n\n if (!key) return null;\n return { mod, altMod, shift, alt, key };\n}\n\n/** Test a parsed shortcut against a `KeyboardEvent`. */\nexport function matchesShortcut(\n parsed: ParsedShortcut,\n event: KeyboardEvent,\n): boolean {\n const mac = isMac();\n const platformMod = mac ? event.metaKey : event.ctrlKey;\n const otherMod = mac ? event.ctrlKey : event.metaKey;\n\n if (parsed.mod !== platformMod) return false;\n if (parsed.altMod !== otherMod) return false;\n if (parsed.shift !== event.shiftKey) return false;\n if (parsed.alt !== event.altKey) return false;\n\n // Normalize the event key. Single-char keys are compared case-insensitively\n // (so `\"mod+K\"` and `\"mod+k\"` both match Shift-less ⌘K). Named keys\n // (Enter, Escape, ArrowUp, …) use their canonical lower-cased name.\n const eventKey = event.key.length === 1 ? event.key.toLowerCase() : event.key.toLowerCase();\n return eventKey === parsed.key;\n}","/**\n * `<Composer />` — the public chatbox component shipped by `composeai`.\n *\n * Design goals:\n * - Internally stateful (no `value`/`onChange` round-trip with the parent).\n * - Plugin-driven: every feature (markdown, attachments, slash, mentions,\n * mermaid, voice, web, ...) is an opt-in plugin behind `features`.\n * - Zero coupling to the host application; safe to publish to npm.\n * - The host only listens via `onSend(payload)` and optionally holds a\n * `ComposerHandle` ref for imperative control.\n *\n * Demos live in `src/showcase/pages/ComposerPage.tsx` and in the example\n * chat app under `src/app/` — neither belongs to the published library.\n */\nimport { forwardRef, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { LexicalComposer } from \"@lexical/react/LexicalComposer\";\nimport { useLexicalComposerContext } from \"@lexical/react/LexicalComposerContext\";\nimport type { InitialConfigType } from \"@lexical/react/LexicalComposer\";\nimport type { Klass, LexicalNode } from \"lexical\";\nimport {\n $createParagraphNode,\n $getRoot,\n ParagraphNode,\n} from \"lexical\";\nimport { $seedInitialValue } from \"./internal/insertText\";\nimport { cn } from \"./internal/cn\";\nimport { deriveColorTokens } from \"./internal/color\";\nimport { slotProps, tokensToStyle } from \"./internal/sx\";\nimport { ComposerProvider, useComposerContext } from \"./core/ComposerProvider\";\nimport { EditorShell } from \"./core/EditorShell\";\nimport { composerTheme } from \"./core/theme\";\nimport { MentionNode } from \"./core/nodes/MentionNode\";\nimport { MarkdownTokenNode } from \"./core/nodes/MarkdownTokenNode\";\nimport { BlockParagraphNode } from \"./core/nodes/BlockParagraphNode\";\nimport { LinkTextNode } from \"./core/nodes/LinkTextNode\";\nimport { collectPlainAndMentions, toMarkdown } from \"./core/serializer\";\nimport { KeyboardPlugin } from \"./plugins/KeyboardPlugin\";\nimport { AutoFocusPlugin } from \"./plugins/AutoFocusPlugin\";\nimport { PasteDropPlugin } from \"./plugins/PasteDropPlugin\";\nimport { MarkdownPlugin } from \"./plugins/MarkdownPlugin\";\nimport { MermaidPlugin } from \"./plugins/MermaidPlugin\";\nimport { SlashCommandPlugin } from \"./plugins/SlashCommandPlugin\";\nimport { MentionPlugin } from \"./plugins/MentionPlugin\";\nimport { GhostedAutoCompletePlugin } from \"./plugins/GhostedAutoCompletePlugin\";\nimport { AttachmentTray } from \"./plugins/AttachmentTray\";\nimport { Toolbar } from \"./ui/Toolbar\";\nimport { SendButton } from \"./ui/SendButton\";\nimport { HintBar } from \"./ui/HintBar\";\nimport { QuickPrompts } from \"./ui/QuickPrompts\";\nimport { useComposerHandle } from \"./hooks/useComposerHandle\";\nimport { parseShortcut, matchesShortcut } from \"./internal/shortcut\";\nimport { focusEditor } from \"./internal/focusEditor\";\nimport type { ComposerHandle, ComposerProps, ComposerSubmitPayload } from \"./types\";\n\n/**\n * ComposeAI — a Lexical-powered, plugin-driven rich input designed for\n * chat / AI assistant interfaces. Internally stateful: parents only listen via\n * `onSend` and (optionally) hold an imperative `ref`.\n */\nexport const Composer = forwardRef<ComposerHandle, ComposerProps>(function Composer(\n props,\n ref,\n) {\n const {\n placeholder = \"Send a message…\",\n onSend,\n onStop,\n isStreaming,\n autoFocus,\n refocusOnSubmit = true,\n focusShortcut = \"mod+/\",\n initialValue,\n className,\n classNames,\n sx,\n style,\n tokens,\n color,\n hint = true,\n features,\n toolbarExtras,\n closeMenusOnOutsideClick = true,\n mode = \"markdown\",\n multiline = true,\n submitOnEnter = true,\n smartNewline = true,\n icons,\n slots,\n renderDiagram,\n prompts,\n attachmentOptions,\n dir,\n } = props;\n\n // `color` is a brand-colour shorthand: derive primary/accent/ring from\n // a single value, then layer the consumer's explicit `tokens` on top so\n // they always win.\n const tokenStyle = useMemo(() => {\n const derived = color ? deriveColorTokens(color) : null;\n if (!derived && !tokens) return undefined;\n return tokensToStyle({ ...derived, ...tokens });\n }, [color, tokens]);\n const root = slotProps(\"root\", \"composer-root\", classNames, sx);\n const rootStyle = useMemo(\n () => ({ ...tokenStyle, ...root.style, ...style }),\n [tokenStyle, root.style, style],\n );\n\n return (\n <ComposerProvider\n features={features}\n isStreaming={isStreaming}\n closeMenusOnOutsideClick={closeMenusOnOutsideClick}\n attachmentOptions={attachmentOptions}\n mode={mode}\n multiline={multiline}\n submitOnEnter={submitOnEnter}\n smartNewline={smartNewline}\n focusShortcut={focusShortcut}\n icons={icons}\n slots={slots}\n renderDiagram={renderDiagram}\n dir={dir}\n classNames={classNames}\n sx={sx}\n tokenStyle={tokenStyle}\n >\n <div\n dir={dir}\n data-composer-scope=\"\"\n className={cn(root.className, className)}\n style={Object.keys(rootStyle).length ? rootStyle : undefined}\n >\n {prompts && prompts.items.length > 0 ? (\n <QuickPrompts prompts={prompts} />\n ) : null}\n <ComposerCard\n placeholder={placeholder}\n initialValue={initialValue}\n handleRef={ref}\n onSend={onSend}\n onStop={onStop}\n autoFocus={autoFocus}\n refocusOnSubmit={refocusOnSubmit}\n focusShortcut={focusShortcut}\n isStreaming={!!isStreaming}\n toolbarExtras={toolbarExtras}\n mode={mode}\n multiline={multiline}\n />\n <HintBar hint={hint} />\n </div>\n </ComposerProvider>\n );\n});\n\ninterface CardProps {\n placeholder: string;\n initialValue?: string;\n handleRef: React.ForwardedRef<ComposerHandle>;\n onSend?: ComposerProps[\"onSend\"];\n onStop?: ComposerProps[\"onStop\"];\n autoFocus?: boolean;\n refocusOnSubmit: boolean;\n focusShortcut: ComposerProps[\"focusShortcut\"];\n isStreaming: boolean;\n toolbarExtras: ComposerProps[\"toolbarExtras\"];\n mode: NonNullable<ComposerProps[\"mode\"]>;\n /** `false` switches the card to the single-line / inline layout. */\n multiline: boolean;\n}\n\n// Slack-style: every visible block is a styled paragraph. In `live` markdown\n// mode the paragraph also remembers a hidden block marker (e.g. `\"# \"`) via\n// `BlockParagraphNode` — registered as a node-replacement so any\n// `$createParagraphNode()` (called by Lexical's internals and our own code)\n// mints our subclass instead.\nconst BLOCK_PARAGRAPH_REPLACEMENT = {\n replace: ParagraphNode,\n with: () => new BlockParagraphNode(),\n withKlass: BlockParagraphNode,\n};\nconst RICH_NODES: InitialConfigType[\"nodes\"] = [\n MentionNode,\n MarkdownTokenNode,\n BlockParagraphNode,\n LinkTextNode,\n BLOCK_PARAGRAPH_REPLACEMENT,\n];\n// Plain-text mode only needs paragraphs (built-in) and mentions — the rest is\n// intentionally absent so pasted rich content collapses to plain text.\nconst PLAIN_NODES: Array<Klass<LexicalNode>> = [MentionNode];\n\nfunction ComposerCard({\n placeholder,\n initialValue,\n handleRef,\n onSend,\n onStop,\n autoFocus,\n refocusOnSubmit,\n focusShortcut,\n isStreaming,\n toolbarExtras,\n mode,\n multiline,\n}: CardProps) {\n const { webEnabled, isDraggingFiles, classNames, sx } = useComposerContext();\n const card = slotProps(\"card\", \"composer-card\", classNames, sx);\n\n // LexicalComposer must wrap everything that touches editor state, including\n // the toolbar and send button (so they can `useLexicalComposerContext()`).\n // Living here — one level above EditorShell — also means the inline layout\n // can place those siblings into the same flex row as the editor block.\n const initialConfig: InitialConfigType = useMemo(\n () => ({\n namespace: \"composeai\",\n theme: composerTheme,\n onError: (error) => {\n console.error(\"[Composer]\", error);\n },\n nodes: mode === \"markdown\" ? RICH_NODES : PLAIN_NODES,\n editorState: initialValue ? undefined : null,\n }),\n [mode, initialValue],\n );\n\n return (\n <div\n data-composer-root=\"\"\n data-composer-inline={multiline ? undefined : \"\"}\n data-composer-web={webEnabled ? \"\" : undefined}\n data-composer-dragging={isDraggingFiles ? \"\" : undefined}\n {...card}\n >\n <div\n aria-hidden\n data-composer-overlay=\"\"\n className=\"composer-overlay-glow\"\n style={{\n background:\n \"linear-gradient(135deg, hsl(var(--primary)/0.08) 0%, transparent 40%, hsl(var(--primary)/0.06) 100%)\",\n }}\n />\n {isDraggingFiles && (\n <div\n aria-hidden\n data-composer-overlay=\"\"\n className=\"composer-overlay-drop\"\n >\n Drop to attach\n </div>\n )}\n <LexicalComposer initialConfig={initialConfig}>\n <ComposerInner\n placeholder={placeholder}\n mode={mode}\n multiline={multiline}\n handleRef={handleRef}\n onSend={onSend}\n onStop={onStop}\n autoFocus={autoFocus}\n refocusOnSubmit={refocusOnSubmit}\n focusShortcut={focusShortcut}\n isStreaming={isStreaming}\n toolbarExtras={toolbarExtras}\n initialValue={initialValue}\n />\n </LexicalComposer>\n </div>\n );\n}\n\ninterface InnerProps {\n placeholder: string;\n mode: NonNullable<ComposerProps[\"mode\"]>;\n multiline: boolean;\n handleRef: React.ForwardedRef<ComposerHandle>;\n onSend?: ComposerProps[\"onSend\"];\n onStop?: ComposerProps[\"onStop\"];\n autoFocus?: boolean;\n refocusOnSubmit: boolean;\n focusShortcut: ComposerProps[\"focusShortcut\"];\n isStreaming: boolean;\n toolbarExtras: ComposerProps[\"toolbarExtras\"];\n initialValue?: string;\n}\n\nfunction ComposerInner({\n placeholder,\n mode,\n multiline,\n handleRef,\n onSend,\n onStop,\n autoFocus,\n refocusOnSubmit,\n focusShortcut,\n isStreaming,\n toolbarExtras,\n initialValue,\n}: InnerProps) {\n const [editor] = useLexicalComposerContext();\n const {\n features,\n attachments,\n clearAttachments,\n registerRunPrompt,\n attachmentOptions,\n } = useComposerContext();\n const canSendOnlyAttachment = attachmentOptions.canSendOnlyAttachment !== false;\n const hasUploadingAttachment = attachments.some((a) => a.status === \"uploading\");\n const hasFailedAttachment = attachments.some((a) => a.status === \"failed\");\n const uploadsBlocking = hasUploadingAttachment || hasFailedAttachment;\n const markdownEnabled = mode === \"markdown\" && features.markdown;\n const [hasText, setHasText] = useState<boolean>(\n !!initialValue && initialValue.trim().length > 0,\n );\n\n const onSendRef = useRef(onSend);\n onSendRef.current = onSend;\n const refocusOnSubmitRef = useRef(refocusOnSubmit);\n refocusOnSubmitRef.current = refocusOnSubmit;\n\n const submit = useCallback(() => {\n if (isStreaming) return;\n // Block while uploads are pending or have failed — the user has visible\n // chips telling them what's going on; sending mid-flight would lose the\n // attachments. Failed chips also block until the user removes them\n // (re-attaching the same file is the retry path).\n if (uploadsBlocking) return;\n let payload: ComposerSubmitPayload | null = null;\n editor.getEditorState().read(() => {\n const { text, mentions } = collectPlainAndMentions(editor);\n const markdown = toMarkdown(editor);\n const trimmed = text.trim();\n // Always require *something* to send. Attachments-only is allowed by\n // default; `canSendOnlyAttachment: false` flips that off — the user\n // must write at least one character even if files are attached.\n if (!trimmed) {\n if (attachments.length === 0) return;\n if (!canSendOnlyAttachment) return;\n }\n payload = {\n text: trimmed,\n markdown,\n attachments: [...attachments],\n mentions,\n };\n });\n if (!payload) return;\n onSendRef.current?.(payload);\n // Focus management is bundled INTO the editor.update via `onUpdate`,\n // which fires after Lexical commits the mutation AND its reconciler\n // has applied selection. If we ran focus/blur before then (as a\n // sibling statement after `editor.update`), the selection\n // restoration on the freshly-cleared root would resurrect focus on\n // the contenteditable and silently undo a blur we just performed.\n //\n // Reads are via refs so prop changes don't churn this callback:\n // - `refocusOnSubmit: true` → explicitly focus the editor. Covers\n // Send-button clicks, `sendValue` quick-prompts, and imperative\n // `ref.submit()`. Keyboard sends already keep focus implicitly,\n // so the call is a harmless no-op for them.\n // - `refocusOnSubmit: false` → explicitly BLUR the root element so\n // the prop is symmetric across triggers: clicking Send leaves\n // focus where it naturally went (the button), and pressing Enter\n // removes focus from the editor instead of letting it linger.\n editor.update(\n () => {\n const root = $getRoot();\n root.clear();\n root.append($createParagraphNode());\n },\n {\n onUpdate: () => {\n if (refocusOnSubmitRef.current) {\n focusEditor(editor);\n } else {\n const root = editor.getRootElement();\n if (root) root.blur();\n }\n },\n },\n );\n clearAttachments();\n }, [\n editor,\n attachments,\n clearAttachments,\n isStreaming,\n canSendOnlyAttachment,\n uploadsBlocking,\n ]);\n\n useComposerHandle(handleRef, submit);\n\n // Global focus shortcut (Cmd/Ctrl+/ by default). Configurable via\n // `focusShortcut`; pass `false` / `null` / `\"\"` to disable entirely.\n // Registered on `window` because the whole point is to grab focus from\n // anywhere on the page — including from inside other inputs that don't\n // know about us.\n useEffect(() => {\n if (!focusShortcut) return;\n const parsed = parseShortcut(focusShortcut);\n if (!parsed) return;\n const onKey = (e: KeyboardEvent) => {\n if (!matchesShortcut(parsed, e)) return;\n // `defaultPrevented` lets a more-local handler (e.g. a popover) win\n // when both are bound to the same combo. We never compete with a\n // child that already consumed the key.\n if (e.defaultPrevented) return;\n e.preventDefault();\n focusEditor(editor);\n };\n window.addEventListener(\"keydown\", onKey);\n return () => window.removeEventListener(\"keydown\", onKey);\n }, [editor, focusShortcut]);\n\n // Seed initial value once on mount. Splits on `\\n` so each line becomes\n // its own paragraph — required for the per-paragraph markdown / mermaid\n // detectors to recognise multi-line blocks (e.g. a ```mermaid fence).\n const seededRef = useRef(false);\n useEffect(() => {\n if (seededRef.current) return;\n seededRef.current = true;\n if (!initialValue) return;\n editor.update(() => {\n $seedInitialValue(initialValue);\n });\n }, [editor, initialValue]);\n\n useEffect(() => {\n return editor.registerUpdateListener(() => {\n editor.getEditorState().read(() => {\n const text = $getRoot().getTextContent().trim();\n setHasText(text.length > 0);\n });\n });\n }, [editor]);\n\n // Quick-prompts bridge: the chip row lives above the editor so it doesn't\n // own the editor state or the submit function. It pipes its clicks through\n // the provider; we subscribe here to do the actual work. We deliberately\n // *replace* whatever is in the editor — `initValue` means \"use this as the\n // starting point\", which is unambiguous (and matches every other quick-\n // prompt UX I've seen).\n useEffect(() => {\n return registerRunPrompt((prompt, behavior) => {\n editor.update(() => {\n $seedInitialValue(prompt);\n });\n if (behavior === \"sendValue\") {\n // Defer to the next microtask so Lexical commits the update above\n // before `submit` reads the editor state. Without this, `submit`\n // would serialize the *previous* state and ignore the prompt.\n queueMicrotask(() => submit());\n } else {\n focusEditor(editor);\n }\n });\n }, [editor, registerRunPrompt, submit]);\n\n const toolbarSlot = <Toolbar extras={toolbarExtras} />;\n const sendButtonSlot = (\n <SendButton\n canSend={\n // Same gate as `submit`, kept in sync so the disabled state is\n // never out of step with what would actually happen on click.\n !uploadsBlocking &&\n (hasText || (attachments.length > 0 && canSendOnlyAttachment))\n }\n isStreaming={isStreaming}\n onSend={submit}\n onStop={onStop}\n />\n );\n\n return (\n <>\n <EditorShell\n placeholder={placeholder}\n mode={mode}\n multiline={multiline}\n header={<AttachmentTray />}\n toolbar={toolbarSlot}\n sendButton={sendButtonSlot}\n // Inline mode can't form a ```mermaid fence (no newlines), so we\n // skip the slot entirely — saves a mount and a `<MermaidPlugin>`\n // subscription, and keeps the card visually a single bar.\n footer={multiline ? <MermaidSlot /> : null}\n />\n\n <KeyboardPlugin onSubmit={submit} />\n <AutoFocusPlugin enabled={!!autoFocus} />\n <PasteDropPlugin />\n {markdownEnabled && <MarkdownPlugin />}\n {features.slashCommands && (\n <SlashCommandPlugin\n config={features.slashCommands}\n onSubmit={submit}\n />\n )}\n {features.mentions && <MentionPlugin config={features.mentions} />}\n {features.ghostedAutoComplete && (\n <GhostedAutoCompletePlugin config={features.ghostedAutoComplete} />\n )}\n </>\n );\n}\n\nfunction MermaidSlot() {\n const { features, mode } = useComposerContext();\n if (mode !== \"markdown\" || !features.mermaid) return null;\n return <MermaidPlugin />;\n}","import { cn } from \"../internal/cn\";\nimport { useComposerContext } from \"../core/ComposerProvider\";\n\nexport interface SuggestionRowProps {\n /** Suggestion labels. Clicking one calls `onSelect` with that string. */\n items: string[];\n onSelect: (value: string) => void;\n className?: string;\n}\n\nexport function SuggestionRow({ items, onSelect, className }: SuggestionRowProps) {\n const { icons } = useComposerContext();\n const { sparkle: SparkleIcon } = icons;\n return (\n <div className={cn(\"composer-suggestions\", className)}>\n {items.map((s) => (\n <button\n key={s}\n type=\"button\"\n onClick={() => onSelect(s)}\n className=\"composer-suggestion\"\n >\n <SparkleIcon />\n {s}\n </button>\n ))}\n </div>\n );\n}"]}
|