{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "rich-text",
  "title": "Rich text editor",
  "author": "superzero11 <https://github.com/superzero11/uiset>",
  "description": "A rich text editor on UI SDK with no editor library: headings, nested and numbered lists, to-dos, quotes, code, links, mentions, dividers and images; a toolbar, Markdown as you type, \"/\" for blocks and \"@\" for people (TriggerMenu); safe paste from documents and the web; undo; Markdown and clean HTML out; agents read and write Markdown.",
  "dependencies": [
    "@ui-sdk/core@0.1.0-beta.5",
    "@ui-sdk/react@0.1.0-beta.5"
  ],
  "registryDependencies": [
    "https://uiset.dev/r/uiset.json",
    "https://uiset.dev/r/button.json",
    "https://uiset.dev/r/field.json",
    "https://uiset.dev/r/popover.json",
    "https://uiset.dev/r/select.json",
    "https://uiset.dev/r/toggle.json",
    "https://uiset.dev/r/toolbar.json",
    "https://uiset.dev/r/trigger-menu.json"
  ],
  "files": [
    {
      "path": "registry/uiset/ui/rich-text.tsx",
      "content": "\"use client\"\n\nimport { ariaKeyshortcuts } from \"@ui-sdk/core\"\nimport { usePart, usePrimitive } from \"@ui-sdk/react/primitive\"\nimport type { EditorChange, TextEditorAdapter } from \"@ui-sdk/core/trigger-menu\"\nimport { createElement, Fragment, useCallback, useEffect, useId, useMemo, useRef, useState, type ReactNode } from \"react\"\nimport { Button } from \"./button\"\nimport { Field, FieldLabel, Input } from \"./field\"\nimport { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from \"./popover\"\nimport { Select, SelectContent, SelectItem, SelectLabel, SelectTrigger, SelectValue } from \"./select\"\nimport { Icon } from \"./shell/icons\"\nimport { Toggle } from \"./toggle\"\nimport { Toolbar, ToolbarButton, ToolbarSeparator } from \"./toolbar\"\nimport { TriggerMenu, TriggerMenuContent, TriggerMenuItem, TriggerMenuList, type TriggerMenuDataItem } from \"./trigger-menu\"\nimport {\n  activeBlock,\n  activeLink,\n  block,\n  blockLength,\n  caret,\n  collapsed,\n  counts,\n  createState,\n  deleteSelection,\n  insertBlock,\n  isMention,\n  linkRange,\n  markActive,\n  sameDoc,\n  sanitizeDoc,\n  select,\n  setBlock,\n  setLink,\n  type Block,\n  type Doc,\n  type EditorState,\n  type Inline,\n  type Selection,\n} from \"./rich-text/model\"\nimport { blockOptions, blockOptionType, blockOptionValue, defaultCommands, listButtons, markButtons, type RichTextCommand as Command } from \"./rich-text/commands\"\nimport { richTextPrimitive } from \"./rich-text/primitive\"\nimport { applyMarkdown, fromMarkdown, toHTML, toMarkdown } from \"./rich-text/serialize\"\nimport { blockLabel, createRichTextView, type RichTextMessages, type RichTextView } from \"./rich-text/view\"\nimport \"./rich-text/rich-text.css\"\n\n// A rich text editor on UI SDK: a toolbar (UI SDK's Toolbar, Toggles, Select and Popover),\n// \"/\" to insert blocks and \"@\" to mention people (UI SDK's TriggerMenu, through an editor\n// adapter), Markdown as you type, paste from documents and the web, undo, and a value agents\n// read and set as Markdown. The editing itself is rich-text/view.ts and model.ts, shared\n// with the web element.\n\ntype Person = { value: string; label: string }\n\ntype RichTextEditorProps = {\n  /** The editor's name for people and agents, like \"Release notes\". */\n  label: string\n  /** Markdown, or a document from an earlier `onValueChange`. */\n  defaultValue?: string | Doc\n  /** A controlled document: pass back what `onValueChange` gives you. */\n  value?: Doc\n  onValueChange?: (doc: Doc) => void\n  placeholder?: string\n  readOnly?: boolean\n  disabled?: boolean\n  /** The toolbar above the text. On by default. */\n  toolbar?: boolean\n  /** People \"@\" can mention. Without them, \"@\" is just a character. */\n  mentions?: Person[]\n  /** What \"/\" offers; the defaults insert blocks. Pass [] to turn \"/\" off. */\n  commands?: Command[]\n  /** Mod+Enter, outside a to-do item. */\n  onSubmit?: () => void\n  /** Pasted, dropped or chosen images: upload them and say where they live. */\n  uploadImage?: (file: File) => Promise<{ src: string; alt?: string } | null>\n  /** For a form: the field name, and whether its value is HTML (default) or Markdown. */\n  name?: string\n  format?: \"html\" | \"markdown\"\n  /** Shows a count; going over is allowed but marked, so nothing typed is lost. */\n  maxLength?: number\n  messages?: Partial<RichTextMessages>\n  className?: string\n}\n\nfunction initialDoc(value: string | Doc | undefined): Doc {\n  if (value === undefined) return createState().doc\n  return typeof value === \"string\" ? fromMarkdown(value) : value\n}\n\nfunction RichTextEditor({\n  label,\n  defaultValue,\n  value,\n  onValueChange,\n  placeholder,\n  readOnly = false,\n  disabled = false,\n  toolbar = true,\n  mentions,\n  commands = defaultCommands,\n  onSubmit,\n  uploadImage,\n  name,\n  format = \"html\",\n  maxLength,\n  messages,\n  className,\n}: RichTextEditorProps) {\n  const root = useRef<HTMLDivElement | null>(null)\n  const viewRef = useRef<RichTextView | null>(null)\n  const [view, setView] = useState<RichTextView | null>(null)\n  const [state, setState] = useState<EditorState>(() => createState(initialDoc(value ?? defaultValue)))\n  const [linkOpen, setLinkOpen] = useState(false)\n  const latest = useRef({ state, onValueChange, onSubmit, uploadImage, messages, locked: readOnly || disabled })\n  latest.current = { ...latest.current, onValueChange, onSubmit, uploadImage, messages, locked: readOnly || disabled }\n  const markdown = useMemo(() => toMarkdown(state.doc), [state.doc])\n  const countId = useId()\n\n  const handle = usePrimitive(richTextPrimitive, {\n    value: markdown,\n    readOnly,\n    disabled,\n    // An agent's setValue, insert or clear: the editor takes the Markdown as one undo step.\n    onValueChange: (next) => {\n      const view = viewRef.current\n      if (!view) return\n      const doc = applyMarkdown(view.state.doc, next)\n      if (doc !== view.state.doc) view.run(() => ({ doc, selection: null, stored: null }), \"input\")\n    },\n  })\n\n  // The \"/\" and \"@\" menus talk to the editor through this adapter. It exists from the first\n  // render, so the text box keeps its place in the tree when the view arrives.\n  const adapterListeners = useRef(new Set<(change: EditorChange) => void>())\n  const adapter = useMemo<TextEditorAdapter>(\n    () => ({\n      get element() {\n        return viewRef.current?.adapter.element ?? root.current ?? undefined\n      },\n      textBefore: (length) => viewRef.current?.adapter.textBefore(length) ?? null,\n      selection: () => viewRef.current?.adapter.selection() ?? null,\n      rectAt: (offset) => viewRef.current?.adapter.rectAt(offset) ?? null,\n      replace: (range, content, options) => viewRef.current?.adapter.replace(range, content, options),\n      subscribe: (listener) => {\n        adapterListeners.current.add(listener)\n        return () => adapterListeners.current.delete(listener)\n      },\n      composing: () => viewRef.current?.adapter.composing() ?? false,\n      tokens: true,\n      submit: (event) => viewRef.current?.adapter.submit?.(event),\n    }),\n    [],\n  )\n\n  // The view owns the text box's children; React renders none into it.\n  const attach = useCallback((el: HTMLDivElement | null) => {\n    if (!el) return\n    const { uploadImage: upload } = latest.current\n    const created = createRichTextView(el, {\n      state: latest.current.state,\n      messages: latest.current.messages,\n      uploadImage: upload ? (file) => latest.current.uploadImage?.(file) ?? Promise.resolve(null) : undefined,\n      onSubmit: () => latest.current.onSubmit?.(),\n      onLinkRequest: () => setLinkOpen(true),\n      onChange: (next, reason) => {\n        latest.current.state = next\n        setState(next)\n        if (reason !== \"selection\") latest.current.onValueChange?.(next.doc)\n      },\n    })\n    const off = created.adapter.subscribe((change) => adapterListeners.current.forEach((listener) => listener(change)))\n    created.setReadOnly(latest.current.locked)\n    viewRef.current = created\n    setView(created)\n    return () => {\n      off()\n      created.destroy()\n      if (viewRef.current === created) viewRef.current = null\n    }\n  }, [])\n\n  const setRoot = useCallback(\n    (el: HTMLDivElement | null) => {\n      root.current = el\n      return attach(el)\n    },\n    [attach],\n  )\n\n  useEffect(() => view?.setReadOnly(readOnly || disabled), [view, readOnly, disabled])\n\n  // A controlled document from outside (a reset, a server copy) replaces what's shown.\n  useEffect(() => {\n    if (!view || value === undefined || sameDoc(value, view.state.doc)) return\n    view.set(createState(value))\n    latest.current.state = view.state\n    setState(view.state)\n  }, [view, value])\n\n  const count = useMemo(() => (maxLength ? counts(state.doc).characters : 0), [maxLength, state.doc])\n\n  const editable = usePart(\n    handle,\n    \"root\",\n    {},\n    {\n      ref: setRoot,\n      \"aria-label\": label,\n      \"aria-describedby\": maxLength ? countId : undefined,\n      \"aria-disabled\": disabled || undefined,\n      \"aria-placeholder\": placeholder,\n      className: \"rich-text-content\",\n    },\n  )\n\n  const triggers = [\n    ...(commands.length ? [{ char: \"/\", boundary: \"start\" as const, items: commands.map(({ value, label }) => ({ value, label })) }] : []),\n    ...(mentions?.length ? [{ char: \"@\", type: \"mention\", items: mentions }] : []),\n  ]\n  const described = new Map(commands.map((c) => [c.value, c]))\n\n  return (\n    <div className={[\"rich-text\", className].filter(Boolean).join(\" \")} data-disabled={disabled || undefined} data-readonly={readOnly || undefined}>\n      {toolbar && view && !readOnly && (\n        <RichTextToolbar view={view} state={state} label={label} linkOpen={linkOpen} onLinkOpenChange={setLinkOpen} uploadImage={uploadImage} disabled={disabled} />\n      )}\n      {/* Always the same tree: mentions arriving later never remount the text box. */}\n      {(\n        <TriggerMenu\n          editor={adapter}\n          triggers={triggers}\n          onSelect={(chosen: string, details) => {\n            if (details.trigger !== \"/\") return\n            // A command runs instead of inserting its name: the \"/\" and query go first.\n            details.preventDefault()\n            const command = described.get(chosen)\n            if (!command || !view) return\n            view.run((s) => {\n              const at = s.selection?.focus.block ?? 0\n              const cleared = deleteSelection(select(s, { anchor: { block: at, offset: details.match.start }, focus: { block: at, offset: details.match.end } }))\n              return command.run(cleared)\n            })\n          }}\n        >\n          {editable}\n          {/* With nothing matching, the menu closes, so Enter makes a new line as usual. */}\n          <TriggerMenuContent className=\"rich-text-menu\">\n            <TriggerMenuList>\n              {(menu) =>\n                (menu.items as TriggerMenuDataItem[]).map((item) => {\n                  const command = described.get(item.value as string)\n                  return (\n                    <TriggerMenuItem key={item.value as string} value={item.value} label={item.label}>\n                      {command?.icon ? (\n                        <Icon name={command.icon} />\n                      ) : command?.glyph ? (\n                        <span className=\"rich-text-menu-glyph\" aria-hidden=\"true\">\n                          {command.glyph}\n                        </span>\n                      ) : null}\n                      <span className=\"rich-text-menu-text\">\n                        <span>{item.label}</span>\n                        {command?.description && <span className=\"rich-text-menu-hint\">{command.description}</span>}\n                      </span>\n                    </TriggerMenuItem>\n                  )\n                })\n              }\n            </TriggerMenuList>\n          </TriggerMenuContent>\n        </TriggerMenu>\n      )}\n      {maxLength ? (\n        <p id={countId} className=\"rich-text-count\" data-over={count > maxLength || undefined}>\n          {count > maxLength ? `${count - maxLength} over the limit of ${maxLength} characters` : `${count} / ${maxLength} characters`}\n        </p>\n      ) : null}\n      {name && <input type=\"hidden\" name={name} value={format === \"markdown\" ? markdown : toHTML(state.doc)} />}\n    </div>\n  )\n}\n\n/* ------------------------------------------------------------------ Toolbar */\n\n/** Keeps the editor's selection while a toolbar control is pressed with a pointer. */\nconst keepSelection = { onMouseDown: (event: { preventDefault: () => void }) => event.preventDefault() }\n\nfunction RichTextToolbar({\n  view,\n  state,\n  label,\n  linkOpen,\n  onLinkOpenChange,\n  uploadImage,\n  disabled,\n}: {\n  view: RichTextView\n  state: EditorState\n  label: string\n  linkOpen: boolean\n  onLinkOpenChange: (open: boolean) => void\n  uploadImage?: (file: File) => Promise<{ src: string; alt?: string } | null>\n  disabled: boolean\n}) {\n  const current = activeBlock(state)\n  // With no caret in the text, it reads \"Text\", as a new line would be.\n  const blockValue = blockOptionValue(current ?? undefined)\n  const back = () => requestAnimationFrame(() => view.focus())\n  const file = useRef<HTMLInputElement>(null)\n\n  return (\n    // Agents format through the editor's Markdown; the toolbar acts on a person's selection.\n    <Toolbar aria-label={`${label} formatting`} className=\"rich-text-toolbar\" aria-disabled={disabled || undefined} data-agent-hidden=\"\">\n      <Select\n        value={blockValue}\n        onValueChange={(next) => {\n          if (!next) return\n          const { type, level } = blockOptionType(next)\n          view.setBlock(type, level)\n          back()\n        }}\n      >\n        <SelectLabel className=\"uiset-visually-hidden\">Block type</SelectLabel>\n        {/* The trigger joins the toolbar's arrow keys, as its buttons do. */}\n        <ToolbarButton render={<SelectTrigger className=\"rich-text-block-type\" />}>\n          <SelectValue />\n        </ToolbarButton>\n        <SelectContent>\n          {blockOptions.map((option) => (\n            <SelectItem key={option.value} value={option.value}>\n              {option.label}\n            </SelectItem>\n          ))}\n        </SelectContent>\n      </Select>\n      <ToolbarSeparator />\n      {markButtons.map((b) => (\n        <Toggle\n          key={b.mark}\n          aria-label={b.label}\n          aria-keyshortcuts={ariaKeyshortcuts(b.keys)}\n          pressed={markActive(state, b.mark)}\n          onPressedChange={() => {\n            view.toggleMark(b.mark)\n            back()\n          }}\n          {...keepSelection}\n        >\n          <Icon name={b.icon} />\n        </Toggle>\n      ))}\n      <LinkButton view={view} state={state} open={linkOpen} onOpenChange={onLinkOpenChange} />\n      <ToolbarSeparator />\n      {listButtons.map((b) => (\n        <Toggle\n          key={b.type}\n          aria-label={b.label}\n          pressed={current?.type === b.type}\n          onPressedChange={() => {\n            view.setBlock(b.type)\n            back()\n          }}\n          {...keepSelection}\n        >\n          <Icon name={b.icon} />\n        </Toggle>\n      ))}\n      <ToolbarButton\n        aria-label=\"Insert divider\"\n        onClick={() => {\n          view.run((s) => insertBlock(s, block(\"divider\")))\n          back()\n        }}\n        {...keepSelection}\n      >\n        <Icon name=\"rule\" />\n      </ToolbarButton>\n      {uploadImage && (\n        <>\n          <ToolbarButton aria-label=\"Insert image\" onClick={() => file.current?.click()} {...keepSelection}>\n            <Icon name=\"image\" />\n          </ToolbarButton>\n          <input\n            ref={file}\n            type=\"file\"\n            accept=\"image/*\"\n            hidden\n            onChange={async (event) => {\n              const chosen = event.currentTarget.files?.[0]\n              event.currentTarget.value = \"\"\n              if (!chosen) return\n              const uploaded = await uploadImage(chosen)\n              if (uploaded) view.run((s) => insertBlock(s, block(\"image\", [], { src: uploaded.src, alt: uploaded.alt ?? \"\" })))\n              back()\n            }}\n          />\n        </>\n      )}\n      <ToolbarSeparator />\n      <ToolbarButton aria-label=\"Undo\" disabled={!view.canUndo()} onClick={() => view.undo()} {...keepSelection}>\n        <Icon name=\"undo\" />\n      </ToolbarButton>\n      <ToolbarButton aria-label=\"Redo\" disabled={!view.canRedo()} onClick={() => view.redo()} {...keepSelection}>\n        <Icon name=\"redo\" />\n      </ToolbarButton>\n    </Toolbar>\n  )\n}\n\n/** The link button: a popover to add, change or remove the link under the caret or selection. */\nfunction LinkButton({ view, state, open, onOpenChange }: { view: RichTextView; state: EditorState; open: boolean; onOpenChange: (open: boolean) => void }) {\n  const current = activeLink(state)\n  const saved = useRef<Selection | null>(null)\n  const [href, setHref] = useState(\"\")\n  const [problem, setProblem] = useState<string | null>(null)\n\n  useEffect(() => {\n    if (!open) return\n    // The selection the link applies to (the whole link when the caret is inside one), kept\n    // while focus is in the popover. Read from the view: React's copy can be a keystroke behind.\n    const now = view.state\n    saved.current = now.selection && collapsed(now.selection) ? (linkRange(now) ?? now.selection) : now.selection\n    setHref(activeLink(now) ?? \"\")\n    setProblem(null)\n  }, [open, view])\n\n  const apply = (value: string | null) => {\n    const selection = saved.current\n    let refused = false\n    view.run((s) => {\n      const target = selection ? select(s, selection) : s\n      const next = setLink(target, value)\n      if (value && next === target) refused = true\n      return next\n    })\n    if (refused) {\n      setProblem(\"Use a web address (https://…), a mail address (mailto:…) or a path (/docs).\")\n      return\n    }\n    onOpenChange(false)\n    requestAnimationFrame(() => view.focus())\n  }\n\n  return (\n    <Popover\n      open={open}\n      onOpenChange={(next) => {\n        onOpenChange(next)\n        // Closed without saving (Escape, a click outside): back to the text, selection kept.\n        if (!next) requestAnimationFrame(() => view.focus())\n      }}\n    >\n      <PopoverTrigger render={<Toggle aria-label=\"Link\" aria-keyshortcuts={ariaKeyshortcuts(\"mod+k\")} pressed={!!current} {...keepSelection} />}>\n        <Icon name=\"link\" />\n      </PopoverTrigger>\n      <PopoverContent className=\"rich-text-link\" initialFocus=\"input\">\n        <PopoverTitle>{current ? \"Edit link\" : \"Add a link\"}</PopoverTitle>\n        <form\n          className=\"rich-text-link-form\"\n          onSubmit={(event) => {\n            event.preventDefault()\n            apply(href.trim() || null)\n          }}\n        >\n          <Field invalid={!!problem}>\n            <FieldLabel>Link address</FieldLabel>\n            <Input value={href} onValueChange={(next: string) => (setHref(next), setProblem(null))} placeholder=\"https://\" inputMode=\"url\" autoComplete=\"url\" spellCheck={false} />\n            {problem && <p className=\"rich-text-link-problem\" role=\"alert\">{problem}</p>}\n          </Field>\n          <div className=\"rich-text-link-actions\">\n            {current && (\n              <Button type=\"button\" variant=\"ghost\" onClick={() => apply(null)}>\n                Remove link\n              </Button>\n            )}\n            <Button type=\"submit\">{current ? \"Save link\" : \"Add link\"}</Button>\n          </div>\n        </form>\n      </PopoverContent>\n    </Popover>\n  )\n}\n\n/* ------------------------------------------------------------------ Showing a document */\n\nfunction runElement(run: Inline, key: number): ReactNode {\n  if (isMention(run)) return <span key={key} className=\"rich-text-mention\" data-mention={run.id}>{`${run.trigger ?? \"@\"}${run.label}`}</span>\n  const parts = run.text.split(\"\\n\").flatMap((part, i) => (i ? [<br key={`b${i}`} />, part] : [part]))\n  let node: ReactNode = <Fragment key={key}>{parts}</Fragment>\n  const m = run.marks ?? {}\n  if (m.code) node = <code key={key}>{node}</code>\n  if (m.bold) node = <strong key={key}>{node}</strong>\n  if (m.italic) node = <em key={key}>{node}</em>\n  if (m.underline) node = <u key={key}>{node}</u>\n  if (m.strike) node = <s key={key}>{node}</s>\n  if (m.link) node = <a key={key} href={m.link} rel=\"noopener noreferrer\">{node}</a>\n  return node\n}\n\nfunction blockElement(b: Block, number: number): ReactNode {\n  const inline = b.content.map(runElement)\n  switch (b.type) {\n    case \"heading\":\n      return createElement(`h${b.level ?? 1}`, { key: b.id, className: `rich-text-block rich-text-heading` }, inline)\n    case \"quote\":\n      return <blockquote key={b.id} className=\"rich-text-block rich-text-quote\">{inline}</blockquote>\n    case \"code\":\n      return <pre key={b.id} className=\"rich-text-block rich-text-code\" data-language={b.language}><code>{b.content.map((r) => (isMention(r) ? r.label : r.text)).join(\"\")}</code></pre>\n    case \"divider\":\n      return <div key={b.id} className=\"rich-text-block rich-text-divider\"><hr /></div>\n    case \"image\":\n      return <div key={b.id} className=\"rich-text-block rich-text-image\"><img src={b.src} alt={b.alt ?? \"\"} /></div>\n    case \"bullet\":\n    case \"ordered\":\n    case \"task\":\n      return (\n        <li key={b.id} className={`rich-text-block rich-text-${b.type}`} aria-level={(b.indent ?? 0) + 1} data-indent={b.indent ?? 0} value={b.type === \"ordered\" ? number : undefined} data-checked={b.type === \"task\" ? String(!!b.checked) : undefined}>\n          {b.type === \"task\" && <span className=\"rich-text-check\" role=\"img\" aria-label={b.checked ? \"Done\" : \"Not done\"} />}\n          {inline}\n        </li>\n      )\n    default:\n      return <p key={b.id} className=\"rich-text-block rich-text-paragraph\">{blockLength(b) ? inline : <br />}</p>\n  }\n}\n\n/** Shows a document read-only, with the editor's styles; rendered as React, never as HTML strings. */\nfunction RichTextContent({ value, className }: { value: string | Doc; className?: string }) {\n  const doc = sanitizeDoc(typeof value === \"string\" ? fromMarkdown(value) : value)\n  const out: ReactNode[] = []\n  const counters: number[] = []\n  let list: { type: string; items: ReactNode[] } | null = null\n  const flush = () => {\n    if (!list) return\n    out.push(createElement(list.type === \"ordered\" ? \"ol\" : \"ul\", { key: `l${out.length}`, className: `rich-text-list rich-text-list-${list.type}` }, list.items))\n    list = null\n  }\n  for (const b of doc) {\n    if (b.type === \"bullet\" || b.type === \"ordered\" || b.type === \"task\") {\n      const level = b.indent ?? 0\n      counters.length = level + 1\n      counters[level] = b.type === \"ordered\" ? (counters[level] ?? 0) + 1 : 0\n      if (!list || list.type !== b.type) {\n        flush()\n        list = { type: b.type, items: [] }\n      }\n      list.items.push(blockElement(b, counters[level]!))\n      continue\n    }\n    counters.length = 0\n    flush()\n    out.push(blockElement(b, 0))\n  }\n  flush()\n  return <div className={[\"rich-text-content\", \"rich-text-static\", className].filter(Boolean).join(\" \")}>{out}</div>\n}\n\nexport { blockLabel, defaultCommands as richTextCommands, RichTextContent, RichTextEditor }\nexport type { Command as RichTextCommand, Doc as RichTextDocument, RichTextEditorProps }\nexport { fromHTML, fromMarkdown, toHTML, toMarkdown, toText } from \"./rich-text/serialize\"\n",
      "type": "registry:ui",
      "target": "@ui/rich-text.tsx"
    },
    {
      "path": "registry/uiset/ui/rich-text/model.ts",
      "content": "// The rich text editor's document and its edits, without a DOM or a framework. A document\n// is a flat list of blocks (lists are blocks with an indent, as in most editors people\n// use); each text block holds inline runs of text with marks, and mentions. Every edit is\n// a pure function from one state to the next, so the React editor and the web element\n// apply the same edits, undo is a stack of states, and all of it is unit tested.\n\ntype Marks = {\n  bold?: true\n  italic?: true\n  underline?: true\n  strike?: true\n  code?: true\n  /** A safe link target (http, https, mailto, tel, or a relative path). */\n  link?: string\n}\ntype MarkName = Exclude<keyof Marks, \"link\">\n\ntype TextRun = { type?: \"text\"; text: string; marks?: Marks }\n/** A mention or other token: one character wide for the caret, never split. */\ntype MentionRun = { type: \"mention\"; id: string; label: string; trigger?: string }\ntype Inline = TextRun | MentionRun\n\ntype TextBlockType = \"paragraph\" | \"heading\" | \"quote\" | \"code\" | \"bullet\" | \"ordered\" | \"task\"\ntype VoidBlockType = \"divider\" | \"image\"\ntype BlockType = TextBlockType | VoidBlockType\n\ntype Block = {\n  id: string\n  type: BlockType\n  content: Inline[]\n  /** Headings: 1 to 3. */\n  level?: 1 | 2 | 3\n  /** List items and tasks: 0 is the outer level. */\n  indent?: number\n  /** Tasks. */\n  checked?: boolean\n  /** Code blocks. */\n  language?: string\n  /** Images. */\n  src?: string\n  alt?: string\n}\n\ntype Doc = Block[]\ntype Position = { block: number; offset: number }\ntype Selection = { anchor: Position; focus: Position }\ntype EditorState = {\n  doc: Doc\n  selection: Selection | null\n  /** Marks for what's typed next at a collapsed caret, after Mod+B with nothing selected. */\n  stored?: Marks | null\n}\n\nconst MAX_INDENT = 4\nconst OBJECT = \"￼\"\nconst marks: MarkName[] = [\"bold\", \"italic\", \"underline\", \"strike\", \"code\"]\n\nlet nextId = 0\nconst newId = () => `b${Date.now().toString(36)}${(nextId++).toString(36)}`\n\n/* ------------------------------------------------------------------ Basics */\n\nconst isVoid = (block: Block) => block.type === \"divider\" || block.type === \"image\"\nconst isList = (block: Block) => block.type === \"bullet\" || block.type === \"ordered\" || block.type === \"task\"\nconst isMention = (run: Inline): run is MentionRun => run.type === \"mention\"\nconst runLength = (run: Inline) => (isMention(run) ? 1 : run.text.length)\nconst blockLength = (block: Block) => block.content.reduce((n, run) => n + runLength(run), 0)\n/** The block's text, a mention as U+FFFC (one character, as the trigger menu reads it). */\nconst blockText = (block: Block) => block.content.map((run) => (isMention(run) ? OBJECT : run.text)).join(\"\")\n/** The block's text as a person reads it: mentions as their label. */\n/** Content as code holds it: one plain run, mentions as their text. */\nconst asCode = (content: Inline[]): Inline[] => {\n  const text = content.map((run) => (isMention(run) ? `${run.trigger ?? \"@\"}${run.label}` : run.text)).join(\"\")\n  return text ? [{ text }] : []\n}\n/** Joins content onto a block; code keeps it plain. */\nconst joined = (into: Block, content: Inline[]): Inline[] => (into.type === \"code\" ? asCode(content) : normalize(content))\nconst plainText = (block: Block) => block.content.map((run) => (isMention(run) ? `${run.trigger ?? \"@\"}${run.label}` : run.text)).join(\"\")\n\nfunction block(type: BlockType = \"paragraph\", content: Inline[] = [], extra: Partial<Block> = {}): Block {\n  return { id: newId(), type, content, ...extra }\n}\n\nconst paragraph = (text = \"\") => block(\"paragraph\", text ? [{ text }] : [])\n\nconst sameMarks = (a?: Marks, b?: Marks) => {\n  const x = a ?? {}\n  const y = b ?? {}\n  return marks.every((m) => !!x[m] === !!y[m]) && (x.link ?? null) === (y.link ?? null)\n}\n\nconst cleanMarks = (m?: Marks | null): Marks | undefined => {\n  if (!m) return undefined\n  const out: Marks = {}\n  for (const name of marks) if (m[name]) out[name] = true\n  if (m.link) out.link = m.link\n  return Object.keys(out).length ? out : undefined\n}\n\n/** Merges neighbours with the same marks and drops empty runs. */\nfunction normalize(content: Inline[]): Inline[] {\n  const out: Inline[] = []\n  for (const run of content) {\n    if (isMention(run)) {\n      out.push(run)\n      continue\n    }\n    if (!run.text) continue\n    const last = out.at(-1)\n    if (last && !isMention(last) && sameMarks(last.marks, run.marks)) out[out.length - 1] = { text: last.text + run.text, marks: last.marks }\n    else out.push({ text: run.text, ...(cleanMarks(run.marks) ? { marks: cleanMarks(run.marks) } : {}) })\n  }\n  return out\n}\n\n/** The runs before `offset` and from it on, splitting a text run at the boundary. */\nfunction splitContent(content: Inline[], offset: number): [Inline[], Inline[]] {\n  const before: Inline[] = []\n  const after: Inline[] = []\n  let at = 0\n  for (const run of content) {\n    const len = runLength(run)\n    if (at + len <= offset) before.push(run)\n    else if (at >= offset) after.push(run)\n    else if (!isMention(run)) {\n      const cut = offset - at\n      before.push({ ...run, text: run.text.slice(0, cut) })\n      after.push({ ...run, text: run.text.slice(cut) })\n    } else after.push(run)\n    at += len\n  }\n  return [normalize(before), normalize(after)]\n}\n\nfunction sliceContent(content: Inline[], from: number, to: number) {\n  return splitContent(splitContent(content, to)[0], from)[1]\n}\n\nconst ordered = (s: Selection): [Position, Position] => {\n  const a = s.anchor\n  const f = s.focus\n  return a.block < f.block || (a.block === f.block && a.offset <= f.offset) ? [a, f] : [f, a]\n}\nconst collapsed = (s: Selection) => s.anchor.block === s.focus.block && s.anchor.offset === s.focus.offset\nconst caret = (pos: Position): Selection => ({ anchor: pos, focus: pos })\n\nfunction clampPosition(doc: Doc, pos: Position): Position {\n  const b = Math.max(0, Math.min(pos.block, doc.length - 1))\n  return { block: b, offset: Math.max(0, Math.min(pos.offset, blockLength(doc[b]!))) }\n}\n\n/** A document is never empty, and a void block never ends it, so there's always a place to type. */\nfunction ensureDoc(doc: Doc): Doc {\n  if (!doc.length) return [paragraph()]\n  if (isVoid(doc.at(-1)!)) return [...doc, paragraph()]\n  return doc\n}\n\nfunction withDoc(state: EditorState, doc: Doc, selection: Selection | null, stored: Marks | null = null): EditorState {\n  const next = ensureDoc(doc)\n  return { doc: next, selection: selection && { anchor: clampPosition(next, selection.anchor), focus: clampPosition(next, selection.focus) }, stored }\n}\n\n/* ------------------------------------------------------------------ Reading */\n\n/** The marks of the character before the caret (or after it at a block start). */\nfunction marksAtPosition(doc: Doc, pos: Position): Marks | undefined {\n  const content = doc[pos.block]?.content ?? []\n  let at = 0\n  let before: Inline | undefined\n  let after: Inline | undefined\n  for (const run of content) {\n    const len = runLength(run)\n    if (at < pos.offset && pos.offset <= at + len) before = run\n    if (!after && at >= pos.offset && len) after = run\n    at += len\n  }\n  const run = before ?? after\n  return run && !isMention(run) ? run.marks : undefined\n}\n\n/** Marks typing would use now: the stored ones, or the character before's, minus a link at its end. */\nfunction typingMarks(state: EditorState): Marks | undefined {\n  if (state.stored !== undefined && state.stored !== null) return cleanMarks(state.stored)\n  if (!state.selection) return undefined\n  // Typing over a selection (or a spellcheck replacing a word) keeps the marks the whole\n  // selection shares, its link included.\n  if (!collapsed(state.selection)) {\n    let shared: Marks | null = null\n    forEachRun(state, (run) => {\n      if (isMention(run)) return\n      const m = run.marks ?? {}\n      if (shared === null) shared = { ...m }\n      else for (const key of Object.keys(shared) as (keyof Marks)[]) if (m[key] !== shared[key]) delete shared[key]\n    })\n    if (shared !== null) return cleanMarks(shared)\n  }\n  const pos = ordered(state.selection)[0]\n  const m = marksAtPosition(state.doc, pos)\n  if (!m?.link) return m\n  // A link doesn't grow when you type at its end.\n  const next = marksAtPosition(state.doc, { block: pos.block, offset: pos.offset + 1 })\n  const atEnd = !next?.link || next.link !== m.link || pos.offset === blockLength(state.doc[pos.block]!)\n  if (!atEnd) return m\n  const { link: _link, ...rest } = m\n  return cleanMarks(rest)\n}\n\n/** Whether `mark` is on for the whole selection (or for typing, when it's a caret). */\nfunction markActive(state: EditorState, mark: MarkName): boolean {\n  if (!state.selection) return false\n  if (collapsed(state.selection)) return !!typingMarks(state)?.[mark]\n  let any = false\n  let all = true\n  forEachRun(state, (run) => {\n    if (isMention(run)) return\n    any = true\n    if (!run.marks?.[mark]) all = false\n  })\n  return any && all\n}\n\n/** The link under the caret or shared by the whole selection. */\nfunction activeLink(state: EditorState): string | null {\n  if (!state.selection) return null\n  if (collapsed(state.selection)) {\n    const pos = state.selection.focus\n    const m = marksAtPosition(state.doc, pos)\n    return m?.link ?? marksAtPosition(state.doc, { block: pos.block, offset: pos.offset + 1 })?.link ?? null\n  }\n  let link: string | null | undefined\n  forEachRun(state, (run) => {\n    const l = isMention(run) ? null : (run.marks?.link ?? null)\n    link = link === undefined ? l : link === l ? l : null\n  })\n  return link ?? null\n}\n\n/** The range of the link run around a caret, to select it before editing the link. */\nfunction linkRange(state: EditorState): Selection | null {\n  const href = activeLink(state)\n  if (!href || !state.selection) return null\n  const pos = state.selection.focus\n  const content = state.doc[pos.block]!.content\n  let at = 0\n  let start = -1\n  let end = -1\n  for (const run of content) {\n    const len = runLength(run)\n    const linked = !isMention(run) && run.marks?.link === href\n    if (linked && start < 0 && at <= pos.offset) start = at\n    if (linked && start >= 0) end = at + len\n    if (!linked && start >= 0 && end >= pos.offset) break\n    if (!linked && at + len <= pos.offset) start = -1\n    at += len\n  }\n  if (start < 0 || end < pos.offset) return null\n  return { anchor: { block: pos.block, offset: start }, focus: { block: pos.block, offset: end } }\n}\n\n/** The type the selection's blocks share, or null when they differ. */\nfunction activeBlock(state: EditorState): { type: BlockType; level?: number } | null {\n  if (!state.selection) return null\n  const [from, to] = ordered(state.selection)\n  const first = state.doc[from.block]!\n  for (let i = from.block; i <= to.block; i++) {\n    const b = state.doc[i]!\n    if (b.type !== first.type || (b.type === \"heading\" && b.level !== first.level)) return null\n  }\n  return { type: first.type, ...(first.type === \"heading\" ? { level: first.level } : {}) }\n}\n\n/** Calls `visit` for each run (or part of one) inside the selection. */\nfunction forEachRun(state: EditorState, visit: (run: Inline, block: Block) => void) {\n  if (!state.selection) return\n  const [from, to] = ordered(state.selection)\n  for (let i = from.block; i <= to.block; i++) {\n    const b = state.doc[i]!\n    if (isVoid(b)) continue\n    const start = i === from.block ? from.offset : 0\n    const end = i === to.block ? to.offset : blockLength(b)\n    for (const run of sliceContent(b.content, start, end)) visit(run, b)\n  }\n}\n\n/** The selected part of the document, as blocks (for copy and drag). */\nfunction fragment(state: EditorState): Doc {\n  if (!state.selection || collapsed(state.selection)) return []\n  const [from, to] = ordered(state.selection)\n  const out: Doc = []\n  for (let i = from.block; i <= to.block; i++) {\n    const b = state.doc[i]!\n    if (isVoid(b)) {\n      out.push({ ...b })\n      continue\n    }\n    const start = i === from.block ? from.offset : 0\n    const end = i === to.block ? to.offset : blockLength(b)\n    out.push({ ...b, id: newId(), content: sliceContent(b.content, start, end) })\n  }\n  return out\n}\n\n/* ------------------------------------------------------------------ Edits */\n\n/** Removes the selected content, joining the first and last block. */\nfunction deleteSelection(state: EditorState): EditorState {\n  if (!state.selection || collapsed(state.selection)) return state\n  const doc = state.doc\n  let [from, to] = ordered(state.selection)\n  // Everything selected and deleted leaves a fresh paragraph, as a new document starts.\n  const end = doc[to.block]!\n  if (from.block === 0 && from.offset === 0 && to.block === doc.length - 1 && (isVoid(end) || to.offset >= blockLength(end))) {\n    return withDoc(state, [{ ...paragraph(), id: doc[0]!.id }], caret({ block: 0, offset: 0 }))\n  }\n  // Whole blocks selected up to the start of the next one (as a triple-click selects):\n  // the next block isn't part of it, so it keeps its own type and text.\n  if (from.offset === 0 && to.offset === 0 && to.block > from.block) to = { block: to.block - 1, offset: blockLength(doc[to.block - 1]!) }\n  const first = doc[from.block]!\n  const last = doc[to.block]!\n  const head = isVoid(first) ? [] : splitContent(first.content, from.offset)[0]\n  const tail = isVoid(last) ? [] : splitContent(last.content, to.offset)[1]\n  // The first block keeps its type, unless it was a void block (then the last one's type).\n  const base = isVoid(first) ? (isVoid(last) ? paragraph() : { ...last, content: [] }) : first\n  const merged: Block = { ...base, content: joined(base, [...head, ...tail]) }\n  const next = [...doc.slice(0, from.block), merged, ...doc.slice(to.block + 1)]\n  return withDoc(state, next, caret({ block: from.block, offset: isVoid(first) ? 0 : from.offset }))\n}\n\n/** Inserts runs at the caret, replacing any selection. Runs take `marks` unless they have their own. */\nfunction insertContent(state: EditorState, content: Inline[]): EditorState {\n  const cleared = deleteSelection(state)\n  if (!cleared.selection) return state\n  const pos = cleared.selection.focus\n  const target = cleared.doc[pos.block]!\n  if (isVoid(target)) {\n    // Typing on an image or a rule makes a paragraph after it.\n    const p = block(\"paragraph\", normalize(content))\n    const doc = [...cleared.doc.slice(0, pos.block + 1), p, ...cleared.doc.slice(pos.block + 1)]\n    return withDoc(cleared, doc, caret({ block: pos.block + 1, offset: blockLength(p) }))\n  }\n  // Code keeps plain text: no marks, mentions read as their text.\n  const runs = target.type === \"code\" ? content.map((run) => ({ text: isMention(run) ? `${run.trigger ?? \"@\"}${run.label}` : run.text })) : content\n  const [before, after] = splitContent(target.content, pos.offset)\n  const inserted = normalize(runs)\n  const doc = cleared.doc.slice()\n  doc[pos.block] = { ...target, content: normalize([...before, ...inserted, ...after]) }\n  const length = inserted.reduce((n, run) => n + runLength(run), 0)\n  return withDoc(cleared, doc, caret({ block: pos.block, offset: pos.offset + length }), cleared.stored ?? null)\n}\n\n/** Types text at the caret: new lines split blocks, as pasting plain text does. */\nfunction insertText(state: EditorState, text: string): EditorState {\n  if (!state.selection) return state\n  const lines = text.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\")\n  const marksNow = typingMarks(state)\n  const inCode = state.doc[ordered(state.selection)[0].block]?.type === \"code\"\n  if (inCode) return keepStored(insertContent(state, [{ text: lines.join(\"\\n\") }]), null)\n  let next = state\n  lines.forEach((line, i) => {\n    if (i > 0) next = splitBlock(next)\n    if (line) next = insertContent({ ...next, stored: next.stored }, [{ text: line, ...(marksNow ? { marks: marksNow } : {}) }])\n  })\n  // Stored marks stay on while typing continues, until the caret moves.\n  return keepStored(next, state.stored ?? null)\n}\n\nconst keepStored = (state: EditorState, stored: Marks | null): EditorState => ({ ...state, stored })\n\n/** A soft line break inside the block (Shift+Enter). */\nfunction insertLineBreak(state: EditorState): EditorState {\n  return insertContent(state, [{ text: \"\\n\", ...(typingMarks(state) ? { marks: typingMarks(state) } : {}) }])\n}\n\n/** Inserts a mention (or any token) at the caret, then a space. */\nfunction insertMention(state: EditorState, mention: Omit<MentionRun, \"type\">): EditorState {\n  return insertContent(state, [{ type: \"mention\", ...mention }, { text: \" \" }])\n}\n\n/** Replaces a range of one block's text (the trigger menu's query) with runs. */\nfunction replaceRange(state: EditorState, block: number, from: number, to: number, content: Inline[]): EditorState {\n  return insertContent({ ...state, selection: { anchor: { block, offset: from }, focus: { block, offset: to } } }, content)\n}\n\n/** Enter: splits the block. An empty list item or quote ends the list or quote instead. */\nfunction splitBlock(state: EditorState): EditorState {\n  const cleared = deleteSelection(state)\n  if (!cleared.selection) return state\n  const pos = cleared.selection.focus\n  const target = cleared.doc[pos.block]!\n  if (target.type === \"code\") {\n    // Enter on an empty block, or on the empty last line, leaves the code for a paragraph.\n    const text = blockText(target)\n    if (!text) return setBlock(cleared, \"paragraph\")\n    if (pos.offset === text.length && text.endsWith(\"\\n\")) {\n      const trimmed = replaceRange(cleared, pos.block, text.length - 1, text.length, [])\n      const doc = [...trimmed.doc.slice(0, pos.block + 1), paragraph(), ...trimmed.doc.slice(pos.block + 1)]\n      return withDoc(trimmed, doc, caret({ block: pos.block + 1, offset: 0 }))\n    }\n    return insertContent(cleared, [{ text: \"\\n\" }])\n  }\n  if (isVoid(target)) {\n    const p = paragraph()\n    return withDoc(cleared, [...cleared.doc.slice(0, pos.block + 1), p, ...cleared.doc.slice(pos.block + 1)], caret({ block: pos.block + 1, offset: 0 }))\n  }\n  const empty = blockLength(target) === 0\n  if (empty && (isList(target) || target.type === \"quote\")) {\n    // Enter on an empty item steps out one level, then out of the list.\n    if (isList(target) && (target.indent ?? 0) > 0) return outdent(cleared)\n    return setBlock(cleared, \"paragraph\")\n  }\n  const [before, after] = splitContent(target.content, pos.offset)\n  // A heading continues as a paragraph; lists and quotes continue as themselves.\n  const nextType: BlockType = target.type === \"heading\" ? \"paragraph\" : target.type\n  const head: Block = { ...target, content: before }\n  const tail: Block = {\n    id: newId(),\n    type: nextType,\n    content: after,\n    ...(isList(target) ? { indent: target.indent ?? 0 } : {}),\n    ...(target.type === \"task\" ? { checked: false } : {}),\n  }\n  // At the very start of a non-empty block, the new empty block goes above and keeps the caret's block as it was.\n  if (pos.offset === 0 && !empty) {\n    const above: Block = { ...tail, content: [], type: target.type === \"heading\" ? \"paragraph\" : target.type }\n    const doc = [...cleared.doc.slice(0, pos.block), above, target, ...cleared.doc.slice(pos.block + 1)]\n    return withDoc(cleared, doc, caret({ block: pos.block + 1, offset: 0 }))\n  }\n  const doc = [...cleared.doc.slice(0, pos.block), head, tail, ...cleared.doc.slice(pos.block + 1)]\n  return withDoc(cleared, doc, caret({ block: pos.block + 1, offset: 0 }))\n}\n\nconst segmenters = new Map<string, Intl.Segmenter>()\nfunction segmenter(granularity: \"grapheme\" | \"word\") {\n  let s = segmenters.get(granularity)\n  if (!s) segmenters.set(granularity, (s = new Intl.Segmenter(undefined, { granularity })))\n  return s\n}\n\n/** Where a delete of one `unit` before (or after) `offset` lands in `text`. */\nfunction stepFrom(text: string, offset: number, unit: \"char\" | \"word\" | \"line\", forward: boolean): number {\n  if (unit === \"line\") {\n    if (forward) {\n      const nl = text.indexOf(\"\\n\", offset)\n      return nl < 0 ? text.length : Math.max(nl, offset + 1)\n    }\n    const nl = text.lastIndexOf(\"\\n\", offset - 1)\n    return nl < 0 ? 0 : Math.min(nl + 1, offset - 1)\n  }\n  const parts = [...segmenter(unit === \"char\" ? \"grapheme\" : \"word\").segment(text)]\n  if (unit === \"char\") {\n    // Whole graphemes: an emoji with its modifiers, or a letter with its accents, goes at once.\n    if (forward) {\n      const next = parts.find((p) => p.index + p.segment.length > offset)\n      return next ? next.index + next.segment.length : text.length\n    }\n    const prev = parts.filter((p) => p.index < offset).at(-1)\n    return prev ? prev.index : 0\n  }\n  // Words: skip spaces next to the caret, then the word.\n  if (forward) {\n    let i = offset\n    while (i < text.length && /\\s/.test(text[i]!)) i++\n    const word = parts.find((p) => p.index <= i && p.index + p.segment.length > i)\n    return word ? word.index + word.segment.length : text.length\n  }\n  let i = offset\n  while (i > 0 && /\\s/.test(text[i - 1]!)) i--\n  const word = parts.filter((p) => p.index < i).at(-1)\n  return word ? word.index : 0\n}\n\n/** Backspace (or Delete with `forward`), by character, word or line. */\nfunction deleteBy(state: EditorState, unit: \"char\" | \"word\" | \"line\" = \"char\", forward = false): EditorState {\n  if (!state.selection) return state\n  if (!collapsed(state.selection)) return deleteSelection(state)\n  const pos = state.selection.focus\n  const target = state.doc[pos.block]!\n  const len = blockLength(target)\n  if (isVoid(target)) {\n    // A selected rule or image goes; the caret moves to the block that takes its place.\n    const doc = [...state.doc.slice(0, pos.block), ...state.doc.slice(pos.block + 1)]\n    const at = Math.min(pos.block, doc.length - 1)\n    return withDoc(state, doc, caret({ block: Math.max(0, forward ? at : pos.block - 1), offset: forward ? 0 : Number.MAX_SAFE_INTEGER }))\n  }\n  if (!forward && pos.offset === 0) {\n    // At a block's start, Backspace first unwraps it: a list item steps out, a heading or quote becomes a paragraph.\n    if (isList(target) && (target.indent ?? 0) > 0) return outdent(state)\n    if (target.type !== \"paragraph\") return setBlock(state, \"paragraph\")\n    if (pos.block === 0) return state\n    const prev = state.doc[pos.block - 1]!\n    if (isVoid(prev)) {\n      // The rule or image before goes, as one Backspace.\n      const doc = [...state.doc.slice(0, pos.block - 1), ...state.doc.slice(pos.block)]\n      return withDoc(state, doc, caret({ block: pos.block - 1, offset: 0 }))\n    }\n    const merged: Block = { ...prev, content: joined(prev, [...prev.content, ...target.content]) }\n    const doc = [...state.doc.slice(0, pos.block - 1), merged, ...state.doc.slice(pos.block + 1)]\n    return withDoc(state, doc, caret({ block: pos.block - 1, offset: blockLength(prev) }))\n  }\n  if (forward && pos.offset === len) {\n    if (pos.block === state.doc.length - 1) return state\n    const next = state.doc[pos.block + 1]!\n    if (isVoid(next)) return withDoc(state, [...state.doc.slice(0, pos.block + 1), ...state.doc.slice(pos.block + 2)], caret(pos))\n    const merged: Block = { ...target, content: joined(target, [...target.content, ...next.content]) }\n    return withDoc(state, [...state.doc.slice(0, pos.block), merged, ...state.doc.slice(pos.block + 2)], caret(pos))\n  }\n  const text = blockText(target)\n  const to = stepFrom(text, pos.offset, unit, forward)\n  const [from, end] = forward ? [pos.offset, Math.min(len, Math.max(to, pos.offset + 1))] : [Math.max(0, Math.min(to, pos.offset - 1)), pos.offset]\n  return deleteSelection({ ...state, selection: { anchor: { block: pos.block, offset: from }, focus: { block: pos.block, offset: end } } })\n}\n\n/** Turns a mark on or off: over the selection, or for typing at a caret. */\nfunction toggleMark(state: EditorState, mark: MarkName): EditorState {\n  if (!state.selection) return state\n  const on = !markActive(state, mark)\n  if (collapsed(state.selection)) {\n    const current = { ...(typingMarks(state) ?? {}) }\n    if (on) current[mark] = true\n    else delete current[mark]\n    return { ...state, stored: cleanMarks(current) ?? {} }\n  }\n  return mapMarks(state, (m) => {\n    const next = { ...(m ?? {}) }\n    if (on) next[mark] = true\n    else delete next[mark]\n    // Code text keeps no other marks but links; other marks drop code.\n    if (on && mark === \"code\") for (const other of marks) if (other !== \"code\") delete next[other]\n    return cleanMarks(next)\n  })\n}\n\n/** Sets or removes a link over the selection. A caret inside a link changes the whole link. */\nfunction setLink(state: EditorState, href: string | null): EditorState {\n  if (!state.selection) return state\n  let target = state\n  if (collapsed(state.selection)) {\n    const range = linkRange(state)\n    if (!range) {\n      if (!href) return state\n      // A link with no text selected inserts its address as the text, once it's safe.\n      const safe = safeHref(href)\n      if (!safe) return state\n      return insertContent(state, [{ text: href.trim(), marks: { ...(typingMarks(state) ?? {}), link: safe } }, { text: \"\" }])\n    }\n    target = { ...state, selection: range }\n  }\n  const safe = href ? safeHref(href) : null\n  if (href && !safe) return state\n  return mapMarks(target, (m) => {\n    const next = { ...(m ?? {}) }\n    if (safe) next.link = safe\n    else delete next.link\n    return cleanMarks(next)\n  })\n}\n\nfunction mapMarks(state: EditorState, update: (m: Marks | undefined) => Marks | undefined): EditorState {\n  if (!state.selection) return state\n  const [from, to] = ordered(state.selection)\n  const doc = state.doc.slice()\n  for (let i = from.block; i <= to.block; i++) {\n    const b = doc[i]!\n    if (isVoid(b) || b.type === \"code\") continue\n    const start = i === from.block ? from.offset : 0\n    const end = i === to.block ? to.offset : blockLength(b)\n    const [head, rest] = splitContent(b.content, start)\n    const [mid, tail] = splitContent(rest, end - start)\n    const changed = mid.map((run) => (isMention(run) ? run : { text: run.text, ...(update(run.marks) ? { marks: update(run.marks) } : {}) }))\n    doc[i] = { ...b, content: normalize([...head, ...changed, ...tail]) }\n  }\n  return { ...state, doc, stored: null }\n}\n\n/** Sets the selection's blocks to a type. Setting the type they already have makes them paragraphs. */\nfunction setBlock(state: EditorState, type: TextBlockType, attrs: { level?: 1 | 2 | 3; language?: string } = {}): EditorState {\n  if (!state.selection) return state\n  const [from, to] = ordered(state.selection)\n  const current = activeBlock(state)\n  const same = current?.type === type && (type !== \"heading\" || current.level === (attrs.level ?? 1))\n  const nextType: TextBlockType = same && type !== \"paragraph\" ? \"paragraph\" : type\n  const doc = state.doc.slice()\n  for (let i = from.block; i <= to.block; i++) {\n    const b = doc[i]!\n    if (isVoid(b)) continue\n    const { level: _l, indent: _i, checked: _c, language: _g, ...rest } = b\n    const content = nextType === \"code\" ? [{ text: plainText(b) }] : b.content\n    doc[i] = {\n      ...rest,\n      type: nextType,\n      content: normalize(content),\n      ...(nextType === \"heading\" ? { level: attrs.level ?? 1 } : {}),\n      ...(nextType === \"bullet\" || nextType === \"ordered\" || nextType === \"task\" ? { indent: b.indent ?? 0 } : {}),\n      ...(nextType === \"task\" ? { checked: b.checked ?? false } : {}),\n      ...(nextType === \"code\" && attrs.language ? { language: attrs.language } : {}),\n    }\n  }\n  return { ...state, doc }\n}\n\nfunction shiftIndent(state: EditorState, by: number): EditorState {\n  if (!state.selection) return state\n  const [from, to] = ordered(state.selection)\n  const doc = state.doc.slice()\n  let changed = false\n  for (let i = from.block; i <= to.block; i++) {\n    const b = doc[i]!\n    if (!isList(b)) continue\n    // An item goes in at most one level deeper than the item above it.\n    const above = doc[i - 1]\n    const limit = above && isList(above) ? Math.min(MAX_INDENT, (above.indent ?? 0) + 1) : 0\n    const indent = Math.max(0, Math.min(by > 0 ? limit : MAX_INDENT, (b.indent ?? 0) + by))\n    if (indent !== (b.indent ?? 0)) changed = true\n    doc[i] = { ...b, indent }\n  }\n  return changed ? { ...state, doc } : state\n}\n\n/** Tab in a list. */\nconst indent = (state: EditorState) => shiftIndent(state, 1)\n/** Shift+Tab in a list. */\nconst outdent = (state: EditorState) => shiftIndent(state, -1)\n\nfunction toggleTask(state: EditorState, index: number): EditorState {\n  const b = state.doc[index]\n  if (!b || b.type !== \"task\") return state\n  const doc = state.doc.slice()\n  doc[index] = { ...b, checked: !b.checked }\n  return { ...state, doc }\n}\n\n/** Inserts a rule or an image after the caret's block (in place of an empty paragraph). */\nfunction insertBlock(state: EditorState, inserted: Block): EditorState {\n  if (!state.selection) return state\n  const pos = ordered(state.selection)[1]\n  const current = state.doc[pos.block]!\n  const replace = current.type === \"paragraph\" && blockLength(current) === 0\n  const at = replace ? pos.block : pos.block + 1\n  const after = paragraph()\n  const doc = [...state.doc.slice(0, at), inserted, after, ...state.doc.slice(replace ? pos.block + 1 : pos.block + 1)]\n  return withDoc(state, doc, caret({ block: at + 1, offset: 0 }))\n}\n\n/** Pastes blocks at the caret: the first joins the caret's block, the rest follow it. */\nfunction insertFragment(state: EditorState, blocks: Doc): EditorState {\n  const pasted = blocks.filter((b) => isVoid(b) || b.content.length || blocks.length === 1)\n  if (!pasted.length) return state\n  if (pasted.length === 1 && !isVoid(pasted[0]!)) {\n    // Into an empty block, a pasted heading, item or quote stays one; elsewhere its text joins.\n    const only = pasted[0]!\n    const cleared = deleteSelection(state)\n    const at = cleared.selection?.focus\n    const target = at ? cleared.doc[at.block] : undefined\n    if (at && target && !isVoid(target) && blockLength(target) === 0 && only.type !== \"paragraph\" && target.type !== \"code\") {\n      const doc = cleared.doc.slice()\n      doc[at.block] = { ...only, id: target.id, content: normalize(only.content) }\n      return withDoc(cleared, doc, caret({ block: at.block, offset: blockLength(doc[at.block]!) }))\n    }\n    return insertContent(state, only.content)\n  }\n  const cleared = deleteSelection(state)\n  if (!cleared.selection) return state\n  const pos = cleared.selection.focus\n  const target = cleared.doc[pos.block]!\n  const [before, after] = isVoid(target) ? [[], []] : splitContent(target.content, pos.offset)\n  const first = pasted[0]!\n  const last = pasted.at(-1)!\n  const middle = pasted.slice(1, -1).map((b) => ({ ...b, id: newId() }))\n  // An empty target block takes the first pasted block's type, as in other editors.\n  const head: Block = isVoid(first) ? { ...target, content: before } : { ...(before.length || isVoid(target) ? target : { ...first, id: target.id }), content: normalize([...before, ...first.content]) }\n  const tail: Block = isVoid(last) ? { ...target, id: newId(), content: after } : { ...last, id: newId(), content: normalize([...last.content, ...after]) }\n  const firstVoid = isVoid(first) ? [{ ...first, id: newId() }] : []\n  const lastVoid = isVoid(last) && pasted.length > 1 ? [{ ...last, id: newId() }] : []\n  const doc = [...cleared.doc.slice(0, pos.block), head, ...firstVoid, ...middle, ...lastVoid, tail, ...cleared.doc.slice(pos.block + 1)].filter(\n    (b, i, all) => !(b === head && !isVoid(b) && blockLength(b) === 0 && isVoid(first) && all.length > 1),\n  )\n  const tailIndex = doc.indexOf(tail)\n  return withDoc(cleared, doc, caret({ block: tailIndex, offset: blockLength(tail) - after.reduce((n, r) => n + runLength(r), 0) }))\n}\n\nfunction select(state: EditorState, selection: Selection | null): EditorState {\n  if (!selection) return { ...state, selection: null, stored: null }\n  const next = { anchor: clampPosition(state.doc, selection.anchor), focus: clampPosition(state.doc, selection.focus) }\n  const moved = !state.selection || state.selection.focus.block !== next.focus.block || state.selection.focus.offset !== next.focus.offset || !collapsed(next)\n  return { ...state, selection: next, stored: moved ? null : state.stored }\n}\n\nfunction selectAll(state: EditorState): EditorState {\n  const last = state.doc.length - 1\n  return { ...state, selection: { anchor: { block: 0, offset: 0 }, focus: { block: last, offset: blockLength(state.doc[last]!) } }, stored: null }\n}\n\n/* -------------------------------------------------------- Markdown as you type */\n\n/**\n * After a space or Enter, a block that starts with Markdown becomes that block: \"# \" a\n * heading, \"- \" a bullet, \"1. \" a numbered item, \"[] \" a task, \"> \" a quote, \"```\" code,\n * \"---\" a rule. Inline, a closing **, *, _, ` or ~~ marks what it wraps.\n */\nfunction inputRule(state: EditorState, typed: string): EditorState | null {\n  if (!state.selection || !collapsed(state.selection)) return null\n  const pos = state.selection.focus\n  const b = state.doc[pos.block]!\n  if (isVoid(b) || b.type === \"code\") return null\n  const text = blockText(b).slice(0, pos.offset)\n  // \"[ ] \" in a bulleted item makes it a to-do, as \"- [ ] \" would in a paragraph.\n  if (typed === \" \" && b.type === \"bullet\" && /^\\[( |x)?\\]$/i.test(text) && pos.offset === text.length) {\n    const cleared = replaceRange(state, pos.block, 0, pos.offset, [])\n    const next = setBlock(select(cleared, caret({ block: pos.block, offset: 0 })), \"task\")\n    if (/x/i.test(text)) next.doc[pos.block] = { ...next.doc[pos.block]!, checked: true }\n    return next\n  }\n  if (typed === \" \" && b.type === \"paragraph\") {\n    const rules: [RegExp, (m: RegExpMatchArray) => [TextBlockType, { level?: 1 | 2 | 3 }?, boolean?]][] = [\n      [/^(#{1,3})$/, (m) => [\"heading\", { level: m[1]!.length as 1 | 2 | 3 }]],\n      [/^[-*+]$/, () => [\"bullet\"]],\n      [/^\\d+[.)]$/, () => [\"ordered\"]],\n      [/^\\[( |x)?\\]$/i, (m) => [\"task\", {}, m[1]?.toLowerCase() === \"x\"]],\n      [/^>$/, () => [\"quote\"]],\n    ]\n    for (const [re, make] of rules) {\n      const m = text.match(re)\n      if (!m) continue\n      const [type, attrs, checked] = make(m)\n      const trimmed = deleteSelection({ ...state, selection: { anchor: { block: pos.block, offset: 0 }, focus: pos } })\n      const next = setBlock(trimmed, type, attrs)\n      if (type === \"task\" && checked) next.doc[pos.block] = { ...next.doc[pos.block]!, checked: true }\n      return next\n    }\n  }\n  if (typed === \"enter\" && b.type === \"paragraph\" && pos.offset === blockLength(b)) {\n    if (/^```(\\w*)$/.test(blockText(b))) {\n      const language = blockText(b).slice(3) || undefined\n      const emptied = { ...state, doc: state.doc.map((x, i) => (i === pos.block ? { ...x, content: [] } : x)), selection: caret({ block: pos.block, offset: 0 }) }\n      return setBlock(emptied, \"code\", { language })\n    }\n    if (/^(-{3,}|\\*{3,}|_{3,})$/.test(blockText(b))) {\n      const doc = state.doc.slice()\n      doc[pos.block] = block(\"divider\")\n      const next = withDoc(state, [...doc.slice(0, pos.block + 1), paragraph(), ...doc.slice(pos.block + 1)], caret({ block: pos.block + 1, offset: 0 }))\n      return next\n    }\n  }\n  // Inline: the closing delimiter was just typed (it isn't in the text yet).\n  const inline: [string, MarkName][] = [\n    [\"**\", \"bold\"],\n    [\"__\", \"bold\"],\n    [\"~~\", \"strike\"],\n    [\"*\", \"italic\"],\n    [\"_\", \"italic\"],\n    [\"`\", \"code\"],\n  ]\n  for (const [delim, mark] of inline) {\n    const withTyped = text + typed\n    if (!withTyped.endsWith(delim)) continue\n    const body = withTyped.slice(0, -delim.length)\n    const open = body.lastIndexOf(delim)\n    if (open < 0) continue\n    const inner = body.slice(open + delim.length)\n    // Not empty, not padded with spaces, and a single * isn't half of a **.\n    if (!inner || /^\\s|\\s$/.test(inner) || inner.includes(OBJECT)) continue\n    if (delim.length === 1 && (body[open - 1] === delim || inner.startsWith(delim))) continue\n    // Inside a word it's text, as Markdown reads it: my_var_name, 2*3*4, a URL.\n    if (delim !== \"`\" && open > 0 && /[\\p{L}\\p{N}_]/u.test(body[open - 1]!)) continue\n    // The typed part of the closing delimiter: everything but what's already in the text.\n    const already = delim.length - typed.length\n    const start = open\n    const end = pos.offset - already\n    let next: EditorState = { ...state, selection: { anchor: { block: pos.block, offset: start + delim.length }, focus: { block: pos.block, offset: end } } }\n    next = mapMarks(next, (m) => cleanMarks({ ...(m ?? {}), [mark]: true }))\n    // Drop the delimiters (closing part already in the text first, then the opening).\n    if (already > 0) next = deleteSelection({ ...next, selection: { anchor: { block: pos.block, offset: end }, focus: { block: pos.block, offset: end + already } } })\n    next = deleteSelection({ ...next, selection: { anchor: { block: pos.block, offset: start }, focus: { block: pos.block, offset: start + delim.length } } })\n    const caretAt = end - delim.length\n    // What's typed next isn't marked.\n    const after = typingMarks({ ...next, selection: caret({ block: pos.block, offset: caretAt }) }) ?? {}\n    const { [mark]: _drop, ...rest } = after as Marks\n    return { ...next, selection: caret({ block: pos.block, offset: caretAt }), stored: cleanMarks(rest) ?? {} }\n  }\n  return null\n}\n\n/* ------------------------------------------------------------------ Links */\n\n/** A link target people can safely follow: http(s), mailto, tel, or a relative path. */\nfunction safeHref(href: string): string | null {\n  const value = href.trim()\n  if (!value) return null\n  // \"//host\" and \"/\\\\host\" are other sites, not paths.\n  if (/^\\/[\\\\/]/.test(value)) return null\n  if (/^(\\/|\\.\\/|\\.\\.\\/|#|\\?)/.test(value)) return value\n  if (/^(mailto|tel):/i.test(value)) return value\n  // A bare domain gets https.\n  const withScheme = /^[a-z][\\w+.-]*:/i.test(value) ? value : /^[\\w-]+(\\.[\\w-]+)+(\\/|$|\\?|#)/.test(value) ? `https://${value}` : null\n  if (!withScheme) return null\n  try {\n    const url = new URL(withScheme)\n    return url.protocol === \"http:\" || url.protocol === \"https:\" ? url.href : null\n  } catch {\n    return null\n  }\n}\n\n/** An image source that's safe to show: http(s), or an inline PNG, GIF, JPEG, WebP or AVIF. */\nfunction safeImage(src: string | null | undefined): string | null {\n  if (!src) return null\n  if (/^data:image\\/(png|gif|jpe?g|webp|avif);/i.test(src)) return src\n  const href = safeHref(src)\n  return href && /^https?:/i.test(href) ? href : null\n}\n\n/* ------------------------------------------------------------------ Untrusted documents */\n\nconst BLOCK_TYPES = new Set<BlockType>([\"paragraph\", \"heading\", \"quote\", \"code\", \"bullet\", \"ordered\", \"task\", \"divider\", \"image\"])\nconst whole = (value: unknown, min: number, max: number, fallback: number) => {\n  const n = Math.trunc(Number(value))\n  return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : fallback\n}\n\nfunction sanitizeMarks(raw: unknown): Marks | undefined {\n  if (!raw || typeof raw !== \"object\") return undefined\n  const m = raw as Record<string, unknown>\n  const out: Marks = {}\n  for (const name of marks) if (m[name] === true) out[name] = true\n  if (typeof m.link === \"string\") {\n    const link = safeHref(m.link)\n    if (link) out.link = link\n  }\n  return Object.keys(out).length ? out : undefined\n}\n\nfunction sanitizeContent(raw: unknown): Inline[] {\n  if (!Array.isArray(raw)) return []\n  const out: Inline[] = []\n  for (const r of raw.slice(0, 10000)) {\n    if (!r || typeof r !== \"object\") continue\n    const run = r as Record<string, unknown>\n    if (run.type === \"mention\") {\n      out.push({ type: \"mention\", id: String(run.id ?? \"\"), label: String(run.label ?? \"\"), trigger: typeof run.trigger === \"string\" ? run.trigger.slice(0, 4) : \"@\" })\n      continue\n    }\n    const text = typeof run.text === \"string\" ? run.text : String(run.text ?? \"\")\n    const m = sanitizeMarks(run.marks)\n    out.push(m ? { text, marks: m } : { text })\n  }\n  return out\n}\n\n/**\n * A document from outside (the clipboard, storage, an app) made safe to edit and show:\n * known block types only, levels and indents in range, links and images that pass the\n * same checks typing them does, and strings where strings belong.\n */\nfunction sanitizeDoc(raw: unknown): Doc {\n  if (!Array.isArray(raw)) return []\n  const out: Doc = []\n  for (const r of raw.slice(0, 10000)) {\n    if (!r || typeof r !== \"object\") continue\n    const b = r as Record<string, unknown>\n    const type: BlockType = BLOCK_TYPES.has(b.type as BlockType) ? (b.type as BlockType) : \"paragraph\"\n    const next: Block = { id: typeof b.id === \"string\" && b.id ? b.id.slice(0, 64) : newId(), type, content: type === \"divider\" || type === \"image\" ? [] : normalize(sanitizeContent(b.content)) }\n    if (type === \"heading\") next.level = whole(b.level, 1, 3, 1) as 1 | 2 | 3\n    if (type === \"bullet\" || type === \"ordered\" || type === \"task\") next.indent = whole(b.indent, 0, MAX_INDENT, 0)\n    if (type === \"task\") next.checked = b.checked === true\n    if (type === \"code\" && typeof b.language === \"string\" && b.language) next.language = b.language.replace(/[^\\w+#.-]/g, \"\").slice(0, 32)\n    if (type === \"image\") {\n      const src = safeImage(typeof b.src === \"string\" ? b.src : null)\n      if (!src) continue\n      next.src = src\n      next.alt = typeof b.alt === \"string\" ? b.alt : \"\"\n    }\n    out.push(next)\n  }\n  return out\n}\n\n/* ------------------------------------------------------------------ State */\n\nfunction createState(doc: Doc = [paragraph()]): EditorState {\n  return { doc: ensureDoc(sanitizeDoc(doc)), selection: null, stored: null }\n}\n\n/** Two documents read the same (ignoring block ids). */\nfunction sameDoc(a: Doc, b: Doc) {\n  if (a.length !== b.length) return false\n  return a.every((x, i) => {\n    const y = b[i]!\n    const { id: _a, ...rx } = x\n    const { id: _b, ...ry } = y\n    return JSON.stringify(rx) === JSON.stringify(ry)\n  })\n}\n\nconst isEmpty = (doc: Doc) => doc.length === 1 && doc[0]!.type === \"paragraph\" && blockLength(doc[0]!) === 0\n\n/** Characters and words, as people count them (a mention is one word). */\nfunction counts(doc: Doc) {\n  const text = doc.map(plainText).join(\"\\n\")\n  const words = [...segmenter(\"word\").segment(text)].filter((s) => s.isWordLike).length\n  return { characters: [...segmenter(\"grapheme\").segment(text.replace(/\\n/g, \"\"))].length, words }\n}\n\nexport {\n  activeBlock,\n  activeLink,\n  block,\n  blockLength,\n  blockText,\n  caret,\n  collapsed,\n  counts,\n  createState,\n  deleteBy,\n  deleteSelection,\n  fragment,\n  indent,\n  inputRule,\n  insertBlock,\n  insertContent,\n  insertFragment,\n  insertLineBreak,\n  insertMention,\n  insertText,\n  isEmpty,\n  isList,\n  isMention,\n  isVoid,\n  linkRange,\n  markActive,\n  marksAtPosition,\n  MAX_INDENT,\n  newId,\n  normalize,\n  OBJECT,\n  ordered,\n  outdent,\n  paragraph,\n  plainText,\n  replaceRange,\n  runLength,\n  safeHref,\n  safeImage,\n  sanitizeDoc,\n  sameDoc,\n  select,\n  selectAll,\n  setBlock,\n  setLink,\n  splitBlock,\n  splitContent,\n  toggleMark,\n  toggleTask,\n  typingMarks,\n}\nexport type { Block, BlockType, Doc, EditorState, Inline, MarkName, Marks, MentionRun, Position, Selection, TextBlockType, TextRun }\n",
      "type": "registry:file",
      "target": "@ui/rich-text/model.ts"
    },
    {
      "path": "registry/uiset/ui/rich-text/serialize.ts",
      "content": "// The rich text document in and out: HTML (to store, render or paste), Markdown (for\n// agents, docs and paste from editors that copy it) and plain text. Reading HTML keeps\n// only what the editor can show and drops everything else, scripts and styles included,\n// so pasted or stored HTML can't bring code along.\n\nimport {\n  block,\n  blockLength,\n  isList,\n  isMention,\n  normalize,\n  paragraph,\n  plainText,\n  safeHref,\n  safeImage,\n  type Block,\n  type Doc,\n  type Inline,\n  type Marks,\n} from \"./model\"\n\n/* ------------------------------------------------------------------ HTML out */\n\nconst headingLevel = (b: Block) => Math.min(3, Math.max(1, Math.trunc(Number(b.level)) || 1))\n/** A list item's depth, kept in range whatever document comes in. */\nconst listIndent = (b: Block) => Math.min(4, Math.max(0, Math.trunc(Number(b.indent)) || 0))\n\nconst escapeHtml = (text: string) =>\n  text.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").replace(/\"/g, \"&quot;\")\n\nfunction inlineHtml(content: Inline[]): string {\n  return content\n    .map((run) => {\n      if (isMention(run)) return `<span data-mention=\"${escapeHtml(run.id)}\" data-trigger=\"${escapeHtml(run.trigger ?? \"@\")}\">${escapeHtml(`${run.trigger ?? \"@\"}${run.label}`)}</span>`\n      let html = escapeHtml(run.text).replace(/\\n/g, \"<br>\")\n      const m = run.marks ?? {}\n      if (m.code) html = `<code>${html}</code>`\n      if (m.bold) html = `<strong>${html}</strong>`\n      if (m.italic) html = `<em>${html}</em>`\n      if (m.underline) html = `<u>${html}</u>`\n      if (m.strike) html = `<s>${html}</s>`\n      if (m.link) html = `<a href=\"${escapeHtml(m.link)}\">${html}</a>`\n      return html\n    })\n    .join(\"\")\n}\n\nconst listTag = (b: Block) => (b.type === \"ordered\" ? \"ol\" : \"ul\")\n\n/** The document as clean HTML: lists nest by indent, tasks carry `data-checked`. */\nfunction toHTML(doc: Doc): string {\n  let html = \"\"\n  // Open lists, outermost first: [tag, indent].\n  const open: { tag: string; indent: number; task: boolean }[] = []\n  const closeTo = (indent: number) => {\n    while (open.length && open.at(-1)!.indent >= indent) html += `</li></${open.pop()!.tag}>`\n  }\n  for (const [i, b] of doc.entries()) {\n    if (isList(b)) {\n      const indent = listIndent(b)\n      const tag = listTag(b)\n      const task = b.type === \"task\"\n      // Deeper lists end first; a different kind of list at this level ends too.\n      closeTo(indent + 1)\n      const top = open.at(-1)\n      if (top && top.indent === indent && (top.tag !== tag || top.task !== task)) closeTo(indent)\n      if (open.at(-1)?.indent === indent) html += \"</li>\"\n      else {\n        while ((open.at(-1)?.indent ?? -1) < indent) {\n          const level = (open.at(-1)?.indent ?? -1) + 1\n          html += task && level === indent ? `<${tag} data-type=\"task\">` : `<${tag}>`\n          open.push({ tag, indent: level, task: task && level === indent })\n          if (level < indent) html += \"<li>\"\n        }\n      }\n      html += task ? `<li data-checked=\"${b.checked ? \"true\" : \"false\"}\">${inlineHtml(b.content)}` : `<li>${inlineHtml(b.content)}`\n      continue\n    }\n    closeTo(0)\n    // A run of quote blocks is one quote, a paragraph each.\n    if (b.type === \"quote\") {\n      html += `${doc[i - 1]?.type === \"quote\" ? \"\" : \"<blockquote>\"}<p>${inlineHtml(b.content)}</p>`\n      if (doc[i + 1]?.type !== \"quote\") html += \"</blockquote>\"\n      continue\n    }\n    switch (b.type) {\n      case \"heading\":\n        html += `<h${headingLevel(b)}>${inlineHtml(b.content)}</h${headingLevel(b)}>`\n        break\n      case \"code\":\n        html += `<pre><code${b.language ? ` class=\"language-${escapeHtml(b.language)}\"` : \"\"}>${escapeHtml(plainText(b))}</code></pre>`\n        break\n      case \"divider\":\n        html += \"<hr>\"\n        break\n      case \"image\":\n        html += b.src ? `<img src=\"${escapeHtml(b.src)}\" alt=\"${escapeHtml(b.alt ?? \"\")}\">` : \"\"\n        break\n      default:\n        html += `<p>${inlineHtml(b.content)}</p>`\n    }\n  }\n  closeTo(0)\n  return html\n}\n\n/* ------------------------------------------------------------------ HTML in */\n\nconst BLOCK_TAGS = new Set([\"P\", \"DIV\", \"H1\", \"H2\", \"H3\", \"H4\", \"H5\", \"H6\", \"BLOCKQUOTE\", \"PRE\", \"UL\", \"OL\", \"LI\", \"HR\", \"IMG\", \"TABLE\", \"TR\", \"SECTION\", \"ARTICLE\", \"HEADER\", \"FOOTER\", \"FIGURE\"])\nconst DROP_TAGS = new Set([\"SCRIPT\", \"STYLE\", \"TEMPLATE\", \"NOSCRIPT\", \"IFRAME\", \"OBJECT\", \"EMBED\", \"SVG\", \"MATH\", \"HEAD\", \"TITLE\", \"META\", \"LINK\", \"BUTTON\", \"SELECT\", \"TEXTAREA\"])\n\n/** An image source that can't run code: http(s), or a data: image. */\n\n/** Marks that an element adds to its text, including the inline styles Google Docs and Word use. */\nfunction marksOf(el: Element, inherited: Marks): Marks {\n  const m: Marks = { ...inherited }\n  const tag = el.tagName\n  if (tag === \"B\" || tag === \"STRONG\") m.bold = true\n  if (tag === \"I\" || tag === \"EM\") m.italic = true\n  if (tag === \"U\" || tag === \"INS\") m.underline = true\n  if (tag === \"S\" || tag === \"STRIKE\" || tag === \"DEL\") m.strike = true\n  if (tag === \"CODE\" || tag === \"KBD\" || tag === \"SAMP\" || tag === \"TT\") m.code = true\n  if (tag === \"A\") {\n    const href = safeHref(el.getAttribute(\"href\") ?? \"\")\n    if (href) m.link = href\n  }\n  const style = (el as HTMLElement).style\n  if (style) {\n    const weight = style.fontWeight\n    if (weight === \"bold\" || Number(weight) >= 600) m.bold = true\n    if (weight === \"normal\" || (Number(weight) > 0 && Number(weight) < 600)) delete m.bold\n    if (style.fontStyle === \"italic\") m.italic = true\n    if (style.fontStyle === \"normal\") delete m.italic\n    const deco = style.textDecorationLine || style.textDecoration\n    if (deco?.includes(\"underline\")) m.underline = true\n    if (deco?.includes(\"line-through\")) m.strike = true\n  }\n  return m\n}\n\ntype ReadContext = { marks: Marks; listIndent: number; listType: \"bullet\" | \"ordered\" | \"task\" | null; inPre: boolean; quote: boolean }\n\n/** Reads HTML into blocks, keeping only what the editor can show. Pass a DOMParser outside a browser. */\nfunction fromHTML(html: string, parser: DOMParser = new DOMParser()): Doc {\n  const dom = parser.parseFromString(html, \"text/html\")\n  const doc: Doc = []\n  let current: Block | null = null\n  const flush = () => {\n    if (current && (current.content.length || current.type !== \"paragraph\")) {\n      current.content = normalize(current.content)\n      doc.push(current)\n    }\n    current = null\n  }\n  const start = (b: Block) => {\n    flush()\n    current = b\n  }\n  const text = (value: string, ctx: ReadContext) => {\n    const t = ctx.inPre ? value : value.replace(/[\\t\\r\\n ]+/g, \" \")\n    if (!t) return\n    if (!current) {\n      if (!ctx.inPre && !t.trim()) return\n      current = block(ctx.quote ? \"quote\" : \"paragraph\")\n    }\n    const prev = current.content.at(-1)\n    // Collapse a space at a block's start or after another space, as browsers render it.\n    const trimmed = !ctx.inPre && (!prev || (!isMention(prev) && prev.text.endsWith(\" \"))) ? t.replace(/^ /, \"\") : t\n    if (trimmed) current.content.push({ text: trimmed, ...(Object.keys(ctx.marks).length && current.type !== \"code\" ? { marks: { ...ctx.marks } } : {}) })\n  }\n  const walk = (node: Node, ctx: ReadContext) => {\n    if (node.nodeType === 3) return text(node.nodeValue ?? \"\", ctx)\n    if (node.nodeType !== 1) return\n    const el = node as Element\n    const tag = el.tagName\n    if (DROP_TAGS.has(tag)) return\n    if ((el as HTMLElement).hidden || (el as HTMLElement).style?.display === \"none\") return\n    if (tag === \"BR\") {\n      if (current) current.content.push({ text: \"\\n\", ...(Object.keys(ctx.marks).length ? { marks: { ...ctx.marks } } : {}) })\n      return\n    }\n    if (tag === \"HR\") {\n      flush()\n      doc.push(block(\"divider\"))\n      return\n    }\n    if (tag === \"IMG\") {\n      const src = safeImage(el.getAttribute(\"src\"))\n      if (!src) return\n      flush()\n      doc.push(block(\"image\", [], { src, alt: el.getAttribute(\"alt\") ?? \"\" }))\n      return\n    }\n    if (el.hasAttribute(\"data-mention\")) {\n      if (!current) current = block(\"paragraph\")\n      const trigger = el.getAttribute(\"data-trigger\") ?? \"@\"\n      const text = el.textContent ?? \"\"\n      const label = trigger && text.startsWith(trigger) ? text.slice(trigger.length) : text\n      current.content.push({ type: \"mention\", id: el.getAttribute(\"data-mention\")!, label, trigger })\n      return\n    }\n    if (tag === \"UL\" || tag === \"OL\") {\n      flush()\n      const task = el.getAttribute(\"data-type\") === \"task\" || !!el.querySelector(\":scope > li > input[type=checkbox]\")\n      const inner: ReadContext = { ...ctx, listIndent: ctx.listType ? ctx.listIndent + 1 : 0, listType: task ? \"task\" : tag === \"OL\" ? \"ordered\" : \"bullet\" }\n      for (const child of el.childNodes) walk(child, inner)\n      flush()\n      return\n    }\n    if (tag === \"LI\") {\n      const type = ctx.listType ?? \"bullet\"\n      const box = el.querySelector(\":scope > input[type=checkbox]\") as HTMLInputElement | null\n      const checked = el.getAttribute(\"data-checked\") === \"true\" || el.getAttribute(\"aria-checked\") === \"true\" || !!box?.hasAttribute(\"checked\")\n      start(block(type, [], { indent: Math.min(4, ctx.listIndent), ...(type === \"task\" ? { checked } : {}) }))\n      for (const child of el.childNodes) {\n        if ((child as Element).tagName === \"INPUT\") continue\n        // A paragraph inside an item is the item's text, not a new block.\n        if ((child as Element).tagName === \"P\") for (const c of child.childNodes) walk(c, ctx)\n        else walk(child, ctx)\n      }\n      flush()\n      return\n    }\n    const heading = /^H([1-6])$/.exec(tag)\n    if (heading) {\n      start(block(\"heading\", [], { level: Math.min(3, Number(heading[1])) as 1 | 2 | 3 }))\n      for (const child of el.childNodes) walk(child, { ...ctx, marks: {} })\n      flush()\n      return\n    }\n    if (tag === \"PRE\") {\n      const code = el.querySelector(\"code\")\n      const language = /language-([\\w+-]+)/.exec(code?.className ?? \"\")?.[1]\n      start(block(\"code\", [], language ? { language } : {}))\n      current!.content.push({ text: (el.textContent ?? \"\").replace(/\\n$/, \"\") })\n      flush()\n      return\n    }\n    if (tag === \"BLOCKQUOTE\") {\n      flush()\n      for (const child of el.childNodes) walk(child, { ...ctx, quote: true })\n      flush()\n      return\n    }\n    // A table row is a line, its cells apart by a tab, so pasted tables stay readable.\n    if (tag === \"TD\" || tag === \"TH\") {\n      if (el.previousElementSibling) text(\"\\t\", { ...ctx, inPre: true })\n      const marks = marksOf(el, ctx.marks)\n      for (const child of el.childNodes) walk(child, { ...ctx, marks })\n      return\n    }\n    if (BLOCK_TAGS.has(tag)) {\n      flush()\n      if (tag !== \"DIV\" || ctx.quote) current = block(ctx.quote ? \"quote\" : \"paragraph\")\n      for (const child of el.childNodes) walk(child, ctx)\n      flush()\n      return\n    }\n    const marks = marksOf(el, ctx.marks)\n    for (const child of el.childNodes) walk(child, { ...ctx, marks })\n  }\n  for (const child of dom.body.childNodes) walk(child, { marks: {}, listIndent: 0, listType: null, inPre: false, quote: false })\n  flush()\n  // Trailing line breaks at a block's end don't show; drop them.\n  for (const b of doc) {\n    const last = b.content.at(-1)\n    if (last && !isMention(last) && b.type !== \"code\") last.text = last.text.replace(/\\n+$/, \"\")\n    b.content = normalize(b.content)\n  }\n  return doc.length ? doc : [paragraph()]\n}\n\n/* ------------------------------------------------------------------ Markdown out */\n\nconst escapeMd = (text: string) =>\n  text\n    .replace(/([\\\\`*_~[\\]<>])/g, \"\\\\$1\")\n    .replace(/^(\\s*)([#>+-])(\\s)/gm, \"$1\\\\$2$3\")\n    // A number and its dot or parenthesis would start a list: the punctuation is escaped.\n    .replace(/^(\\s*)(\\d+)([.)])(\\s)/gm, \"$1$2\\\\$3$4\")\n    // A line of dashes would read back as a rule.\n    .replace(/^(\\s*)(-{3,}\\s*)$/gm, \"$1\\\\$2\")\n\n/** A link address for Markdown: in angle brackets when it holds parentheses or spaces. */\nconst mdDestination = (href: string) => (/[()\\s]/.test(href) ? `<${href.replace(/[<>]/g, encodeURIComponent)}>` : href)\n\nfunction inlineMd(content: Inline[]): string {\n  return content\n    .map((run) => {\n      if (isMention(run)) return `${run.trigger ?? \"@\"}${run.label}`\n      const m = run.marks ?? {}\n      if (m.code) {\n        // The fence is one backtick longer than any run inside; a backtick at an edge gets a space.\n        const longest = Math.max(0, ...(run.text.match(/`+/g) ?? []).map((t) => t.length))\n        const ticks = \"`\".repeat(longest + 1)\n        const pad = /^`|`$/.test(run.text) ? \" \" : \"\"\n        const code = `${ticks}${pad}${run.text}${pad}${ticks}`\n        return m.link ? `[${code}](${mdDestination(m.link)})` : code\n      }\n      // Delimiters hug the text; surrounding spaces stay outside them.\n      const [, lead, body, trail] = /^(\\s*)([\\s\\S]*?)(\\s*)$/.exec(run.text)!\n      if (!body) return run.text\n      let md = escapeMd(body!).replace(/\\n/g, \"  \\n\")\n      if (m.bold) md = `**${md}**`\n      if (m.italic) md = `*${md}*`\n      if (m.strike) md = `~~${md}~~`\n      if (m.underline) md = `<u>${md}</u>`\n      if (m.link) md = `[${md}](${mdDestination(m.link)})`\n      return `${lead}${md}${trail}`\n    })\n    .join(\"\")\n}\n\n/** The document as Markdown (GitHub flavored: tasks, strikethrough, fenced code). */\nfunction toMarkdown(doc: Doc): string {\n  const out: string[] = []\n  const counters: number[] = []\n  doc.forEach((b, i) => {\n    const prev = doc[i - 1]\n    const list = isList(b)\n    // A blank line between blocks, except between items of the same list.\n    // Quote blocks in a row stay one quote, with a \">\" line between them.\n    if (i > 0 && !(list && prev && isList(prev))) out.push(b.type === \"quote\" && prev?.type === \"quote\" ? \">\" : \"\")\n    if (!list) counters.length = 0\n    switch (b.type) {\n      case \"heading\":\n        out.push(`${\"#\".repeat(b.level ?? 1)} ${inlineMd(b.content)}`)\n        break\n      case \"quote\":\n        out.push(`> ${inlineMd(b.content).replace(/\\n/g, \"\\n> \")}`)\n        break\n      case \"code\": {\n        const body = plainText(b)\n        const fence = body.includes(\"```\") ? \"````\" : \"```\"\n        out.push(`${fence}${b.language ?? \"\"}\\n${body}\\n${fence}`)\n        break\n      }\n      case \"divider\":\n        out.push(\"---\")\n        break\n      case \"image\":\n        out.push(`![${(b.alt ?? \"\").replace(/[[\\]]/g, \"\")}](${mdDestination(b.src ?? \"\")})`)\n        break\n      case \"bullet\":\n      case \"ordered\":\n      case \"task\": {\n        const indent = listIndent(b)\n        counters.length = indent + 1\n        counters[indent] = b.type === \"ordered\" ? (counters[indent] ?? 0) + 1 : 0\n        const marker = b.type === \"ordered\" ? `${counters[indent]}.` : b.type === \"task\" ? `- [${b.checked ? \"x\" : \" \"}]` : \"-\"\n        out.push(`${\"  \".repeat(indent)}${marker} ${inlineMd(b.content)}`)\n        break\n      }\n      default:\n        out.push(inlineMd(b.content))\n    }\n  })\n  return out.join(\"\\n\")\n}\n\n/* ------------------------------------------------------------------ Markdown in */\n\n/** Reads inline Markdown: **bold**, _italic_, ~~strike~~, `code`, [links](url), <u>underline</u>. */\nfunction parseInline(source: string, marks: Marks = {}): Inline[] {\n  const runs: Inline[] = []\n  let i = 0\n  let buffer = \"\"\n  const push = (text: string, m: Marks) => text && runs.push({ text, ...(Object.keys(m).length ? { marks: { ...m } } : {}) })\n  const flush = () => {\n    push(buffer, marks)\n    buffer = \"\"\n  }\n  while (i < source.length) {\n    const rest = source.slice(i)\n    if (rest[0] === \"\\\\\" && rest[1] && /[\\\\`*_~[\\]<>#+\\-.!()]/.test(rest[1])) {\n      buffer += rest[1]\n      i += 2\n      continue\n    }\n    const code = /^(`+)([\\s\\S]+?)\\1/.exec(rest)\n    if (code) {\n      flush()\n      push(code[2]!.replace(/^ (.*) $/, \"$1\"), { ...marks, code: true })\n      i += code[0].length\n      continue\n    }\n    const link = /^\\[((?:\\\\.|[^\\]\\\\])*)\\]\\((?:<([^>]*)>|([^)\\s]+))(?:\\s+\"[^\"]*\")?\\)/.exec(rest)\n    if (link) {\n      flush()\n      const href = safeHref(link[2] ?? link[3]!)\n      runs.push(...parseInline(link[1]!, href ? { ...marks, link: href } : marks))\n      i += link[0].length\n      continue\n    }\n    const under = /^<u>([\\s\\S]+?)<\\/u>/.exec(rest)\n    if (under) {\n      flush()\n      runs.push(...parseInline(under[1]!, { ...marks, underline: true }))\n      i += under[0].length\n      continue\n    }\n    const pairs: [RegExp, keyof Marks][] = [\n      [/^\\*\\*(?=\\S)([\\s\\S]*?\\S)\\*\\*/, \"bold\"],\n      [/^__(?=\\S)([\\s\\S]*?\\S)__/, \"bold\"],\n      [/^~~(?=\\S)([\\s\\S]*?\\S)~~/, \"strike\"],\n      [/^\\*(?=\\S)([\\s\\S]*?\\S)\\*/, \"italic\"],\n      [/^_(?=\\S)([\\s\\S]*?\\S)_(?![\\w])/, \"italic\"],\n    ]\n    const hit = pairs.map(([re, mark]) => [re.exec(rest), mark] as const).find(([m]) => m)\n    if (hit && !(hit[1] === \"italic\" && rest[0] === \"_\" && /\\w/.test(source[i - 1] ?? \"\"))) {\n      flush()\n      runs.push(...parseInline(hit[0]![1]!, { ...marks, [hit[1]]: true }))\n      i += hit[0]![0].length\n      continue\n    }\n    if (rest.startsWith(\"  \\n\") || rest.startsWith(\"\\\\\\n\")) {\n      buffer += \"\\n\"\n      i += 3\n      continue\n    }\n    buffer += rest[0]\n    i += 1\n  }\n  flush()\n  return normalize(runs)\n}\n\n/** Lines of one paragraph: two trailing spaces are a hard break (kept), one is a soft break. */\nconst softBreaks = (text: string) => text.replace(/[ \\t]+\\n/g, (m) => (m.length >= 3 ? \"  \\n\" : \" \"))\n\n/** Reads Markdown into blocks: headings, lists (nested, numbered, tasks), quotes, fenced code, rules and images. */\nfunction fromMarkdown(markdown: string): Doc {\n  const lines = markdown.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\")\n  const doc: Doc = []\n  let para: string[] = []\n  const flushPara = () => {\n    if (para.length) doc.push(block(\"paragraph\", parseInline(softBreaks(para.join(\"\\n\")))))\n    para = []\n  }\n  let quoteOpen = false\n  let quoteLines: string[] = []\n  for (let i = 0; i < lines.length; i++) {\n    const line = lines[i]!\n    // Whether the line before was a quote line (anything else, a blank line too, ends a quote).\n    const inQuote = quoteOpen\n    quoteOpen = false\n    const fence = /^(\\s*)(`{3,}|~{3,})\\s*([\\w+-]*)\\s*$/.exec(line)\n    if (fence) {\n      flushPara()\n      const body: string[] = []\n      i++\n      while (i < lines.length && !lines[i]!.trim().startsWith(fence[2]!)) body.push(lines[i++]!)\n      doc.push(block(\"code\", [{ text: body.join(\"\\n\") }], fence[3] ? { language: fence[3] } : {}))\n      continue\n    }\n    if (!line.trim()) {\n      flushPara()\n      continue\n    }\n    const heading = /^(#{1,6})\\s+(.*?)(?:\\s+#+)?\\s*$/.exec(line)\n    if (heading) {\n      flushPara()\n      doc.push(block(\"heading\", parseInline(heading[2]!), { level: Math.min(3, heading[1]!.length) as 1 | 2 | 3 }))\n      continue\n    }\n    if (/^\\s*([-*_])(\\s*\\1){2,}\\s*$/.test(line)) {\n      flushPara()\n      doc.push(block(\"divider\"))\n      continue\n    }\n    const image = /^!\\[([^\\]]*)\\]\\((?:<([^>]*)>|([^)\\s]+))\\)\\s*$/.exec(line.trim())\n    if (image) {\n      flushPara()\n      const src = safeImage(image[2] ?? image[3]!)\n      if (src) doc.push(block(\"image\", [], { src, alt: image[1] }))\n      continue\n    }\n    const quote = /^\\s*>\\s?(.*)$/.exec(line)\n    if (quote) {\n      flushPara()\n      const text = quote[1]!\n      const prev = doc.at(-1)\n      // Lines of one quote are one block, with line breaks; a bare \">\" starts the next block.\n      if (!text.trim()) quoteOpen = false\n      else if (inQuote && prev?.type === \"quote\") {\n        quoteLines.push(text)\n        doc[doc.length - 1] = { ...prev, content: parseInline(softBreaks(quoteLines.join(\"\\n\"))) }\n        quoteOpen = true\n      } else {\n        quoteLines = [text]\n        doc.push(block(\"quote\", parseInline(text)))\n        quoteOpen = true\n      }\n      continue\n    }\n    const item = /^(\\s*)([-*+]|\\d+[.)])\\s+(\\[( |x|X)\\]\\s+)?(.*)$/.exec(line)\n    if (item) {\n      flushPara()\n      const indent = Math.min(4, Math.floor(item[1]!.replace(/\\t/g, \"  \").length / 2))\n      const content = parseInline(item[5]!)\n      if (item[3]) doc.push(block(\"task\", content, { indent, checked: item[4]!.toLowerCase() === \"x\" }))\n      else doc.push(block(/\\d/.test(item[2]!) ? \"ordered\" : \"bullet\", content, { indent }))\n      continue\n    }\n    para.push(line)\n  }\n  flushPara()\n  return doc.length ? doc : [paragraph()]\n}\n\n/* ------------------------------------------------------------------ Text */\n\n/** The document as plain text: one block per line, list items with their markers. */\nfunction toText(doc: Doc): string {\n  return doc\n    .map((b) => {\n      if (b.type === \"divider\") return \"---\"\n      if (b.type === \"image\") return b.alt ?? \"\"\n      const text = plainText(b)\n      if (b.type === \"bullet\") return `${\"  \".repeat(b.indent ?? 0)}• ${text}`\n      if (b.type === \"task\") return `${\"  \".repeat(b.indent ?? 0)}${b.checked ? \"☑\" : \"☐\"} ${text}`\n      if (b.type === \"ordered\") return `${\"  \".repeat(b.indent ?? 0)}${text}`\n      return text\n    })\n    .join(\"\\n\")\n}\n\n/** Whether a document has anything in it (for \"required\"). */\nconst hasContent = (doc: Doc) => doc.some((b) => b.type === \"divider\" || b.type === \"image\" || blockLength(b) > 0)\n\n/**\n * An agent's new Markdown applied to a document. Unchanged text changes nothing; text that\n * only adds to the end (an agent's insert) appends its blocks, so what's there keeps what\n * Markdown can't say (mentions, line breaks inside items, empty lines); anything else\n * replaces the document.\n */\nfunction applyMarkdown(doc: Doc, next: string): Doc {\n  const current = toMarkdown(doc).trimEnd()\n  if (next.trimEnd() === current) return doc\n  if (current && next.startsWith(current) && /^\\n\\n/.test(next.slice(current.length))) {\n    const kept = doc.slice()\n    while (kept.length > 1 && kept.at(-1)!.type === \"paragraph\" && !blockLength(kept.at(-1)!)) kept.pop()\n    return [...kept, ...fromMarkdown(next.slice(current.length))]\n  }\n  return fromMarkdown(next)\n}\n\nexport { applyMarkdown, escapeHtml, fromHTML, fromMarkdown, hasContent, parseInline, safeImage, toHTML, toMarkdown, toText }\n",
      "type": "registry:file",
      "target": "@ui/rich-text/serialize.ts"
    },
    {
      "path": "registry/uiset/ui/rich-text/view.ts",
      "content": "// The rich text editor on the page, without a framework: it draws the document into an\n// editable element, keeps the caret in sync both ways, and turns what people do (typing,\n// dictation, input methods, Enter, Backspace, shortcuts, paste, drop) into the document\n// edits in model.ts. The React editor and the web element both mount it, so they behave\n// the same. The browser never edits the DOM by itself: each input is cancelled and\n// applied to the document, except text an input method is still composing, which is read\n// back once it's done.\n\nimport { announce, createUndoStack, isComposing, matchesShortcut } from \"@ui-sdk/core\"\nimport type { EditorChange, TextEditorAdapter, TextRange, TokenInsert } from \"@ui-sdk/core/trigger-menu\"\nimport {\n  plainText,\n  typingMarks,\n  OBJECT,\n  insertContent,\n  sanitizeDoc,\n  activeBlock,\n  block,\n  blockLength,\n  blockText,\n  caret,\n  collapsed,\n  createState,\n  deleteBy,\n  deleteSelection,\n  fragment,\n  indent,\n  inputRule,\n  insertBlock,\n  insertFragment,\n  insertLineBreak,\n  insertMention,\n  insertText,\n  isEmpty,\n  isList,\n  isMention,\n  isVoid,\n  markActive,\n  normalize,\n  ordered,\n  outdent,\n  replaceRange,\n  select,\n  setBlock,\n  splitBlock,\n  toggleMark,\n  toggleTask,\n  type Block,\n  type Doc,\n  type EditorState,\n  type Inline,\n  type MarkName,\n  type Marks,\n  type Position,\n  type Selection,\n} from \"./model\"\nimport { fromHTML, fromMarkdown, toHTML, toText } from \"./serialize\"\n\nconst MIME = \"application/x-uiset-rich-text\"\n\ntype ChangeReason = \"input\" | \"format\" | \"paste\" | \"drop\" | \"undo\" | \"redo\" | \"selection\" | \"set\" | \"composition\"\n\ntype ViewOptions = {\n  state?: EditorState\n  /** Called after every change to the document or the selection. */\n  onChange?: (state: EditorState, reason: ChangeReason) => void\n  /** Mod+K: open your link editor. */\n  onLinkRequest?: () => void\n  /** Mod+Enter outside a task item. */\n  onSubmit?: () => void\n  /** Pasted or dropped image files: upload and return where they live, or null to skip. */\n  uploadImage?: (file: File) => Promise<{ src: string; alt?: string } | null>\n  /** Words for announcements, for translation. */\n  messages?: Partial<Messages>\n}\n\ntype Messages = { markOn: (mark: string) => string; markOff: (mark: string) => string; block: (name: string) => string; undo: string; redo: string }\nconst english: Messages = {\n  markOn: (mark) => `${mark} on`,\n  markOff: (mark) => `${mark} off`,\n  block: (name) => name,\n  undo: \"Undone\",\n  redo: \"Redone\",\n}\nconst markNames: Record<MarkName, string> = { bold: \"Bold\", italic: \"Italic\", underline: \"Underline\", strike: \"Strikethrough\", code: \"Code\" }\n\n/* ------------------------------------------------------------------ Drawing */\n\nconst tagFor = (b: Block) => {\n  switch (b.type) {\n    case \"heading\":\n      return `h${b.level ?? 1}`\n    case \"quote\":\n      return \"blockquote\"\n    case \"code\":\n      return \"pre\"\n    case \"bullet\":\n    case \"ordered\":\n    case \"task\":\n      return \"li\"\n    case \"divider\":\n    case \"image\":\n      return \"div\"\n    default:\n      return \"p\"\n  }\n}\n\n/** One run as DOM: text (with <br> for line breaks) inside its mark elements, or a mention chip. */\nfunction drawRun(run: Inline): Node {\n  if (isMention(run)) {\n    const chip = document.createElement(\"span\")\n    chip.className = \"rich-text-mention\"\n    chip.contentEditable = \"false\"\n    chip.dataset.mention = run.id\n    chip.dataset.trigger = run.trigger ?? \"@\"\n    chip.textContent = `${run.trigger ?? \"@\"}${run.label}`\n    return chip\n  }\n  const frag = document.createDocumentFragment()\n  run.text.split(\"\\n\").forEach((part, i) => {\n    if (i > 0) frag.append(document.createElement(\"br\"))\n    if (part) frag.append(document.createTextNode(part))\n  })\n  let node: Node = frag\n  const m = run.marks ?? {}\n  const wrap = (tag: string, attrs: Record<string, string> = {}) => {\n    const el = document.createElement(tag)\n    for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, v)\n    el.append(node)\n    node = el\n  }\n  if (m.code) wrap(\"code\")\n  if (m.bold) wrap(\"strong\")\n  if (m.italic) wrap(\"em\")\n  if (m.underline) wrap(\"u\")\n  if (m.strike) wrap(\"s\")\n  if (m.link) wrap(\"a\", { href: m.link, rel: \"noopener noreferrer\", target: \"_blank\" })\n  return node\n}\n\nfunction drawBlock(b: Block, listNumber: number): HTMLElement {\n  const el = document.createElement(tagFor(b))\n  el.dataset.block = b.id\n  el.className = `rich-text-block rich-text-${b.type}`\n  if (b.type !== \"code\") el.dir = \"auto\"\n  if (b.type === \"divider\") {\n    el.contentEditable = \"false\"\n    el.append(document.createElement(\"hr\"))\n    return el\n  }\n  if (b.type === \"image\") {\n    el.contentEditable = \"false\"\n    const img = document.createElement(\"img\")\n    img.src = b.src ?? \"\"\n    img.alt = b.alt ?? \"\"\n    img.draggable = false\n    el.append(img)\n    return el\n  }\n  if (isList(b)) {\n    el.setAttribute(\"aria-level\", String((b.indent ?? 0) + 1))\n    el.dataset.indent = String(b.indent ?? 0)\n    if (b.type === \"ordered\") el.setAttribute(\"value\", String(listNumber))\n    if (b.type === \"task\") {\n      el.dataset.checked = String(!!b.checked)\n      const box = document.createElement(\"span\")\n      box.className = \"rich-text-check\"\n      box.contentEditable = \"false\"\n      box.setAttribute(\"role\", \"checkbox\")\n      box.setAttribute(\"aria-checked\", String(!!b.checked))\n      // Named by its task; checked or not is aria-checked's to say.\n      box.setAttribute(\"aria-label\", plainText(b).trim() || \"To-do\")\n      el.append(box)\n    }\n  }\n  const body = b.type === \"code\" ? document.createElement(\"code\") : el\n  if (b.type === \"code\") {\n    el.append(body)\n    if (b.language) el.dataset.language = b.language\n  }\n  for (const run of b.content) body.append(drawRun(run))\n  // An empty block, or one ending in a line break, needs a <br> to hold the caret's line.\n  const text = blockText(b)\n  if (!text || text.endsWith(\"\\n\")) {\n    const br = document.createElement(\"br\")\n    br.dataset.placeholder = \"\"\n    body.append(br)\n  }\n  return el\n}\n\n/** The element that holds a block's text (a code block's <code>, otherwise the block itself). */\nconst textHost = (el: HTMLElement): HTMLElement => (el.tagName === \"PRE\" ? ((el.querySelector(\":scope > code\") as HTMLElement) ?? el) : el)\n\n/** Where two documents first differ, as a caret in `next`: after any text `next` adds there. */\nfunction changePoint(prev: Doc, next: Doc): Selection | null {\n  const key = (b: Block) => JSON.stringify([b.type, b.level, b.indent, b.checked, b.content])\n  let i = 0\n  while (i < prev.length && i < next.length && key(prev[i]!) === key(next[i]!)) i++\n  if (i >= next.length) i = next.length - 1\n  if (i < 0) return null\n  const b = next[i]!\n  if (isVoid(b)) return caret({ block: i, offset: 0 })\n  const now = blockText(b)\n  const was = prev[i] && !isVoid(prev[i]!) ? blockText(prev[i]!) : \"\"\n  let start = 0\n  while (start < now.length && start < was.length && now[start] === was[start]) start++\n  let end = 0\n  while (end < now.length - start && end < was.length - start && now[now.length - 1 - end] === was[was.length - 1 - end]) end++\n  return caret({ block: i, offset: Math.max(start, now.length - end) })\n}\n\n/* ------------------------------------------------------------------ Positions */\n\n/** How many characters of a block's text come before (node, offset), with mentions as one and <br> as a newline. */\nfunction offsetIn(host: HTMLElement, node: Node, offset: number): number {\n  let count = 0\n  let done = false\n  const target = node.nodeType === 3 ? node : (node.childNodes[offset] ?? null)\n  const walk = (n: Node): void => {\n    if (done) return\n    if (n === target && node.nodeType !== 3) {\n      done = true\n      return\n    }\n    if (n.nodeType === 3) {\n      if (n === node) {\n        count += offset\n        done = true\n        return\n      }\n      count += (n.nodeValue ?? \"\").length\n      return\n    }\n    const el = n as HTMLElement\n    if (el.dataset?.mention !== undefined) {\n      count += 1\n      return\n    }\n    if (el.classList?.contains(\"rich-text-check\")) return\n    if (el.tagName === \"BR\") {\n      if (el.dataset.placeholder === undefined) count += 1\n      return\n    }\n    for (const child of n.childNodes) walk(child)\n    // A point after an element's last child (as after a <br> inside <strong>) ends there.\n    if (n === node && target === null) done = true\n  }\n  // A point inside a mention chip is before or after it.\n  const chip = (node.nodeType === 3 ? node.parentElement : (node as Element))?.closest?.(\"[data-mention]\")\n  if (chip && host.contains(chip)) return offsetIn(host, chip.parentNode!, [...chip.parentNode!.childNodes].indexOf(chip as ChildNode)) + (offset > 0 ? 1 : 0)\n  if (node === host && target === null) {\n    for (const child of host.childNodes) walk(child)\n    return count\n  }\n  for (const child of host.childNodes) walk(child)\n  return count\n}\n\n/** The DOM point for a character offset in a block. */\nfunction pointIn(host: HTMLElement, offset: number): [Node, number] {\n  let left = offset\n  let result: [Node, number] | null = null\n  const walk = (n: Node): void => {\n    if (result) return\n    if (n.nodeType === 3) {\n      const len = (n.nodeValue ?? \"\").length\n      if (left <= len) result = [n, left]\n      else left -= len\n      return\n    }\n    const el = n as HTMLElement\n    const index = () => [...n.parentNode!.childNodes].indexOf(n as ChildNode)\n    if (el.dataset?.mention !== undefined || (el.tagName === \"BR\" && el.dataset.placeholder === undefined)) {\n      if (left === 0) result = [n.parentNode!, index()]\n      else if (left === 1 && el.tagName !== \"BR\") result = [n.parentNode!, index() + 1]\n      else left -= 1\n      // After a <br>, the next line starts: the point is in front of what follows.\n      if (!result && el.tagName === \"BR\" && left === 0) result = [n.parentNode!, index() + 1]\n      return\n    }\n    if (el.classList?.contains(\"rich-text-check\") || el.tagName === \"BR\") return\n    for (const child of n.childNodes) walk(child)\n  }\n  for (const child of host.childNodes) walk(child)\n  if (result) return result\n  const last = host.lastChild\n  if (last && (last as HTMLElement).dataset?.placeholder !== undefined) return [host, host.childNodes.length - 1]\n  return [host, host.childNodes.length]\n}\n\n/** Reads a block's text and marks back from its DOM, after an input method wrote into it. */\nfunction readBlock(host: HTMLElement): Inline[] {\n  const runs: Inline[] = []\n  const walk = (n: Node, marks: Marks) => {\n    if (n.nodeType === 3) {\n      if (n.nodeValue) runs.push({ text: n.nodeValue, ...(Object.keys(marks).length ? { marks: { ...marks } } : {}) })\n      return\n    }\n    const el = n as HTMLElement\n    if (el.classList?.contains(\"rich-text-check\")) return\n    if (el.dataset?.mention !== undefined) {\n      const text = el.textContent ?? \"\"\n      const trigger = el.dataset.trigger ?? \"@\"\n      runs.push({ type: \"mention\", id: el.dataset.mention!, label: trigger && text.startsWith(trigger) ? text.slice(trigger.length) : text, trigger })\n      return\n    }\n    if (el.tagName === \"BR\") {\n      if (el.dataset.placeholder === undefined) runs.push({ text: \"\\n\", ...(Object.keys(marks).length ? { marks: { ...marks } } : {}) })\n      return\n    }\n    const m = { ...marks }\n    const tag = el.tagName\n    if (tag === \"STRONG\" || tag === \"B\") m.bold = true\n    if (tag === \"EM\" || tag === \"I\") m.italic = true\n    if (tag === \"U\") m.underline = true\n    if (tag === \"S\") m.strike = true\n    if (tag === \"CODE\" && host.tagName !== \"CODE\") m.code = true\n    if (tag === \"A\" && el.getAttribute(\"href\")) m.link = el.getAttribute(\"href\")!\n    for (const child of n.childNodes) walk(child, m)\n  }\n  for (const child of host.childNodes) walk(child, {})\n  return normalize(runs)\n}\n\n/* ------------------------------------------------------------------ The view */\n\ntype Listener = (state: EditorState, reason: ChangeReason) => void\n\nfunction createRichTextView(root: HTMLElement, options: ViewOptions = {}) {\n  let state = options.state ?? createState()\n  const messages = { ...english, ...options.messages }\n  const listeners = new Set<Listener>()\n  const adapterListeners = new Set<(change: EditorChange) => void>()\n  const undo = createUndoStack({ doc: state.doc, selection: state.selection }, { limit: 300, groupDelay: 700 })\n  const drawn = new Map<string, { block: Block; el: HTMLElement; number: number }>()\n  let composing = false\n  /** The block and marks typing would use when a composition started. */\n  let composeFrom: { block: Block; marks: Marks | undefined } | null = null\n  let applyingSelection = false\n  let readOnly = false\n  let destroyed = false\n  let lastSelectionKey = \"\"\n\n  root.contentEditable = \"true\"\n  root.setAttribute(\"role\", \"textbox\")\n  root.setAttribute(\"aria-multiline\", \"true\")\n  root.spellcheck = true\n  root.translate = true\n  root.classList.add(\"rich-text-content\")\n\n  /* -------------------------------------------------------- draw */\n\n  function draw() {\n    // List numbers per level: a numbered item counts on from the item before it at its level.\n    const counters: number[] = []\n    const wanted: HTMLElement[] = []\n    let list: HTMLElement | null = null\n    let listKind = \"\"\n    const top: Node[] = []\n    state.doc.forEach((b) => {\n      let number = 0\n      if (isList(b)) {\n        const level = b.indent ?? 0\n        counters.length = level + 1\n        counters[level] = b.type === \"ordered\" ? (counters[level] ?? 0) + 1 : 0\n        number = counters[level]!\n      } else counters.length = 0\n      const known = drawn.get(b.id)\n      let el: HTMLElement\n      if (known && known.block === b && known.number === number) el = known.el\n      else {\n        el = drawBlock(b, number)\n        drawn.set(b.id, { block: b, el, number })\n      }\n      wanted.push(el)\n      if (isList(b)) {\n        const kind = b.type\n        if (!list || listKind !== kind) {\n          // Reuse the container the first item already sits in, so a list isn't rebuilt per keystroke.\n          const tag = kind === \"ordered\" ? \"OL\" : \"UL\"\n          const existing = el.parentElement && el.parentElement !== root && el.parentElement.tagName === tag && el.parentElement.parentElement === root && !top.includes(el.parentElement) ? el.parentElement : null\n          list = existing ?? document.createElement(tag.toLowerCase())\n          list.className = `rich-text-list rich-text-list-${kind}`\n          listKind = kind\n          top.push(list)\n        }\n        if (list.children[[...wantedIn(list)].length] !== el) list.insertBefore(el, list.children[[...wantedIn(list)].length] ?? null)\n        markWanted(list, el)\n      } else {\n        list = null\n        listKind = \"\"\n        top.push(el)\n      }\n    })\n    // Put the top-level nodes in order, then drop anything else (old blocks, empty lists).\n    top.forEach((node, i) => {\n      if (root.childNodes[i] !== node) root.insertBefore(node, root.childNodes[i] ?? null)\n    })\n    while (root.childNodes.length > top.length) root.lastChild!.remove()\n    for (const node of top) {\n      if ((node as HTMLElement).classList?.contains(\"rich-text-list\")) {\n        const keep = wantedSets.get(node as HTMLElement)!\n        for (const child of [...(node as HTMLElement).children]) if (!keep.has(child as HTMLElement)) child.remove()\n      }\n    }\n    wantedSets = new WeakMap()\n    const ids = new Set(state.doc.map((b) => b.id))\n    for (const id of drawn.keys()) if (!ids.has(id)) drawn.delete(id)\n    root.toggleAttribute(\"data-empty\", isEmpty(state.doc))\n    drawSelectedVoid()\n  }\n  let wantedSets = new WeakMap<HTMLElement, Set<HTMLElement>>()\n  const wantedIn = (list: HTMLElement) => wantedSets.get(list) ?? new Set<HTMLElement>()\n  const markWanted = (list: HTMLElement, el: HTMLElement) => {\n    let set = wantedSets.get(list)\n    if (!set) wantedSets.set(list, (set = new Set()))\n    set.add(el)\n  }\n\n  /** A selected rule or image shows as selected (it has no caret of its own). */\n  function drawSelectedVoid() {\n    for (const el of root.querySelectorAll(\"[data-selected]\")) el.removeAttribute(\"data-selected\")\n    const sel = state.selection\n    if (!sel || !collapsed(sel)) return\n    const b = state.doc[sel.focus.block]\n    if (b && isVoid(b)) drawn.get(b.id)?.el.setAttribute(\"data-selected\", \"\")\n  }\n\n  /* -------------------------------------------------------- selection */\n\n  const blockIndexOf = (el: Element | null): number => {\n    const host = el?.closest?.(\"[data-block]\")\n    if (!host || !root.contains(host)) return -1\n    const id = (host as HTMLElement).dataset.block\n    return state.doc.findIndex((b) => b.id === id)\n  }\n\n  function positionFromDom(node: Node, offset: number): Position | null {\n    if (node === root) {\n      // Between blocks: the start of the block at `offset`, or the end of the last one.\n      const child = root.childNodes[offset] as HTMLElement | undefined\n      if (child) {\n        const first = child.matches?.(\"[data-block]\") ? child : child.querySelector?.(\"[data-block]\")\n        const index = blockIndexOf(first ?? null)\n        if (index >= 0) return { block: index, offset: 0 }\n      }\n      const last = state.doc.length - 1\n      return { block: last, offset: blockLength(state.doc[last]!) }\n    }\n    const el = node.nodeType === 3 ? node.parentElement : (node as Element)\n    const index = blockIndexOf(el)\n    if (index < 0) return null\n    const b = state.doc[index]!\n    if (isVoid(b)) return { block: index, offset: 0 }\n    const host = textHost(drawn.get(b.id)!.el)\n    if (!host.contains(node) && node !== host) return { block: index, offset: 0 }\n    return { block: index, offset: Math.min(blockLength(b), offsetIn(host, node, offset)) }\n  }\n\n  function readSelection(): Selection | null {\n    const sel = root.ownerDocument.getSelection()\n    if (!sel || !sel.anchorNode || !sel.focusNode || !root.contains(sel.anchorNode) || !root.contains(sel.focusNode)) return null\n    const anchor = positionFromDom(sel.anchorNode, sel.anchorOffset)\n    const focus = positionFromDom(sel.focusNode, sel.focusOffset)\n    return anchor && focus ? { anchor, focus } : null\n  }\n\n  function writeSelection() {\n    const sel = state.selection\n    const domSel = root.ownerDocument.getSelection()\n    if (!sel || !domSel || root.ownerDocument.activeElement !== root) return\n    const point = (pos: Position): [Node, number] => {\n      const b = state.doc[pos.block]!\n      const el = drawn.get(b.id)!.el\n      if (isVoid(b)) return [el.parentNode!, [...el.parentNode!.childNodes].indexOf(el)]\n      return pointIn(textHost(el), pos.offset)\n    }\n    const [an, ao] = point(sel.anchor)\n    const [fn, fo] = point(sel.focus)\n    applyingSelection = true\n    try {\n      if (domSel.anchorNode !== an || domSel.anchorOffset !== ao || domSel.focusNode !== fn || domSel.focusOffset !== fo) domSel.setBaseAndExtent(an, ao, fn, fo)\n    } finally {\n      queueMicrotask(() => (applyingSelection = false))\n    }\n    revealCaret(fn, fo)\n  }\n\n  /** Keeps the caret in view as it moves: in the editor's own scroll box, then the page. */\n  function revealCaret(node: Node, offset: number) {\n    const range = root.ownerDocument.createRange()\n    try {\n      range.setStart(node, offset)\n    } catch {\n      return\n    }\n    range.collapse(true)\n    let rect = range.getBoundingClientRect()\n    if (!rect.height) {\n      const el = (node.nodeType === 3 ? node.parentElement : (node as Element)) as HTMLElement | null\n      rect = el?.getBoundingClientRect() ?? rect\n      if (!rect.height) return\n    }\n    const margin = 8\n    if (root.scrollHeight > root.clientHeight) {\n      const box = root.getBoundingClientRect()\n      if (rect.bottom > box.bottom - margin) root.scrollTop += rect.bottom - box.bottom + margin\n      else if (rect.top < box.top + margin) root.scrollTop -= box.top + margin - rect.top\n      rect = range.getBoundingClientRect().height ? range.getBoundingClientRect() : rect\n    }\n    const view = root.ownerDocument.defaultView\n    if (!view) return\n    if (rect.bottom > view.innerHeight - margin) view.scrollBy(0, rect.bottom - view.innerHeight + margin)\n    else if (rect.top < margin) view.scrollBy(0, rect.top - margin)\n  }\n\n  /* -------------------------------------------------------- applying */\n\n  const notifyAdapter = (change: EditorChange) => adapterListeners.forEach((l) => l(change))\n\n  function commit(next: EditorState, reason: ChangeReason, group?: string, change?: { inserted: string; range: TextRange; user: boolean }) {\n    if (destroyed) return\n    const docChanged = next.doc !== state.doc\n    state = next\n    draw()\n    writeSelection()\n    if (docChanged && reason !== \"undo\" && reason !== \"redo\") undo.record({ doc: state.doc, selection: state.selection }, group ? { group } : undefined)\n    if (!group) undo.seal()\n    lastSelectionKey = selectionKey(state.selection)\n    listeners.forEach((l) => l(state, reason))\n    options.onChange?.(state, reason)\n    if (change) notifyAdapter({ type: \"input\", ...change })\n    else notifyAdapter({ type: \"selection\" })\n  }\n\n  const selectionKey = (s: Selection | null) => (s ? `${s.anchor.block}:${s.anchor.offset}:${s.focus.block}:${s.focus.offset}` : \"\")\n\n  /** Applies an edit to the current selection (read from the page first). */\n  function edit(update: (s: EditorState) => EditorState | null, reason: ChangeReason = \"input\", group?: string, change?: { inserted: string; range: TextRange; user: boolean }) {\n    if (readOnly) return false\n    const fresh = readSelection()\n    const base = fresh ? select(state, fresh) : state\n    const next = update(base)\n    if (!next) return false\n    commit(next, reason, group, change)\n    return true\n  }\n\n  /** The block-local range an edit replaces, for the trigger menu's change events. */\n  const localRange = (s: EditorState): TextRange | null => {\n    if (!s.selection) return null\n    const [from, to] = ordered(s.selection)\n    if (from.block !== to.block) return null\n    return { start: from.offset, end: to.offset }\n  }\n\n  /* -------------------------------------------------------- input */\n\n  function targetSelection(event: InputEvent): Selection | null {\n    const range = event.getTargetRanges?.()[0]\n    if (!range) return null\n    const anchor = positionFromDom(range.startContainer, range.startOffset)\n    const focus = positionFromDom(range.endContainer, range.endOffset)\n    return anchor && focus ? { anchor, focus } : null\n  }\n\n  function typeText(text: string, target: Selection | null) {\n    const base = target ? select(state, target) : select(state, readSelection() ?? state.selection)\n    const range = localRange(base)\n    let next: EditorState\n    // A single character might complete Markdown (a space after \"#\", a closing \"**\").\n    const rule = text.length === 1 && base.selection && collapsed(base.selection) ? inputRule(base, text) : null\n    if (rule) next = text === \" \" && rule.doc[base.selection!.focus.block]!.type !== base.doc[base.selection!.focus.block]!.type ? rule : rule\n    else next = insertText(base, text)\n    commit(next, \"input\", \"typing\", range ? { inserted: text, range, user: true } : undefined)\n  }\n\n  const deleteUnits: Record<string, [\"char\" | \"word\" | \"line\", boolean]> = {\n    deleteContentBackward: [\"char\", false],\n    deleteContentForward: [\"char\", true],\n    deleteWordBackward: [\"word\", false],\n    deleteWordForward: [\"word\", true],\n    deleteSoftLineBackward: [\"line\", false],\n    deleteSoftLineForward: [\"line\", true],\n    deleteHardLineBackward: [\"line\", false],\n    deleteHardLineForward: [\"line\", true],\n  }\n\n  function onBeforeInput(event: InputEvent) {\n    if (readOnly) return event.preventDefault()\n    const type = event.inputType\n    // Input methods compose in the DOM; their text is read back when they finish.\n    if (type === \"insertCompositionText\" || type === \"deleteCompositionText\" || type === \"insertFromComposition\" || (isComposing(event) && type !== \"insertParagraph\")) return\n    event.preventDefault()\n    const target = targetSelection(event)\n    if (type === \"insertText\" || type === \"insertReplacementText\") {\n      const text = event.data ?? event.dataTransfer?.getData(\"text/plain\") ?? \"\"\n      if (text) typeText(text, type === \"insertReplacementText\" ? target : (target ?? readSelection()))\n      return\n    }\n    if (type === \"insertParagraph\") {\n      edit((s) => inputRule(s, \"enter\") ?? splitBlock(s), \"input\")\n      return\n    }\n    if (type === \"insertLineBreak\") {\n      edit(insertLineBreak, \"input\", \"typing\")\n      return\n    }\n    const del = deleteUnits[type]\n    if (del) {\n      const base = select(state, readSelection() ?? state.selection)\n      // The browser's own range for word and line deletes (it knows where words end in every language).\n      const useTarget = target && !collapsed(target) && del[0] !== \"char\"\n      const before = localRange(base)\n      const next = useTarget ? deleteSelection(select(base, target)) : deleteBy(base, del[0], del[1])\n      const after = localRange(next)\n      commit(next, \"input\", \"delete\", before && after && base.selection!.focus.block === next.selection?.focus.block ? { inserted: \"\", range: { start: Math.min(before.start, after.start), end: Math.max(before.end, before.start === after.start && !del[1] ? before.end : before.end) }, user: true } : undefined)\n      return\n    }\n    const format: Record<string, MarkName> = { formatBold: \"bold\", formatItalic: \"italic\", formatUnderline: \"underline\", formatStrikeThrough: \"strike\" }\n    if (format[type]) return void toggle(format[type]!)\n    if (type === \"historyUndo\") return void doUndo()\n    if (type === \"historyRedo\") return void doRedo()\n    // Paste, drop and cut arrive as their own events; anything else (insertOrderedList…) is ignored.\n  }\n\n  function onComposition(event: CompositionEvent) {\n    if (event.type === \"compositionstart\") {\n      composing = true\n      // A selection across blocks goes first, so the input method writes into one block.\n      if (state.selection && !collapsed(state.selection)) {\n        const fresh = readSelection()\n        if (fresh && fresh.anchor.block !== fresh.focus.block) commit(deleteSelection(select(state, fresh)), \"input\")\n      }\n      const at = state.selection ? state.doc[ordered(state.selection)[0].block] : undefined\n      composeFrom = at && !isVoid(at) ? { block: at, marks: typingMarks(state) } : null\n      notifyAdapter({ type: \"compositionstart\" })\n      return\n    }\n    composing = false\n    reconcile()\n    notifyAdapter({ type: \"compositionend\" })\n  }\n\n  /** Reads back the blocks an input method or the browser changed by itself. */\n  function reconcile() {\n    const sel = root.ownerDocument.getSelection()\n    const el = sel?.focusNode ? (sel.focusNode.nodeType === 3 ? sel.focusNode.parentElement : (sel.focusNode as Element)) : null\n    const index = blockIndexOf(el)\n    if (index < 0) return\n    const b = state.doc[index]!\n    const entry = drawn.get(b.id)\n    if (!entry || isVoid(b)) return\n    const host = textHost(entry.el)\n    const content = readBlock(host)\n    const caretOffset = sel?.focusNode ? offsetIn(host, sel.focusNode, sel.focusOffset) : blockLength(b)\n    const doc = state.doc.slice()\n    doc[index] = { ...b, content: b.type === \"code\" ? [{ text: content.map((r) => (isMention(r) ? r.label : r.text)).join(\"\") }] : content }\n    // Text an input method only added goes in with the marks typing would have used there\n    // (after Mod+B, or inside `code`), whatever the browser wrote into the page.\n    const from = composeFrom\n    composeFrom = null\n    if (from && from.block.id === b.id && b.type !== \"code\") {\n      const was = blockText(b)\n      const now = content.map((r) => (isMention(r) ? OBJECT : r.text)).join(\"\")\n      let start = 0\n      while (start < was.length && was[start] === now[start]) start++\n      let end = 0\n      while (end < was.length - start && end < now.length - start && was[was.length - 1 - end] === now[now.length - 1 - end]) end++\n      const added = now.slice(start, now.length - end)\n      if (added && was.length - start - end === 0 && !added.includes(OBJECT)) {\n        const typed = insertContent(select(state, caret({ block: index, offset: start })), [{ text: added, ...(from.marks ? { marks: from.marks } : {}) }])\n        doc[index] = typed.doc[index]!\n      }\n    }\n    // The DOM the input method left behind is redrawn from the document.\n    drawn.delete(b.id)\n    commit({ ...state, doc, selection: caret({ block: index, offset: caretOffset }) }, \"composition\", \"typing\")\n  }\n\n  function onInput(event: Event) {\n    // Anything that slipped past beforeinput (an input method in some browsers, a spellcheck\n    // replacement) is read back from the page.\n    if (composing || isComposing(event as InputEvent)) return\n    reconcile()\n  }\n\n  // Focus coming back to the text without a press in it (after a popover, a dialog, Tab)\n  // puts the selection it had back at once. Safari places the caret at the start on focus\n  // and reports that with a late selectionchange, which would otherwise replace the person's\n  // selection. A press in the text is left alone: the browser puts the caret where the\n  // person clicked (writing the old selection there broke clicking in Firefox).\n  let pressing = false\n  const released = () => (pressing = false)\n  function onFocus() {\n    if (state.selection && !pressing) writeSelection()\n  }\n\n  function onSelectionChange() {\n    if (applyingSelection || composing || destroyed) return\n    const fresh = readSelection()\n    if (!fresh) return\n    const key = selectionKey(fresh)\n    if (key === lastSelectionKey) return\n    lastSelectionKey = key\n    state = select(state, fresh)\n    undo.seal()\n    drawSelectedVoid()\n    listeners.forEach((l) => l(state, \"selection\"))\n    options.onChange?.(state, \"selection\")\n    notifyAdapter({ type: \"selection\" })\n  }\n\n  /* -------------------------------------------------------- keys */\n\n  function toggle(mark: MarkName) {\n    // A locked editor changes nothing, so it announces nothing either.\n    if (readOnly) return\n    let on = false\n    edit((s) => {\n      const next = toggleMark(s, mark)\n      on = markActive(next, mark)\n      return next\n    }, \"format\")\n    announce(on ? messages.markOn(markNames[mark]) : messages.markOff(markNames[mark]))\n  }\n\n  function onKeyDown(event: KeyboardEvent) {\n    // An open \"/\" or \"@\" menu handles its own keys (Enter, Tab, arrows) first.\n    if (event.defaultPrevented || isComposing(event) || readOnly) return\n    const shortcuts: [string, () => void][] = [\n      [\"mod+b\", () => toggle(\"bold\")],\n      [\"mod+i\", () => toggle(\"italic\")],\n      [\"mod+u\", () => toggle(\"underline\")],\n      [\"mod+shift+s\", () => toggle(\"strike\")],\n      [\"mod+shift+x\", () => toggle(\"strike\")],\n      [\"mod+e\", () => toggle(\"code\")],\n      // The link popover reads the selection now, not after the last selectionchange lands.\n      [\"mod+k\", () => (onSelectionChange(), options.onLinkRequest?.())],\n      [\"mod+z\", () => doUndo()],\n      [\"mod+shift+z\", () => doRedo()],\n      [\"mod+y\", () => doRedo()],\n      [\"mod+alt+0\", () => blockType(\"paragraph\")],\n      [\"mod+alt+1\", () => blockType(\"heading\", 1)],\n      [\"mod+alt+2\", () => blockType(\"heading\", 2)],\n      [\"mod+alt+3\", () => blockType(\"heading\", 3)],\n      [\"mod+shift+7\", () => blockType(\"ordered\")],\n      [\"mod+shift+8\", () => blockType(\"bullet\")],\n      [\"mod+shift+9\", () => blockType(\"task\")],\n    ]\n    for (const [keys, run] of shortcuts) {\n      if (!matchesShortcut(event, keys)) continue\n      event.preventDefault()\n      run()\n      return\n    }\n    const sel = readSelection() ?? state.selection\n    const current = sel ? state.doc[ordered(sel)[0].block] : undefined\n    if (matchesShortcut(event, \"mod+enter\")) {\n      event.preventDefault()\n      if (current?.type === \"task\" && sel) edit((s) => toggleTask(s, ordered(sel)[0].block), \"format\")\n      else options.onSubmit?.()\n      return\n    }\n    // Tab nests list items; elsewhere it moves on, as in any other field.\n    if (event.key === \"Tab\" && !event.altKey && !event.ctrlKey && !event.metaKey && current && isList(current)) {\n      event.preventDefault()\n      edit(event.shiftKey ? outdent : indent, \"format\")\n      return\n    }\n    // Arrows onto a rule or image select it; Backspace/Delete there removes it.\n    if (current && isVoid(current) && (event.key === \"Backspace\" || event.key === \"Delete\")) {\n      event.preventDefault()\n      edit((s) => deleteBy(s, \"char\", event.key === \"Delete\"), \"input\")\n    }\n  }\n\n  function blockType(type: \"paragraph\" | \"heading\" | \"bullet\" | \"ordered\" | \"task\" | \"quote\" | \"code\", level?: 1 | 2 | 3) {\n    if (readOnly) return\n    edit((s) => setBlock(s, type, level ? { level } : {}), \"format\")\n    const now = activeBlock(state)\n    if (now) announce(messages.block(blockLabel(now.type, now.level)))\n  }\n\n  /* -------------------------------------------------------- clipboard */\n\n  function writeClipboard(data: DataTransfer) {\n    const fresh = readSelection()\n    const s = fresh ? select(state, fresh) : state\n    let blocks = fragment(s)\n    if (!blocks.length) return false\n    // Part of one block is inline text: no list marker, no heading.\n    const sel = s.selection\n    if (sel && blocks.length === 1 && sel.anchor.block === sel.focus.block && !isVoid(blocks[0]!)) {\n      const b = s.doc[sel.anchor.block]!\n      if (b.type !== \"code\" || blockLength(blocks[0]!) < blockLength(b)) blocks = [{ ...blocks[0]!, type: b.type === \"code\" ? \"code\" : \"paragraph\", level: undefined, indent: undefined, checked: undefined }]\n    }\n    data.setData(\"text/plain\", toText(blocks))\n    data.setData(\"text/html\", toHTML(blocks))\n    data.setData(MIME, JSON.stringify(blocks))\n    return true\n  }\n\n  function readTransfer(data: DataTransfer): Doc | null {\n    const own = data.getData(MIME)\n    if (own) {\n      try {\n        // Any page can put this type on the clipboard or a drag: it's checked like any other input.\n        return sanitizeDoc(JSON.parse(own)).map((b) => ({ ...b, id: block().id }))\n      } catch {\n        /* fall through */\n      }\n    }\n    const html = data.getData(\"text/html\")\n    // Images from pasted pages only come in when the app takes images (uploadImage): no\n    // hotlinks, tracking pixels or huge data: addresses otherwise.\n    if (html) return fromHTML(html).filter((b) => b.type !== \"image\" || !!options.uploadImage)\n    const text = data.getData(\"text/plain\")\n    if (!text) return null\n    // Text that looks like Markdown (a heading, a list, a fence, **bold**) is read as Markdown.\n    if (/(^|\\n)(#{1,3} |[-*+] |\\d+[.)] |> |```|- \\[[ x]\\] )|\\*\\*[^*\\n]+\\*\\*|\\[[^\\]]+\\]\\([^)]+\\)/.test(text)) return fromMarkdown(text)\n    return null\n  }\n\n  async function insertFiles(files: File[], at: Selection | null) {\n    const images = files.filter((f) => f.type.startsWith(\"image/\"))\n    if (!images.length || !options.uploadImage) return false\n    for (const file of images) {\n      const uploaded = await options.uploadImage(file)\n      if (!uploaded) continue\n      const base = at ? select(state, at) : state\n      commit(insertBlock(base, block(\"image\", [], { src: uploaded.src, alt: uploaded.alt ?? file.name.replace(/\\.[^.]+$/, \"\") })), \"paste\")\n      at = null\n    }\n    return true\n  }\n\n  function onCopy(event: ClipboardEvent) {\n    if (event.clipboardData && writeClipboard(event.clipboardData)) event.preventDefault()\n  }\n\n  function onCut(event: ClipboardEvent) {\n    if (!event.clipboardData || readOnly) return\n    if (writeClipboard(event.clipboardData)) {\n      event.preventDefault()\n      edit(deleteSelection, \"input\")\n    }\n  }\n\n  function onPaste(event: ClipboardEvent) {\n    if (readOnly || !event.clipboardData) return\n    event.preventDefault()\n    const data = event.clipboardData\n    const files = [...data.files]\n    const at = readSelection()\n    if (files.length && options.uploadImage) {\n      void insertFiles(files, at)\n      return\n    }\n    const current = at ? state.doc[ordered(at)[0].block] : undefined\n    const plain = data.getData(\"text/plain\")\n    // Into code, everything pastes as its text.\n    if (current?.type === \"code\") return void edit((s) => insertText(s, plain), \"paste\")\n    const blocks = readTransfer(data)\n    const fromPlain = !data.getData(MIME) && !data.getData(\"text/html\")\n    if (blocks && fromPlain && blocks.length === 1 && current && blockLength(current) > 0 && plain) edit((s) => insertText(s, plain), \"paste\")\n    else if (blocks) edit((s) => insertFragment(s, blocks), \"paste\")\n    else if (plain) edit((s) => insertText(s, plain), \"paste\")\n  }\n\n  let dragged: Selection | null = null\n  function onDragStart(event: DragEvent) {\n    dragged = readSelection()\n    if (event.dataTransfer) writeClipboard(event.dataTransfer)\n  }\n\n  function onDragEnd() {\n    dragged = null\n  }\n\n  function onDrop(event: DragEvent) {\n    if (readOnly || !event.dataTransfer) return\n    event.preventDefault()\n    const doc = root.ownerDocument as Document & { caretPositionFromPoint?: (x: number, y: number) => { offsetNode: Node; offset: number } | null }\n    let point: Position | null = null\n    const pos = doc.caretPositionFromPoint?.(event.clientX, event.clientY)\n    if (pos) point = positionFromDom(pos.offsetNode, pos.offset)\n    else {\n      const range = doc.caretRangeFromPoint?.(event.clientX, event.clientY)\n      if (range) point = positionFromDom(range.startContainer, range.startOffset)\n    }\n    const files = [...event.dataTransfer.files]\n    if (files.length) return void insertFiles(files, point ? caret(point) : null)\n    const blocks = readTransfer(event.dataTransfer)\n    const plain = event.dataTransfer.getData(\"text/plain\")\n    const own = dragged && event.dataTransfer.types.includes(MIME) ? dragged : null\n    dragged = null\n    if (!point) return\n    let base = state\n    // Moving within the editor: take the text out first, then put it where it was dropped.\n    if (own && !collapsed(own) && !event.altKey && !(event.ctrlKey && !navigator.platform.startsWith(\"Mac\"))) {\n      const [from, to] = ordered(own)\n      const inside = (point.block > from.block || (point.block === from.block && point.offset >= from.offset)) && (point.block < to.block || (point.block === to.block && point.offset <= to.offset))\n      if (inside) return\n      const before = point.block < from.block || (point.block === from.block && point.offset < from.offset)\n      const removed = deleteSelection(select(state, own))\n      if (!before) {\n        // Positions after the removed text shift back by what was removed.\n        const removedBlocks = to.block - from.block\n        point = point.block === to.block ? { block: from.block, offset: from.offset + (point.offset - to.offset) } : { block: point.block - removedBlocks, offset: point.offset }\n      }\n      base = removed\n    }\n    const at = select(base, caret(point))\n    commit(blocks ? insertFragment(at, blocks) : insertText(at, plain), \"drop\")\n  }\n\n  /* -------------------------------------------------------- tasks and voids by pointer */\n\n  function onPointerDown(event: PointerEvent) {\n    pressing = true\n    const target = event.target as HTMLElement\n    const box = target.closest(\".rich-text-check\")\n    // A to-do's box keeps the caret where it is; the click toggles it.\n    if (box) {\n      event.preventDefault()\n      return\n    }\n    const voidEl = target.closest(\".rich-text-divider, .rich-text-image\")\n    if (voidEl) {\n      event.preventDefault()\n      root.focus({ preventScroll: true })\n      const index = blockIndexOf(voidEl)\n      if (index >= 0) commit(select(state, caret({ block: index, offset: 0 })), \"selection\")\n    }\n  }\n\n  function onClick(event: MouseEvent) {\n    const box = (event.target as HTMLElement).closest(\".rich-text-check\")\n    if (!box || readOnly) return\n    event.preventDefault()\n    const index = blockIndexOf(box)\n    if (index >= 0) commit(toggleTask(state, index), \"format\")\n  }\n\n  /* -------------------------------------------------------- undo */\n\n  function restore(entry: unknown, reason: \"undo\" | \"redo\") {\n    if (!entry) return false\n    const { doc } = entry as { doc: Doc; selection: Selection | null }\n    // The caret goes where the change was: after text that comes back, or where text went.\n    commit({ doc, selection: changePoint(state.doc, doc), stored: null }, reason)\n    announce(reason === \"undo\" ? messages.undo : messages.redo)\n    return true\n  }\n  const doUndo = () => !readOnly && restore(undo.undo(), \"undo\")\n  const doRedo = () => !readOnly && restore(undo.redo(), \"redo\")\n\n  /* -------------------------------------------------------- the trigger menu */\n\n  const adapter: TextEditorAdapter = {\n    get element() {\n      return root\n    },\n    textBefore(length) {\n      const sel = state.selection\n      if (!sel || !collapsed(sel)) return null\n      const b = state.doc[sel.focus.block]\n      if (!b || isVoid(b)) return null\n      const text = blockText(b).slice(0, sel.focus.offset)\n      const start = Math.max(0, text.length - length)\n      return { text: text.slice(start), offset: start }\n    },\n    selection() {\n      if (root.ownerDocument.activeElement !== root || !state.selection) return null\n      return localRange(state)\n    },\n    rectAt(offset) {\n      const sel = state.selection\n      if (!sel) return null\n      const b = state.doc[sel.focus.block]\n      const el = b && drawn.get(b.id)?.el\n      if (!el || isVoid(b!)) return null\n      const [node, at] = pointIn(textHost(el), offset)\n      const range = root.ownerDocument.createRange()\n      range.setStart(node, at)\n      range.collapse(true)\n      let rect = range.getBoundingClientRect()\n      // An empty line has no box of its own; use the block's.\n      if (!rect.height) rect = el.getBoundingClientRect()\n      return { x: rect.left, y: rect.top, width: rect.width, height: rect.height || parseFloat(getComputedStyle(el).lineHeight) || 16 }\n    },\n    replace(range, content) {\n      const sel = state.selection\n      if (!sel) return\n      const index = sel.focus.block\n      // A token keeps the character that started it (\"@\", \"#\"), read from the text it replaces.\n      const startChar = blockText(state.doc[index]!).slice(range.start, range.start + 1)\n      const trigger = startChar && !/[\\p{L}\\p{N}\\s]/u.test(startChar) ? startChar : \"@\"\n      const run: Inline[] = typeof content === \"string\" ? [{ text: content }] : [{ type: \"mention\", id: (content as TokenInsert).value, label: (content as TokenInsert).label, trigger }, { text: \" \" }]\n      commit(replaceRange(state, index, range.start, range.end, run), \"input\", undefined, { inserted: typeof content === \"string\" ? content : \"￼ \", range, user: false })\n    },\n    subscribe(listener) {\n      adapterListeners.add(listener)\n      return () => adapterListeners.delete(listener)\n    },\n    composing: () => composing,\n    tokens: true,\n    submit: () => options.onSubmit?.(),\n  }\n\n  /* -------------------------------------------------------- wiring */\n\n  const doc = root.ownerDocument\n  root.addEventListener(\"beforeinput\", onBeforeInput as EventListener)\n  root.addEventListener(\"input\", onInput)\n  root.addEventListener(\"compositionstart\", onComposition as EventListener)\n  root.addEventListener(\"compositionend\", onComposition as EventListener)\n  root.addEventListener(\"keydown\", onKeyDown)\n  root.addEventListener(\"copy\", onCopy)\n  root.addEventListener(\"cut\", onCut)\n  root.addEventListener(\"paste\", onPaste)\n  root.addEventListener(\"dragstart\", onDragStart)\n  root.addEventListener(\"dragend\", onDragEnd)\n  root.addEventListener(\"click\", onClick)\n  root.addEventListener(\"drop\", onDrop)\n  root.addEventListener(\"pointerdown\", onPointerDown)\n  root.addEventListener(\"focus\", onFocus)\n  doc.addEventListener(\"pointerup\", released, true)\n  doc.addEventListener(\"pointercancel\", released, true)\n  doc.addEventListener(\"selectionchange\", onSelectionChange)\n  draw()\n\n  return {\n    get state() {\n      return state\n    },\n    /** Replaces the state from outside (a controlled value). Undo starts over from it. */\n    set(next: EditorState, reason: ChangeReason = \"set\") {\n      state = next\n      draw()\n      writeSelection()\n      if (reason === \"set\") undo.reset({ doc: state.doc, selection: state.selection })\n      listeners.forEach((l) => l(state, reason))\n    },\n    /** Applies an edit to the current selection, as a toolbar button or an agent does. */\n    run(update: (s: EditorState) => EditorState | null, reason: ChangeReason = \"format\") {\n      return edit(update, reason)\n    },\n    toggleMark: toggle,\n    setBlock: blockType,\n    insertMention(mention: { id: string; label: string; trigger?: string }) {\n      return edit((s) => insertMention(s, mention), \"input\")\n    },\n    undo: doUndo,\n    redo: doRedo,\n    canUndo: () => undo.canUndo(),\n    canRedo: () => undo.canRedo(),\n    setReadOnly(value: boolean) {\n      readOnly = value\n      root.contentEditable = value ? \"false\" : \"true\"\n      root.setAttribute(\"aria-readonly\", String(value))\n      root.tabIndex = 0\n    },\n    focus(options?: FocusOptions) {\n      root.focus(options)\n      if (!state.selection) state = select(state, caret({ block: state.doc.length - 1, offset: blockLength(state.doc.at(-1)!) }))\n      writeSelection()\n    },\n    subscribe(listener: Listener) {\n      listeners.add(listener)\n      return () => void listeners.delete(listener)\n    },\n    adapter,\n    destroy() {\n      destroyed = true\n      root.removeEventListener(\"beforeinput\", onBeforeInput as EventListener)\n      root.removeEventListener(\"input\", onInput)\n      root.removeEventListener(\"compositionstart\", onComposition as EventListener)\n      root.removeEventListener(\"compositionend\", onComposition as EventListener)\n      root.removeEventListener(\"keydown\", onKeyDown)\n      root.removeEventListener(\"copy\", onCopy)\n      root.removeEventListener(\"cut\", onCut)\n      root.removeEventListener(\"paste\", onPaste)\n      root.removeEventListener(\"dragstart\", onDragStart)\n      root.removeEventListener(\"dragend\", onDragEnd)\n      root.removeEventListener(\"click\", onClick)\n      root.removeEventListener(\"drop\", onDrop)\n      root.removeEventListener(\"pointerdown\", onPointerDown)\n      root.removeEventListener(\"focus\", onFocus)\n      doc.removeEventListener(\"pointerup\", released, true)\n      doc.removeEventListener(\"pointercancel\", released, true)\n      doc.removeEventListener(\"selectionchange\", onSelectionChange)\n      listeners.clear()\n      adapterListeners.clear()\n    },\n  }\n}\n\nconst blockLabels: Record<string, string> = {\n  paragraph: \"Text\",\n  quote: \"Quote\",\n  code: \"Code block\",\n  bullet: \"Bulleted list\",\n  ordered: \"Numbered list\",\n  task: \"To-do list\",\n  divider: \"Divider\",\n  image: \"Image\",\n}\n/** A block type in words, for the toolbar and announcements. */\nconst blockLabel = (type: string, level?: number) => (type === \"heading\" ? `Heading ${level ?? 1}` : (blockLabels[type] ?? type))\n\ntype RichTextView = ReturnType<typeof createRichTextView>\n\n/**\n * A document as read-only DOM, with the editor's classes (for showing saved text with the\n * same styles). Built from the document, never from HTML strings.\n */\nfunction renderDocument(unchecked: Doc): DocumentFragment {\n  const doc = sanitizeDoc(unchecked)\n  const out = document.createDocumentFragment()\n  const counters: number[] = []\n  let list: HTMLElement | null = null\n  let kind = \"\"\n  for (const b of doc) {\n    let number = 0\n    if (isList(b)) {\n      const level = b.indent ?? 0\n      counters.length = level + 1\n      counters[level] = b.type === \"ordered\" ? (counters[level] ?? 0) + 1 : 0\n      number = counters[level]!\n    } else counters.length = 0\n    const el = drawBlock(b, number)\n    el.removeAttribute(\"data-block\")\n    el.removeAttribute(\"contenteditable\")\n    for (const part of el.querySelectorAll(\"[contenteditable]\")) part.removeAttribute(\"contenteditable\")\n    // A to-do's box is a picture of its state here, not a control.\n    const box = el.querySelector(\".rich-text-check\")\n    if (box) {\n      box.setAttribute(\"role\", \"img\")\n      box.setAttribute(\"aria-label\", b.type === \"task\" && b.checked ? \"Done\" : \"Not done\")\n      box.removeAttribute(\"aria-checked\")\n    }\n    if (isList(b)) {\n      if (!list || kind !== b.type) {\n        list = document.createElement(b.type === \"ordered\" ? \"ol\" : \"ul\")\n        list.className = `rich-text-list rich-text-list-${b.type}`\n        kind = b.type\n        out.append(list)\n      }\n      list.append(el)\n    } else {\n      list = null\n      kind = \"\"\n      out.append(el)\n    }\n  }\n  return out\n}\n\nexport { blockLabel, createRichTextView, english as richTextMessages, offsetIn, pointIn, readBlock, renderDocument }\nexport type { ChangeReason, Messages as RichTextMessages, RichTextView, ViewOptions as RichTextViewOptions }\n",
      "type": "registry:file",
      "target": "@ui/rich-text/view.ts"
    },
    {
      "path": "registry/uiset/ui/rich-text/primitive.ts",
      "content": "// The rich text editor as a UI SDK primitive: what agents read (the text as Markdown) and\n// what they can do (set it, insert at the end, clear it), through the same change path\n// as a person's edits, so the app's onValueChange sees `details.source === \"agent\"` and can\n// refuse it. The React editor and the web element both run on it.\n\nimport { createChange, definePrimitive, type ChangeDetails } from \"@ui-sdk/core\"\n\ntype RichTextReason = \"set-value\" | \"insert\" | \"clear\"\n\ntype RichTextPrimitiveOptions = {\n  /** The text as Markdown: what an agent reads. */\n  value?: string\n  defaultValue?: string\n  disabled?: boolean\n  readOnly?: boolean\n  onValueChange?: (markdown: string, details: ChangeDetails<RichTextReason>) => void\n}\n\n/** @internal Left out of @uiset/web's declarations: its type names UI SDK internals. */\nconst richTextPrimitive = definePrimitive({\n  name: \"rich-text\",\n  options: {\n    value: \"string\",\n    defaultValue: \"string\",\n    disabled: \"boolean\",\n    readOnly: \"boolean\",\n    onValueChange: \"callback\",\n  },\n  controlled: [\"value\"],\n  state: (options: RichTextPrimitiveOptions) => ({ value: options.value ?? options.defaultValue ?? \"\" }),\n  // The editor passes its text back as it changes, so agents always read what's shown.\n  sync: (options) => (options.value === undefined ? {} : { value: options.value }),\n  api: (context) => {\n    const change = createChange(context)\n    const opts = () => context.options()\n    const refuse = () => {\n      if (opts().disabled) throw new Error(\"The editor is turned off.\")\n      if (opts().readOnly) throw new Error(\"The editor is read-only.\")\n    }\n    const current = () => String(context.store.get().value ?? \"\")\n    return {\n      /** Replaces the text with Markdown (headings, lists, tasks, quotes, code, links, **bold**, _italic_). */\n      setValue(markdown: string, event?: Event) {\n        refuse()\n        return change(\"value\", String(markdown ?? \"\"), { reason: \"set-value\", event })\n      },\n      /** Adds Markdown at the end, as new blocks. */\n      insert(markdown: string, event?: Event) {\n        refuse()\n        const text = String(markdown ?? \"\").trim()\n        if (!text) throw new Error(\"Give some text to insert.\")\n        const before = current().trimEnd()\n        return change(\"value\", before ? `${before}\\n\\n${text}` : text, { reason: \"insert\", event })\n      },\n      clear(event?: Event) {\n        refuse()\n        return change(\"value\", \"\", { reason: \"clear\", event })\n      },\n    }\n  },\n  slots: (slot) => ({\n    root: slot({ attrs: () => ({ role: \"textbox\", \"aria-multiline\": \"true\" }) }),\n  }),\n  agent: { actions: [\"setValue\", \"insert\", \"clear\"] },\n})\n\nexport { richTextPrimitive }\nexport type { RichTextPrimitiveOptions, RichTextReason }\n",
      "type": "registry:file",
      "target": "@ui/rich-text/primitive.ts"
    },
    {
      "path": "registry/uiset/ui/rich-text/commands.ts",
      "content": "// What the rich text editor offers, shared by React and Web Components: the \"/\" commands\n// and the toolbar's marks, lists and block types.\n\nimport type { IconName } from \"../shell/icon-paths\"\nimport { block, insertBlock, setBlock, type EditorState, type MarkName, type TextBlockType } from \"./model\"\n\ntype RichTextCommand = {\n  value: string\n  label: string\n  description?: string\n  /** An icon, or a short glyph like \"H1\" where no icon says it better. */\n  icon?: IconName\n  glyph?: string\n  run: (state: EditorState) => EditorState\n}\n\nconst blockCommand = (type: TextBlockType, level?: 1 | 2 | 3) => (s: EditorState) => setBlock(s, type, level ? { level } : {})\n\n/** What \"/\" offers at the start of a line. */\nconst defaultCommands: RichTextCommand[] = [\n  { value: \"text\", label: \"Text\", description: \"A plain paragraph\", glyph: \"T\", run: blockCommand(\"paragraph\") },\n  { value: \"h1\", label: \"Heading 1\", glyph: \"H1\", description: \"A big section title\", run: blockCommand(\"heading\", 1) },\n  { value: \"h2\", label: \"Heading 2\", glyph: \"H2\", description: \"A section title\", run: blockCommand(\"heading\", 2) },\n  { value: \"h3\", label: \"Heading 3\", glyph: \"H3\", description: \"A small section title\", run: blockCommand(\"heading\", 3) },\n  { value: \"bullet\", label: \"Bulleted list\", description: \"A list with dots\", icon: \"list-bullet\", run: blockCommand(\"bullet\") },\n  { value: \"ordered\", label: \"Numbered list\", description: \"A list with numbers\", icon: \"list-ordered\", run: blockCommand(\"ordered\") },\n  { value: \"task\", label: \"To-do list\", description: \"A list with checkboxes\", icon: \"list-check\", run: blockCommand(\"task\") },\n  { value: \"quote\", label: \"Quote\", description: \"Set text apart\", icon: \"quote\", run: blockCommand(\"quote\") },\n  { value: \"code\", label: \"Code block\", description: \"Code, as it's typed\", icon: \"code-block\", run: blockCommand(\"code\") },\n  { value: \"divider\", label: \"Divider\", description: \"A line between sections\", icon: \"rule\", run: (s) => insertBlock(s, block(\"divider\")) },\n]\n\nconst markButtons: { mark: MarkName; label: string; icon: IconName; keys: string }[] = [\n  { mark: \"bold\", label: \"Bold\", icon: \"bold\", keys: \"mod+b\" },\n  { mark: \"italic\", label: \"Italic\", icon: \"italic\", keys: \"mod+i\" },\n  { mark: \"underline\", label: \"Underline\", icon: \"underline\", keys: \"mod+u\" },\n  { mark: \"strike\", label: \"Strikethrough\", icon: \"strike\", keys: \"mod+shift+x\" },\n  { mark: \"code\", label: \"Code\", icon: \"code-inline\", keys: \"mod+e\" },\n]\n\nconst listButtons: { type: \"bullet\" | \"ordered\" | \"task\"; label: string; icon: IconName }[] = [\n  { type: \"bullet\", label: \"Bulleted list\", icon: \"list-bullet\" },\n  { type: \"ordered\", label: \"Numbered list\", icon: \"list-ordered\" },\n  { type: \"task\", label: \"To-do list\", icon: \"list-check\" },\n]\n\n/** The block-type menu's choices: a value per type (\"h1\"–\"h3\" for headings). */\nconst blockOptions = [\n  { value: \"paragraph\", label: \"Text\" },\n  { value: \"h1\", label: \"Heading 1\" },\n  { value: \"h2\", label: \"Heading 2\" },\n  { value: \"h3\", label: \"Heading 3\" },\n  { value: \"quote\", label: \"Quote\" },\n  { value: \"code\", label: \"Code block\" },\n]\n\n/** The block-type menu's value for a block (\"paragraph\" for lists and anything it doesn't list). */\nfunction blockOptionValue(b: { type: string; level?: number } | undefined): string {\n  if (!b) return \"paragraph\"\n  if (b.type === \"heading\") return `h${b.level ?? 1}`\n  return b.type === \"quote\" || b.type === \"code\" ? b.type : \"paragraph\"\n}\n\n/** The block type and level for a block-type menu value. */\nfunction blockOptionType(value: string): { type: \"paragraph\" | \"heading\" | \"quote\" | \"code\"; level?: 1 | 2 | 3 } {\n  if (value === \"h1\" || value === \"h2\" || value === \"h3\") return { type: \"heading\", level: Number(value[1]) as 1 | 2 | 3 }\n  return { type: value === \"quote\" || value === \"code\" ? value : \"paragraph\" }\n}\n\n/** Where a \"/\" command's text starts: the last \"/\" before the caret in the block. */\nfunction commandStart(text: string, caret: number): number {\n  return Math.max(0, text.lastIndexOf(\"/\", caret - 1))\n}\n\nexport { blockOptions, blockOptionType, blockOptionValue, commandStart, defaultCommands, listButtons, markButtons }\nexport type { RichTextCommand }\n",
      "type": "registry:file",
      "target": "@ui/rich-text/commands.ts"
    },
    {
      "path": "registry/uiset/ui/rich-text/rich-text.css",
      "content": "@layer ui-sdk, uiset.tokens, uiset.base, uiset.skin;\n\n/* The rich text editor: a field-like box with a toolbar, and the document's own typography.\n   RichTextContent (read-only) uses the same text styles without the box. */\n\n@layer uiset.base {\n  :where([data-uiset]) {\n    --rich-text-padding-block: 0.75rem;\n    --rich-text-padding-inline: 1rem;\n    --rich-text-min-height: 9rem;\n    --rich-text-max-height: none;\n    --rich-text-indent: 1.5em;\n  }\n\n  .rich-text {\n    display: flex;\n    flex-direction: column;\n    min-inline-size: 0;\n    border: 1px solid var(--ui-input);\n    border-radius: var(--ui-radius);\n    background: var(--ui-background);\n    color: var(--ui-foreground);\n\n    /* One ring, on the box's own edge, while the text has focus (as text fields do). */\n    &:has(.rich-text-content:focus-visible) {\n      border-color: var(--ui-ring-border);\n      outline: 2px solid var(--ui-ring-border);\n      outline-offset: -1px;\n    }\n\n    &[data-disabled] {\n      opacity: 0.6;\n      cursor: not-allowed;\n    }\n\n    &[data-readonly] {\n      background: transparent;\n    }\n  }\n\n  .rich-text .rich-text-content:focus-visible {\n    outline: none;\n  }\n\n  .rich-text-toolbar {\n    position: sticky;\n    inset-block-start: 0;\n    z-index: 1;\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    gap: 2px;\n    padding: 0.25rem;\n    border-block-end: 1px solid var(--ui-border);\n    border-start-start-radius: inherit;\n    border-start-end-radius: inherit;\n    background: var(--ui-background);\n\n    & [data-slot=\"toolbar-separator\"] {\n      align-self: stretch;\n      margin-inline: 0.25rem;\n    }\n\n    & svg {\n      inline-size: 1rem;\n      block-size: 1rem;\n    }\n  }\n\n  /* The toolbar sits 4px inside the editor's 1px edge, so its controls' corners are the\n     editor's radius less 5px: concentric with the editor's top corners. (Specific enough\n     to outrank base.css's rule for controls in any toolbar.) */\n  [data-uiset]\n    .rich-text-toolbar[data-slot=\"toolbar\"]\n    :is([data-slot=\"toolbar-button\"], [data-slot=\"toggle\"], [data-slot=\"select-trigger\"], [data-slot=\"menu-trigger\"]) {\n    border-radius: max(0px, calc(var(--ui-radius) - 5px));\n  }\n\n  .rich-text-block-type {\n    min-inline-size: 8.5rem;\n  }\n\n  /* ------------------------------------------------------------ the text */\n\n  .rich-text-content {\n    position: relative;\n    min-block-size: var(--rich-text-min-height);\n    max-block-size: var(--rich-text-max-height);\n    overflow-y: auto;\n    padding: var(--rich-text-padding-block) var(--rich-text-padding-inline);\n    line-height: 1.6;\n    overflow-wrap: anywhere;\n    white-space: pre-wrap;\n    cursor: text;\n    caret-color: var(--ui-foreground);\n\n    & > * {\n      margin: 0;\n    }\n\n    & > * + * {\n      margin-block-start: 0.5em;\n    }\n\n    /* The placeholder, while the document is one empty paragraph. */\n    &[data-empty][aria-placeholder]::before {\n      content: attr(aria-placeholder);\n      position: absolute;\n      inset-block-start: var(--rich-text-padding-block);\n      inset-inline: var(--rich-text-padding-inline);\n      color: var(--ui-muted-foreground);\n      pointer-events: none;\n    }\n\n    &[contenteditable=\"false\"] {\n      cursor: default;\n    }\n  }\n\n  /* Saved text shown read-only: the document's typography, none of the field's box. */\n  .rich-text-content.rich-text-static {\n    min-block-size: 0;\n    max-block-size: none;\n    padding: 0;\n    overflow: visible;\n    cursor: auto;\n    white-space: normal;\n\n    & .rich-text-paragraph,\n    & .rich-text-heading,\n    & .rich-text-quote,\n    & li {\n      white-space: pre-wrap;\n    }\n  }\n\n  .rich-text-heading {\n    line-height: 1.25;\n    font-weight: 650;\n    text-wrap: balance;\n\n    * + & {\n      margin-block-start: 0.9em;\n    }\n  }\n\n  h1.rich-text-heading {\n    font-size: 1.625em;\n    letter-spacing: -0.01em;\n  }\n\n  h2.rich-text-heading {\n    font-size: 1.3125em;\n  }\n\n  h3.rich-text-heading {\n    font-size: 1.0625em;\n  }\n\n  .rich-text-quote {\n    padding-inline-start: 0.875em;\n    border-inline-start: 3px solid var(--ui-border);\n    color: var(--ui-muted-foreground);\n\n    /* Quote blocks in a row read as one quote: the bar runs on through the gap. */\n    & + & {\n      margin-block-start: 0;\n      padding-block-start: 0.5em;\n    }\n  }\n\n  .rich-text-code {\n    padding: 0.75em 1em;\n    border-radius: var(--ui-radius);\n    background: var(--ui-muted);\n    font-family: var(--ui-font-mono, ui-monospace, monospace);\n    font-size: 0.875em;\n    line-height: 1.55;\n    white-space: pre;\n    overflow-x: auto;\n    tab-size: 2;\n\n    & code {\n      font: inherit;\n    }\n  }\n\n  .rich-text-content :not(pre) > code {\n    padding: 0.1em 0.3em;\n    border-radius: 4px;\n    background: var(--ui-muted);\n    font-family: var(--ui-font-mono, ui-monospace, monospace);\n    font-size: 0.875em;\n  }\n\n  /* Links keep the text color (4.5:1 in every skin) with an accent underline. */\n  .rich-text-content a {\n    color: inherit;\n    text-decoration: underline;\n    text-decoration-color: var(--ui-primary);\n    text-decoration-thickness: 1.5px;\n    text-underline-offset: 0.18em;\n  }\n\n  .rich-text-mention {\n    padding: 0 0.25em;\n    border: 1px solid transparent;\n    border-radius: 4px;\n    /* A tint of the accent, so a mention stands out on muted surfaces too. */\n    background: var(--ui-muted);\n    background: color-mix(in oklch, var(--ui-primary) 14%, transparent);\n    font-weight: 550;\n    white-space: nowrap;\n  }\n\n  /* Lists are flat (one list per run of items); depth is the item's indent. */\n  .rich-text-list {\n    padding-inline-start: var(--rich-text-indent);\n\n    & li + li {\n      margin-block-start: 0.2em;\n    }\n\n    & li {\n      margin-inline-start: calc(var(--rich-text-indent) * var(--level, 0));\n    }\n\n    & li[data-indent=\"1\"] {\n      --level: 1;\n    }\n\n    & li[data-indent=\"2\"] {\n      --level: 2;\n    }\n\n    & li[data-indent=\"3\"] {\n      --level: 3;\n    }\n\n    & li[data-indent=\"4\"] {\n      --level: 4;\n    }\n  }\n\n  .rich-text-list-bullet li {\n    list-style-type: disc;\n\n    &:is([data-indent=\"1\"], [data-indent=\"4\"]) {\n      list-style-type: circle;\n    }\n\n    &:is([data-indent=\"2\"]) {\n      list-style-type: square;\n    }\n  }\n\n  .rich-text-list-ordered li {\n    list-style-type: decimal;\n\n    &:is([data-indent=\"1\"], [data-indent=\"4\"]) {\n      list-style-type: lower-alpha;\n    }\n\n    &:is([data-indent=\"2\"]) {\n      list-style-type: lower-roman;\n    }\n  }\n\n  .rich-text-list-task {\n    padding-inline-start: 0;\n\n    & li {\n      position: relative;\n      list-style: none;\n      padding-inline-start: 1.75em;\n    }\n\n    & li[data-checked=\"true\"] {\n      color: var(--ui-muted-foreground);\n      text-decoration: line-through;\n      text-decoration-color: color-mix(in oklch, currentColor 60%, transparent);\n    }\n  }\n\n  .rich-text-check {\n    position: absolute;\n    inset-inline-start: 0.1em;\n    inset-block-start: calc((1lh - 1.05em) / 2);\n    inline-size: 1.05em;\n    block-size: 1.05em;\n    border: 1.5px solid var(--ui-input);\n    border-radius: 4px;\n    background: var(--ui-background);\n    cursor: pointer;\n\n    /* A bigger target than the box. */\n    &::after {\n      content: \"\";\n      position: absolute;\n      inset: -0.35em;\n    }\n\n    [data-checked=\"true\"] > & {\n      border-color: var(--ui-primary);\n      background: var(--ui-primary);\n\n      &::before {\n        content: \"\";\n        position: absolute;\n        inset: 0;\n        background: var(--ui-primary-foreground);\n        mask: var(--ui-icon-check) center / 80% no-repeat;\n      }\n    }\n\n    .rich-text-content[contenteditable=\"false\"] & {\n      cursor: default;\n    }\n  }\n\n  .rich-text-divider {\n    padding-block: 0.5em;\n\n    & hr {\n      margin: 0;\n      border: 0;\n      border-block-start: 1px solid var(--ui-border);\n    }\n  }\n\n  .rich-text-image img {\n    display: block;\n    max-inline-size: 100%;\n    block-size: auto;\n    border-radius: var(--ui-radius);\n  }\n\n  /* A rule or image has no caret: when it's the selection, it wears the ring. */\n  :is(.rich-text-divider, .rich-text-image)[data-selected] {\n    border-radius: var(--ui-radius);\n    outline: 2px solid var(--ui-ring-border);\n    outline-offset: 2px;\n  }\n\n  /* ------------------------------------------------------------ around the text */\n\n  .rich-text-count {\n    margin: 0;\n    padding: 0.375rem var(--rich-text-padding-inline);\n    border-block-start: 1px solid var(--ui-border);\n    color: var(--ui-muted-foreground);\n    font-size: 0.8125rem;\n    font-variant-numeric: tabular-nums;\n    text-align: end;\n\n    &[data-over] {\n      color: var(--ui-destructive);\n      font-weight: 550;\n    }\n  }\n\n  .rich-text-menu {\n    max-block-size: min(28rem, var(--available-height, 28rem));\n    overflow-y: auto;\n  }\n\n  .rich-text-menu [data-slot=\"trigger-menu-item\"] {\n    display: flex;\n    align-items: center;\n    gap: 0.625rem;\n\n    & svg {\n      flex: none;\n      inline-size: 1rem;\n      block-size: 1rem;\n      color: var(--ui-muted-foreground);\n    }\n  }\n\n  .rich-text-menu-glyph {\n    flex: none;\n    inline-size: 1rem;\n    color: var(--ui-muted-foreground);\n    font-size: 0.75rem;\n    font-weight: 700;\n    line-height: 1;\n    text-align: center;\n  }\n\n  .rich-text-menu-text {\n    display: grid;\n    gap: 1px;\n    min-inline-size: 0;\n    line-height: 1.3;\n  }\n\n  .rich-text-menu-hint {\n    color: var(--ui-muted-foreground);\n    font-size: 0.8125em;\n  }\n\n  .rich-text-link {\n    inline-size: min(22rem, calc(100vw - 2rem));\n  }\n\n  .rich-text-link-form {\n    display: grid;\n    gap: 0.75rem;\n    margin-block-start: 0.5rem;\n  }\n\n  .rich-text-link-problem {\n    margin: 0;\n    color: var(--ui-destructive);\n    font-size: 0.8125rem;\n  }\n\n  .rich-text-link-actions {\n    display: flex;\n    justify-content: flex-end;\n    gap: 0.5rem;\n  }\n\n  @media (forced-colors: active) {\n    .rich-text-check {\n      border-color: CanvasText;\n\n      [data-checked=\"true\"] > &::before {\n        background: Canvas;\n      }\n    }\n\n    .rich-text-mention {\n      border-color: CanvasText;\n    }\n  }\n}\n",
      "type": "registry:file",
      "target": "@ui/rich-text/rich-text.css"
    },
    {
      "path": "registry/uiset/ui/shell/shell.css",
      "content": "@layer ui-sdk, uiset.tokens, uiset.base, uiset.skin;\n\n@layer uiset.base {\n  :where([data-uiset]) {\n    /* Status colors: text and edges hold 4.5:1 / 3:1 on --ui-background in each scheme. */\n    /* Dark values also clear 4.5:1 on the mid-dark Blueprint and Studio panels. */\n    --tone-info: light-dark(oklch(0.48 0.15 255), oklch(0.86 0.08 240));\n    --tone-success: light-dark(oklch(0.47 0.12 150), oklch(0.87 0.11 150));\n    --tone-warning: light-dark(oklch(0.5 0.12 70), oklch(0.89 0.11 85));\n    --tone-danger: light-dark(oklch(0.46 0.19 27), oklch(0.86 0.08 25));\n    --tone-neutral: var(--ui-muted-foreground);\n  }\n\n  .uiset-visually-hidden {\n    position: absolute;\n    width: 1px;\n    height: 1px;\n    overflow: hidden;\n    clip-path: inset(50%);\n    white-space: nowrap;\n  }\n\n  .uiset-icon {\n    width: 1rem;\n    height: 1rem;\n    flex-shrink: 0;\n    fill: none;\n    stroke: currentColor;\n    stroke-width: 1.75;\n    stroke-linecap: round;\n    stroke-linejoin: round;\n  }\n\n  /* App shell */\n\n  .app-shell {\n    --sidebar-width: 15rem;\n    display: grid;\n    grid-template-columns: var(--sidebar-width) minmax(0, 1fr);\n    min-height: var(--app-shell-height, 100dvh);\n    background: var(--ui-background);\n    color: var(--ui-foreground);\n\n    &[data-narrow] {\n      grid-template-columns: minmax(0, 1fr);\n    }\n  }\n\n  [data-sidebar=\"collapsed\"] .app-shell:not([data-narrow]) {\n    --sidebar-width: 3.75rem;\n  }\n\n  .app-sidebar,\n  .app-drawer {\n    display: flex;\n    flex-direction: column;\n    gap: 0.75rem;\n    min-width: 0;\n    padding: 0.75rem;\n    border-inline-end: 1px solid var(--ui-border);\n    background: color-mix(in oklab, var(--ui-muted) 55%, var(--ui-background));\n    overflow: hidden;\n  }\n\n  .app-sidebar-top {\n    display: flex;\n    align-items: center;\n    justify-content: space-between;\n    gap: 0.5rem;\n    min-height: 2.25rem;\n  }\n\n  .app-brand {\n    min-width: 0;\n    margin: 0;\n    overflow: hidden;\n    font-weight: 600;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n  }\n\n  [data-sidebar=\"collapsed\"] .app-sidebar .app-brand {\n    display: none;\n  }\n\n  .app-sidebar-toggle,\n  .app-menu-button {\n    flex-shrink: 0;\n    width: 2.25rem;\n    height: 2.25rem;\n    padding: 0;\n  }\n\n  .app-main {\n    display: flex;\n    flex-direction: column;\n    min-width: 0;\n  }\n\n  /* Its padding counts in its height, with or without a page's box-sizing reset. */\n  .app-header {\n    box-sizing: border-box;\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    gap: 0.75rem;\n    min-height: 3.25rem;\n    padding: 0.5rem 1rem;\n    border-bottom: 1px solid var(--ui-border);\n  }\n\n  /* The padding is a variable, so a full-bleed page (an inbox) can cancel it exactly. */\n  .app-content {\n    --app-shell-pad: clamp(1rem, 3vw, 2rem);\n    flex: 1;\n    min-width: 0;\n    padding: var(--app-shell-pad);\n  }\n\n  .sidebar-nav {\n    display: grid;\n    gap: 1rem;\n  }\n\n  .sidebar-group {\n    display: grid;\n    gap: 0.25rem;\n\n    ul {\n      display: grid;\n      gap: 2px;\n      margin: 0;\n      padding: 0;\n      list-style: none;\n    }\n  }\n\n  .sidebar-group-title {\n    margin: 0;\n    padding-inline: 0.5rem;\n    font-size: 0.75rem;\n    font-weight: 600;\n    color: var(--ui-muted-foreground);\n  }\n\n  /* Collapsed to icons: group titles leave the layout (a hidden title used to keep its\n     width and push the icons off center), and a rule separates the groups instead. */\n  [data-sidebar=\"collapsed\"] .app-sidebar {\n    .sidebar-group-title {\n      position: absolute;\n      width: 1px;\n      height: 1px;\n      overflow: hidden;\n      clip-path: inset(50%);\n      white-space: nowrap;\n    }\n\n    .sidebar-nav {\n      gap: 0.5rem;\n    }\n\n    .sidebar-group + .sidebar-group {\n      padding-block-start: 0.5rem;\n      border-block-start: 1px solid var(--ui-border);\n    }\n  }\n\n  /* A tooltip trigger, so UI SDK's stylesheet would draw it as a button: reset that. */\n  .sidebar-link {\n    display: flex;\n    align-items: center;\n    justify-content: flex-start;\n    gap: 0.625rem;\n    width: 100%;\n    height: auto;\n    min-height: 2.25rem;\n    padding: 0.375rem 0.5rem;\n    border: 0;\n    border-radius: var(--ui-radius);\n    background: transparent;\n    color: var(--ui-foreground);\n    font-weight: 400;\n    text-decoration: none;\n\n    &:hover {\n      background: var(--ui-muted);\n    }\n\n    &[aria-current=\"page\"] {\n      position: relative;\n      background: var(--ui-muted);\n      font-weight: 600;\n\n      /* A short bar, inset from the corners (an inset shadow bent around them). */\n      &::before {\n        content: \"\";\n        position: absolute;\n        inset-block: 0.5rem;\n        inset-inline-start: 0;\n        inline-size: 3px;\n        border-radius: 999px;\n        background: var(--ui-primary);\n      }\n    }\n\n    &:focus-visible {\n      outline: 2px solid var(--ui-ring-border);\n      outline-offset: -2px;\n    }\n  }\n\n  .sidebar-icon {\n    display: inline-grid;\n    place-items: center;\n    width: 1.25rem;\n    flex-shrink: 0;\n  }\n\n  .sidebar-label {\n    flex: 1;\n    min-width: 0;\n    overflow: hidden;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n  }\n\n  .sidebar-badge {\n    font-size: 0.75rem;\n  }\n\n  /* Each link is a square icon button, centered in the rail under the toggle; the current\n     page shows by its fill and an accent icon (a side bar on a square reads as a glitch). */\n  [data-sidebar=\"collapsed\"] .app-sidebar {\n    .sidebar-link {\n      justify-content: center;\n      inline-size: 2.25rem;\n      min-block-size: 2.25rem;\n      margin-inline: auto;\n      padding: 0;\n\n      &[aria-current=\"page\"] {\n        color: color-mix(in oklch, var(--ui-primary) 55%, var(--ui-foreground));\n\n        &::before {\n          display: none;\n        }\n      }\n    }\n\n    .sidebar-label,\n    .sidebar-badge {\n      position: absolute;\n      width: 1px;\n      height: 1px;\n      overflow: hidden;\n      clip-path: inset(50%);\n    }\n  }\n\n  /* The tooltip repeats the visible label, so it only shows when labels are hidden. */\n  [data-sidebar=\"expanded\"] .sidebar-tooltip,\n  .app-drawer .sidebar-tooltip {\n    display: none;\n  }\n\n  /* Page structure */\n\n  .breadcrumbs ol {\n    display: flex;\n    flex-wrap: wrap;\n    align-items: center;\n    gap: 0.25rem;\n    margin: 0;\n    padding: 0;\n    list-style: none;\n    font-size: 0.875rem;\n  }\n\n  .breadcrumbs li {\n    display: inline-flex;\n    align-items: center;\n    gap: 0.25rem;\n    color: var(--ui-muted-foreground);\n\n    a {\n      color: inherit;\n      text-underline-offset: 0.2em;\n    }\n\n    [aria-current=\"page\"] {\n      color: var(--ui-foreground);\n      font-weight: 500;\n    }\n  }\n\n  .breadcrumbs-separator {\n    width: 0.875rem;\n    height: 0.875rem;\n  }\n\n  .page-header {\n    display: grid;\n    gap: 0.75rem;\n    margin-bottom: 1.5rem;\n  }\n\n  .page-header-row {\n    display: flex;\n    flex-wrap: wrap;\n    align-items: flex-end;\n    justify-content: space-between;\n    gap: 1rem;\n  }\n\n  .page-header-title {\n    margin: 0;\n    font-size: clamp(1.5rem, 3vw, 1.875rem);\n    line-height: 1.15;\n    text-wrap: balance;\n  }\n\n  .page-header-description {\n    max-width: 42rem;\n    margin: 0.375rem 0 0;\n    color: var(--ui-muted-foreground);\n  }\n\n  .page-header-actions {\n    display: flex;\n    flex-wrap: wrap;\n    gap: 0.5rem;\n  }\n\n  .card {\n    display: grid;\n    gap: 1rem;\n    min-width: 0;\n    padding: 1.25rem;\n    border: 1px solid var(--ui-border);\n    border-radius: calc(var(--ui-radius) + 6px);\n    background: var(--ui-background);\n  }\n\n  .card-header {\n    display: grid;\n    gap: 0.25rem;\n  }\n\n  .card-title {\n    margin: 0;\n    font-size: 1rem;\n    font-weight: 600;\n  }\n\n  .card-description {\n    margin: 0;\n    color: var(--ui-muted-foreground);\n    font-size: 0.875rem;\n  }\n\n  .card-footer {\n    display: flex;\n    flex-wrap: wrap;\n    gap: 0.5rem;\n    padding-top: 1rem;\n    border-top: 1px solid var(--ui-border);\n  }\n\n  /* Data display */\n\n  .badge {\n    --badge-color: var(--tone-neutral);\n    display: inline-flex;\n    align-items: center;\n    gap: 0.25rem;\n    padding: 0.0625rem 0.5rem;\n    border: 1px solid color-mix(in oklab, var(--badge-color) 55%, transparent);\n    border-radius: min(999px, calc(var(--ui-radius) * 999));\n    background: color-mix(in oklab, var(--badge-color) 10%, var(--ui-background));\n    color: var(--badge-color);\n    font-size: 0.75rem;\n    font-weight: 600;\n    line-height: 1.5;\n    white-space: nowrap;\n\n    &[data-tone=\"info\"] {\n      --badge-color: var(--tone-info);\n    }\n\n    &[data-tone=\"success\"] {\n      --badge-color: var(--tone-success);\n    }\n\n    &[data-tone=\"warning\"] {\n      --badge-color: var(--tone-warning);\n    }\n\n    &[data-tone=\"danger\"] {\n      --badge-color: var(--tone-danger);\n    }\n  }\n\n  .count-badge {\n    position: relative;\n    display: inline-flex;\n    vertical-align: middle;\n  }\n\n  /* The solid button's colors: every skin already holds 4.5:1 between them. */\n  .count-badge-count {\n    position: absolute;\n    inset-block-start: 0;\n    inset-inline-end: 0;\n    translate: 40% -40%;\n    display: inline-flex;\n    align-items: center;\n    justify-content: center;\n    box-sizing: border-box;\n    min-width: 1.125rem;\n    height: 1.125rem;\n    padding-inline: 0.3125rem;\n    border-radius: min(999px, calc(var(--ui-radius) * 999));\n    background: var(--uiset-solid-bg);\n    color: var(--uiset-solid-fg);\n    box-shadow: 0 0 0 2px var(--ui-background);\n    font-size: 0.6875rem;\n    font-weight: 600;\n    font-variant-numeric: tabular-nums;\n    line-height: 1;\n    white-space: nowrap;\n    pointer-events: none;\n\n    &:dir(rtl) {\n      translate: -40% -40%;\n    }\n\n    &[data-dot] {\n      min-width: 0.625rem;\n      width: 0.625rem;\n      height: 0.625rem;\n      padding: 0;\n      translate: 20% -20%;\n\n      &:dir(rtl) {\n        translate: -20% -20%;\n      }\n    }\n  }\n\n  /* Each avatar overlaps the one before it, with a ring of the page color between them. */\n  .avatar-group {\n    display: inline-flex;\n    align-items: center;\n    vertical-align: middle;\n\n    & > * {\n      box-shadow: 0 0 0 2px var(--ui-background);\n    }\n\n    /* A small overlap: more would cover the next avatar's initials. */\n    & > * + * {\n      margin-inline-start: calc(var(--ui-spacing) * -1);\n    }\n  }\n\n  .avatar-group-more {\n    font-variant-numeric: tabular-nums;\n  }\n\n  /* Content sits at the top, so figures in a row line up whether or not one has a trend. */\n  .stat {\n    display: grid;\n    align-content: start;\n    gap: 0.25rem;\n\n    p {\n      margin: 0;\n    }\n  }\n\n  .stat-label {\n    font-size: 0.875rem;\n    color: var(--ui-muted-foreground);\n  }\n\n  .stat-trend {\n    max-inline-size: 100%;\n  }\n\n  /* A standalone figure keeps proportional digits; tabular ones look loose this big. */\n  .stat-value {\n    font-size: 1.75rem;\n    font-weight: 650;\n    line-height: 1.15;\n  }\n\n  .stat-change {\n    display: inline-flex;\n    align-items: center;\n    gap: 0.25rem;\n    font-size: 0.875rem;\n    font-weight: 600;\n\n    &[data-good] {\n      color: var(--tone-success);\n    }\n\n    &[data-bad] {\n      color: var(--tone-danger);\n    }\n  }\n\n  .stat-period,\n  .stat-description {\n    color: var(--ui-muted-foreground);\n    font-weight: 400;\n  }\n\n  .stat-description {\n    font-size: 0.8125rem;\n  }\n\n  .empty-state {\n    display: grid;\n    justify-items: center;\n    gap: 0.5rem;\n    padding: 2.5rem 1rem;\n    text-align: center;\n  }\n\n  .empty-state-icon {\n    width: 2rem;\n    height: 2rem;\n    color: var(--ui-muted-foreground);\n  }\n\n  .empty-state-title {\n    margin: 0.25rem 0 0;\n    font-size: 1.0625rem;\n  }\n\n  .empty-state-description {\n    max-width: 28rem;\n    margin: 0;\n    color: var(--ui-muted-foreground);\n  }\n\n  .empty-state-actions {\n    display: flex;\n    flex-wrap: wrap;\n    justify-content: center;\n    gap: 0.5rem;\n    margin-top: 0.5rem;\n  }\n\n  .skeleton {\n    display: block;\n    width: 100%;\n    border-radius: var(--ui-radius);\n    background: linear-gradient(\n        90deg,\n        var(--ui-muted) 0 35%,\n        color-mix(in oklab, var(--ui-muted), var(--ui-foreground) 8%) 50%,\n        var(--ui-muted) 65% 100%\n      )\n      0 0 / 300% 100%;\n    animation: skeleton-wave 1.6s ease-in-out infinite;\n  }\n\n  .skeleton-text {\n    display: grid;\n    gap: 0.5rem;\n\n    .skeleton {\n      height: 0.75rem;\n    }\n  }\n\n  @keyframes skeleton-wave {\n    from {\n      background-position: 100% 0;\n    }\n    to {\n      background-position: 0 0;\n    }\n  }\n\n  .description-list {\n    display: grid;\n    margin: 0;\n\n    &[data-layout=\"columns\"] .description-item {\n      display: grid;\n      grid-template-columns: minmax(8rem, 1fr) 2fr;\n      gap: 1rem;\n    }\n\n    dt {\n      color: var(--ui-muted-foreground);\n    }\n\n    dd {\n      margin: 0;\n      min-width: 0;\n      overflow-wrap: anywhere;\n    }\n  }\n\n  .description-item {\n    padding-block: 0.625rem;\n    border-bottom: 1px solid var(--ui-border);\n\n    &:last-child {\n      border-bottom: 0;\n    }\n  }\n\n  .item-list {\n    display: grid;\n    margin: 0;\n    padding: 0;\n    list-style: none;\n  }\n\n  .item {\n    display: flex;\n    align-items: center;\n    gap: 0.75rem;\n    min-height: 3rem;\n    padding-block: 0.625rem;\n    border-bottom: 1px solid var(--ui-border);\n\n    &:last-child {\n      border-bottom: 0;\n    }\n  }\n\n  .item-text {\n    display: grid;\n    flex: 1;\n    min-width: 0;\n  }\n\n  .item-title {\n    overflow: hidden;\n    color: var(--ui-foreground);\n    font-weight: 500;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n  }\n\n  a.item-title {\n    text-decoration: none;\n\n    &:hover {\n      text-decoration: underline;\n    }\n  }\n\n  .item-description,\n  .item-meta {\n    color: var(--ui-muted-foreground);\n    font-size: 0.8125rem;\n  }\n\n  .item-actions {\n    display: flex;\n    gap: 0.25rem;\n  }\n\n  .alert {\n    --alert-color: var(--tone-info);\n    display: grid;\n    grid-template-columns: auto minmax(0, 1fr) auto;\n    gap: 0.75rem;\n    align-items: start;\n    padding: 0.875rem 1rem;\n    position: relative;\n    overflow: hidden;\n    padding-inline-start: calc(1rem + 3px);\n    border: 1px solid color-mix(in oklab, var(--alert-color) 45%, var(--ui-border));\n    border-radius: calc(var(--ui-radius) + 4px);\n    background: color-mix(in oklab, var(--alert-color) 7%, var(--ui-background));\n\n    /* The accent is a straight bar the corners clip; a thick border would taper into them. */\n    &::before {\n      content: \"\";\n      position: absolute;\n      inset-block: 0;\n      inset-inline-start: 0;\n      inline-size: 4px;\n      background: var(--alert-color);\n    }\n\n    &[data-tone=\"success\"] {\n      --alert-color: var(--tone-success);\n    }\n\n    &[data-tone=\"warning\"] {\n      --alert-color: var(--tone-warning);\n    }\n\n    &[data-tone=\"danger\"] {\n      --alert-color: var(--tone-danger);\n    }\n  }\n\n  .alert-icon {\n    width: 1.25rem;\n    height: 1.25rem;\n    color: var(--alert-color);\n  }\n\n  .alert-body {\n    display: grid;\n    gap: 0.25rem;\n  }\n\n  .alert-title {\n    margin: 0;\n    font-weight: 600;\n  }\n\n  .alert-text {\n    color: var(--ui-foreground);\n  }\n\n  .alert-actions {\n    display: flex;\n    flex-wrap: wrap;\n    gap: 0.5rem;\n    margin-top: 0.375rem;\n  }\n\n  .alert-dismiss {\n    width: 2rem;\n    height: 2rem;\n    padding: 0;\n  }\n\n  /* Sized in its own em so a key sits inside a line of text, not below it. */\n  .kbd {\n    display: inline-flex;\n    align-items: center;\n    min-width: 1.75em;\n    height: 1.75em;\n    justify-content: center;\n    padding-inline: 0.4em;\n    vertical-align: 0.125em;\n    line-height: 1;\n    border: 1px solid var(--ui-input);\n    border-bottom-width: 2px;\n    border-radius: calc(var(--ui-radius) / 2 + 2px);\n    background: var(--ui-background);\n    color: var(--ui-foreground);\n    font-family: var(--ui-font-mono);\n    font-size: 0.75rem;\n  }\n\n  .spinner {\n    display: inline-block;\n    flex-shrink: 0;\n    border: 2px solid color-mix(in oklab, var(--ui-foreground) 18%, transparent);\n    border-top-color: var(--ui-primary);\n    border-radius: 50%;\n    animation: spinner-turn 0.8s linear infinite;\n  }\n\n  @keyframes spinner-turn {\n    to {\n      rotate: 1turn;\n    }\n  }\n\n  .stepper {\n    container-type: inline-size;\n  }\n\n  .stepper ol {\n    display: flex;\n    flex-wrap: wrap;\n    gap: 0.25rem 1rem;\n    margin: 0;\n    padding: 0;\n    list-style: none;\n  }\n\n  /* Marks line up across steps, whether a step has a description or not. */\n  .stepper-step {\n    align-items: flex-start;\n    gap: 0.625rem;\n    height: auto;\n    min-height: 2.75rem;\n    padding: 0.375rem 0.625rem 0.375rem 0.375rem;\n    text-align: start;\n  }\n\n  @container (max-width: 30rem) {\n    .stepper ol {\n      flex-direction: column;\n      flex-wrap: nowrap;\n    }\n  }\n\n  .stepper-mark {\n    box-sizing: border-box;\n    display: inline-grid;\n    place-items: center;\n    width: 1.75rem;\n    height: 1.75rem;\n    flex-shrink: 0;\n    border: 2px solid var(--ui-input);\n    border-radius: 50%;\n    font-size: 0.8125rem;\n    font-weight: 600;\n    font-variant-numeric: tabular-nums;\n  }\n\n  .stepper li[data-state=\"current\"] .stepper-mark {\n    border-color: var(--ui-primary);\n    color: var(--ui-primary);\n  }\n\n  .stepper li[data-state=\"complete\"] .stepper-mark {\n    border-color: var(--ui-primary);\n    background: var(--ui-primary);\n    color: var(--ui-primary-foreground);\n  }\n\n  /* The label's first line centers on the mark, whatever the page's line height. */\n  .stepper-text {\n    display: grid;\n    padding-block-start: max(0px, calc((1.75rem - 1lh) / 2));\n  }\n\n  .stepper-label {\n    font-weight: 600;\n  }\n\n  .stepper-description {\n    font-size: 0.75rem;\n    color: var(--ui-muted-foreground);\n  }\n\n  .search-field {\n    position: relative;\n    display: flex;\n    /* A row even as a UI SDK field (which stacks its parts), so the icon centers. */\n    flex-direction: row;\n    align-items: center;\n    width: 100%;\n\n    [data-slot=\"input\"] {\n      width: 100%;\n      padding-inline: 2.125rem 3rem;\n    }\n  }\n\n  .search-field-icon {\n    position: absolute;\n    inset-inline-start: 0.625rem;\n    color: var(--ui-muted-foreground);\n    pointer-events: none;\n  }\n\n  .search-field-clear {\n    position: absolute;\n    inset-inline-end: 0.25rem;\n    width: 1.75rem;\n    height: 1.75rem;\n    padding: 0;\n  }\n\n  /* The browser's own clear button would duplicate ours. */\n  .search-field input[type=\"search\"]::-webkit-search-cancel-button {\n    display: none;\n  }\n\n  .search-field-hint {\n    position: absolute;\n    inset-inline-end: 0.5rem;\n    pointer-events: none;\n  }\n\n  .copy-button {\n    gap: 0.375rem;\n  }\n\n  @media (prefers-reduced-motion: reduce) {\n    .skeleton,\n    .spinner {\n      animation-duration: 0s;\n    }\n\n    .spinner {\n      border-top-color: var(--ui-muted-foreground);\n    }\n  }\n\n  @media (forced-colors: active) {\n    .badge,\n    .alert,\n    .kbd {\n      border-color: CanvasText;\n    }\n\n    /* Shadows don't draw here, so the rings become real edges. */\n    .avatar-group > *,\n    .count-badge-count {\n      outline: 1px solid CanvasText;\n    }\n\n    .count-badge-count {\n      background: Canvas;\n      color: CanvasText;\n    }\n\n    .sidebar-link[aria-current=\"page\"] {\n      outline: 2px solid Highlight;\n    }\n\n    .stepper li[data-state=\"complete\"] .stepper-mark {\n      background: Highlight;\n      color: HighlightText;\n    }\n  }\n}\n",
      "type": "registry:file",
      "target": "@ui/shell/shell.css"
    },
    {
      "path": "registry/uiset/ui/shell/icons.tsx",
      "content": "import { iconPaths, type IconName } from \"./icon-paths\"\n\nfunction Icon({ name, className }: { name: IconName; className?: string }) {\n  return (\n    <svg\n      viewBox=\"0 0 24 24\"\n      aria-hidden=\"true\"\n      focusable=\"false\"\n      className={[\"uiset-icon\", className].filter(Boolean).join(\" \")}\n    >\n      <path d={iconPaths[name]} />\n    </svg>\n  )\n}\n\nexport { Icon }\nexport type { IconName }\n",
      "type": "registry:file",
      "target": "@ui/shell/icons.tsx"
    },
    {
      "path": "registry/uiset/ui/shell/icon-paths.ts",
      "content": "// UISet's icons as SVG path data on a 24×24 grid, stroked: framework-free, so the React\n// Icon and the web elements draw the same shapes.\nconst iconPaths = {\n  // Text editing (the rich text editor's toolbar).\n  bold: \"M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z\",\n  italic: \"M10 5h8M6 19h8M14 5l-4 14\",\n  underline: \"M7 5v6a5 5 0 0 0 10 0V5M5 20h14\",\n  strike: \"M5 12h14M16 7a4 4 0 0 0-3.5-2h-1A3.5 3.5 0 0 0 8 8.5c0 1.4.8 2.4 2.5 3M8 17a4 4 0 0 0 3.5 2h1a3.5 3.5 0 0 0 3.5-3.5c0-.6-.1-1.1-.4-1.5\",\n  \"code-inline\": \"M9 8l-4 4 4 4M15 8l4 4-4 4\",\n  link: \"M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1\",\n  \"list-bullet\": \"M9 6h11M9 12h11M9 18h11M4.5 6v.01M4.5 12v.01M4.5 18v.01\",\n  \"list-ordered\": \"M10 6h10M10 12h10M10 18h10M4 4.5l1.5-.5v4.5M4 15a1.3 1.3 0 0 1 2.4.6c0 .8-2.4 1.7-2.4 2.9h2.6\",\n  \"list-check\": \"M11 6h9M11 12h9M11 18h9M3.5 6l1.5 1.5L8 4.5M3.5 12l1.5 1.5 3-3M3.5 18l1.5 1.5 3-3\",\n  quote: \"M6 7h4v4c0 3-1.3 5-4 6M14 7h4v4c0 3-1.3 5-4 6\",\n  undo: \"M9 14L4 9l5-5M4 9h10a6 6 0 0 1 0 12h-3\",\n  redo: \"M15 14l5-5-5-5M20 9H10a6 6 0 0 0 0 12h3\",\n  image: \"M4 5h16v14H4zM4 16l5-5 4 4 3-3 4 4M15 9.5v.01\",\n  \"code-block\": \"M4 5h16v14H4zM9.5 10l-2 2 2 2M14.5 10l2 2-2 2\",\n  rule: \"M4 12h16M8 8h8M8 16h8\",\n  menu: \"M4 7h16M4 12h16M4 17h16\",\n  sidebar: \"M4 5h16v14H4zM9 5v14\",\n  chevron: \"M9 6l6 6-6 6\",\n  search: \"M11 18a7 7 0 1 1 0-14 7 7 0 0 1 0 14zM20 20l-4-4\",\n  close: \"M6 6l12 12M18 6L6 18\",\n  copy: \"M8 8h11v11H8zM5 16V5h11\",\n  check: \"M5 12.5l4.5 4.5L19 7.5\",\n  info: \"M12 11v6M12 7.5v.01M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18z\",\n  success: \"M8 12.5l2.5 2.5L16 9.5M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18z\",\n  warning:\n    \"M12 9v4M12 16.5v.01M10.3 4.2L2.6 18a2 2 0 0 0 1.7 3h15.4a2 2 0 0 0 1.7-3L13.7 4.2a2 2 0 0 0-3.4 0z\",\n  danger: \"M15 9l-6 6M9 9l6 6M12 21a9 9 0 1 1 0-18 9 9 0 0 1 0 18z\",\n  up: \"M7 14l5-5 5 5\",\n  down: \"M7 10l5 5 5-5\",\n  inbox: \"M4 13l2.5-7h11l2.5 7v6H4zM4 13h5l1 2h4l1-2h5\",\n  more: \"M4.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0M10.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0M16.8 12a1.2 1.2 0 1 0 2.4 0a1.2 1.2 0 1 0-2.4 0\",\n  columns: \"M4 5h16v14H4zM10 5v14M15 5v14\",\n  download: \"M12 4v11M7 10l5 5 5-5M5 20h14\",\n  upload: \"M12 15V4M7 9l5-5 5 5M5 20h14\",\n  retry: \"M20 12a8 8 0 1 1-8-8c2.2 0 4.3.9 5.9 2.4L20 8.5M20 4v4.5h-4.5\",\n  filter: \"M4 6h16M7 12h10M10 18h4\",\n  home: \"M4 11l8-7 8 7M6 9.5V20h12V9.5M10 20v-5h4v5\",\n  users: \"M9 11a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7zM3 20c0-3.3 2.7-6 6-6s6 2.7 6 6M16 4.5a3.5 3.5 0 0 1 0 6.5M21 20c0-2.6-1.6-4.8-4-5.6\",\n  orders: \"M6 4h12l1 16H5zM9 8a3 3 0 0 0 6 0\",\n  reports: \"M5 20V10M12 20V4M19 20v-7\",\n  settings: \"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 13.5l1.6 1.2-2 3.4-1.9-.7a7 7 0 0 1-2 1.2l-.3 2h-4l-.3-2a7 7 0 0 1-2-1.2l-1.9.7-2-3.4 1.6-1.2a7 7 0 0 1 0-3l-1.6-1.2 2-3.4 1.9.7a7 7 0 0 1 2-1.2l.3-2h4l.3 2a7 7 0 0 1 2 1.2l1.9-.7 2 3.4-1.6 1.2a7 7 0 0 1 0 3z\",\n  mail: \"M4 6h16v12H4zM4 7l8 6 8-6\",\n  star: \"M12 4l2.5 5.2 5.5.8-4 3.9.9 5.6L12 16.8 7.1 19.5l.9-5.6-4-3.9 5.5-.8z\",\n  archive: \"M4 5h16v4H4zM6 9v10h12V9M10 13h4\",\n  trash: \"M5 7h14M10 7V5h4v2M7 7l1 13h8l1-13\",\n  plus: \"M12 5v14M5 12h14\",\n  minus: \"M5 12h14\",\n  fit: \"M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5\",\n  folder: \"M3.5 6.5a1.5 1.5 0 0 1 1.5-1.5h4l2 2h8a1.5 1.5 0 0 1 1.5 1.5v9a1.5 1.5 0 0 1-1.5 1.5H5a1.5 1.5 0 0 1-1.5-1.5z\",\n  file: \"M6 3.5h8l4 4v13H6zM14 3.5v4h4\",\n  branch: \"M6 4v16M18 8a2 2 0 1 0 0-4 2 2 0 0 0 0 4zM18 8c0 5-6 5-12 8\",\n  grip: \"M9 6.5v.01M15 6.5v.01M9 12v.01M15 12v.01M9 17.5v.01M15 17.5v.01\",\n  edit: \"M5 19h4L19 9l-4-4L5 15zM14 6l4 4\",\n  send: \"M4 12l16-8-6 16-2-7z\",\n  card: \"M3 6h18v12H3zM3 10h18M7 15h4\",\n  shield: \"M12 3l7 3v5c0 4.5-3 8.5-7 10-4-1.5-7-5.5-7-10V6z\",\n  bell: \"M6 16V11a6 6 0 0 1 12 0v5l2 2H4zM10 20a2 2 0 0 0 4 0\",\n}\n\ntype IconName = keyof typeof iconPaths\n\n/** An icon as an SVG element, for code without React. */\nfunction iconElement(name: IconName, className?: string) {\n  const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\")\n  svg.setAttribute(\"viewBox\", \"0 0 24 24\")\n  svg.setAttribute(\"aria-hidden\", \"true\")\n  svg.setAttribute(\"focusable\", \"false\")\n  svg.setAttribute(\"class\", [\"uiset-icon\", className].filter(Boolean).join(\" \"))\n  const path = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\")\n  path.setAttribute(\"d\", iconPaths[name])\n  svg.append(path)\n  return svg\n}\n\nexport { iconElement, iconPaths }\nexport type { IconName }\n",
      "type": "registry:file",
      "target": "@ui/shell/icon-paths.ts"
    }
  ],
  "type": "registry:ui"
}