{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "editor",
  "title": "Editor",
  "description": "Always-on live-preview markdown editor: one surface that is both the rendered document and the text you type into, with debounced autosave and a per-construct typography map.",
  "dependencies": [
    "@base-ui/react",
    "@codemirror/commands",
    "@codemirror/lang-markdown",
    "@codemirror/language",
    "@codemirror/state",
    "@codemirror/view",
    "@lezer/common",
    "@lezer/markdown",
    "lucide-react"
  ],
  "registryDependencies": [
    "https://www.deltacomponents.dev/r/utils.json",
    "https://www.deltacomponents.dev/r/button.json",
    "https://www.deltacomponents.dev/r/tooltip.json"
  ],
  "files": [
    {
      "path": "registry/ui/editor.tsx",
      "content": "\"use client\";\n\nimport {\n  createContext,\n  forwardRef,\n  useCallback,\n  useContext,\n  useEffect,\n  useRef,\n  useState,\n  useSyncExternalStore,\n  type ReactNode,\n} from \"react\";\nimport { Compartment, EditorState, type Extension } from \"@codemirror/state\";\nimport { EditorView } from \"@codemirror/view\";\n\nimport {\n  liveMarkdownBase,\n  livePreview,\n  type EditorElements,\n} from \"@/lib/live-markdown\";\nimport { cn } from \"@/lib/utils\";\n\n/** What the corner indicator is reporting. `error` means the write rejected\n *  and the text is only in the browser. */\nexport type SaveState = \"idle\" | \"dirty\" | \"saving\" | \"saved\" | \"error\";\n\nconst SAVE_LABEL: Record<SaveState, string> = {\n  idle: \"\",\n  dirty: \"Unsaved\",\n  saving: \"Saving\",\n  saved: \"Saved\",\n  error: \"Not saved\",\n};\n\n// The view, published to whatever the editor renders above its text (the\n// controls). A version counter rather than the view itself: the view is one\n// mutable object for the editor's whole life, so the way to say \"something\n// changed\" is a tick, and `useSyncExternalStore` turns ticks into renders of\n// the subscriber alone — a keystroke never re-renders the editor.\ninterface EditorStore {\n  view: EditorView | null;\n  version: number;\n  listeners: Set<() => void>;\n}\n\nconst EditorContext = createContext<EditorStore | null>(null);\n\nfunction notify(store: EditorStore) {\n  store.version++;\n  for (const listener of store.listeners) listener();\n}\n\n/** The live `EditorView` of the enclosing `<Editor>`, re-rendering the caller\n *  on every transaction — document, selection or focus — so pressed states\n *  track the caret. Null before the editor has mounted and outside one. */\nexport function useEditorView(): EditorView | null {\n  const store = useContext(EditorContext);\n  if (!store) throw new Error(\"useEditorView must be used inside <Editor>\");\n  const subscribe = useCallback(\n    (listener: () => void) => {\n      store.listeners.add(listener);\n      return () => void store.listeners.delete(listener);\n    },\n    [store],\n  );\n  useSyncExternalStore(\n    subscribe,\n    () => store.version,\n    () => 0,\n  );\n  return store.view;\n}\n\nexport interface EditorProps {\n  /** Seeds the document. The editor owns the text from then on — see the note\n   *  on the save contract in the docs. */\n  defaultValue?: string;\n  placeholder?: string;\n  /** Every keystroke. For persistence use `onSave`, which is debounced. */\n  onChange?: (doc: string) => void;\n  /** Fired after `saveDelay` of idle, on blur, and on unmount — never with a\n   *  document it has already stored. Reject (or throw) to report a failed\n   *  write: the indicator says so and the next flush retries. */\n  onSave?: (doc: string) => void | Promise<void>;\n  saveDelay?: number;\n  /** Hide the corner save indicator and drive your own from `onSaveState`. */\n  showSaveStatus?: boolean;\n  onSaveState?: (state: SaveState) => void;\n  /** Which element each markdown construct renders as, and its classes.\n   *  Omitted keys fall back to `defaultElements`. */\n  elements?: EditorElements;\n  /** Extra CodeMirror extensions, appended after the editor's own. Read once\n   *  at mount like `defaultValue` — reconfiguring would rebuild state the\n   *  user is mid-edit in. */\n  extensions?: Extension;\n  /** Rendered above the text, sharing its width — this is where\n   *  `<EditorControls />` goes. */\n  children?: ReactNode;\n  className?: string;\n}\n\n/**\n * Always-on live-preview markdown editor: one surface that is both the\n * rendered document and the text you type into. Syntax marks conceal\n * everywhere the caret isn't.\n *\n * The editor is created exactly once per mount (empty-dep effect, callbacks\n * held in refs) — rebuilding the view on re-render would drop the caret and\n * the undo history.\n */\nexport const Editor = forwardRef<HTMLDivElement, EditorProps>(function Editor(\n  {\n    defaultValue = \"\",\n    placeholder = \"\",\n    onChange,\n    onSave,\n    saveDelay = 800,\n    showSaveStatus = true,\n    onSaveState,\n    elements,\n    extensions,\n    children,\n    className,\n  },\n  ref,\n) {\n  const containerRef = useRef<HTMLDivElement | null>(null);\n  const viewRef = useRef<EditorView | null>(null);\n  const [store] = useState<EditorStore>(() => ({ view: null, version: 0, listeners: new Set() }));\n  const [mounted, setMounted] = useState(false);\n  const [saveState, setSaveState] = useState<SaveState>(\"idle\");\n  // One compartment so an `elements` change swaps only the preview plugin;\n  // rebuilding the whole extension set would construct a fresh history() and\n  // lose the user's undo stack.\n  const [elementsCompartment] = useState(() => new Compartment());\n\n  // Read once at mount: re-seeding the document from props mid-edit would\n  // fight the user for the caret.\n  const seedRef = useRef({ defaultValue, placeholder, elements, extensions });\n\n  // The editor owns the document after mount; these refs only orchestrate\n  // saving. `savedRef` is the last value known to be STORED and `sendingRef`\n  // the one in flight, so idle ticks, blurs and double-flushes are no-ops.\n  const draftRef = useRef(defaultValue);\n  const savedRef = useRef(defaultValue);\n  const sendingRef = useRef<string | null>(null);\n  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n  // Only the newest save may set the indicator: a slow write that resolves\n  // after a later one would otherwise report stale news.\n  const saveTokenRef = useRef(0);\n  const onChangeRef = useRef(onChange);\n  const onSaveRef = useRef(onSave);\n  const onSaveStateRef = useRef(onSaveState);\n  const saveDelayRef = useRef(saveDelay);\n  useEffect(() => {\n    onChangeRef.current = onChange;\n    onSaveRef.current = onSave;\n    onSaveStateRef.current = onSaveState;\n    saveDelayRef.current = saveDelay;\n  });\n\n  const report = useCallback((state: SaveState) => {\n    setSaveState(state);\n    onSaveStateRef.current?.(state);\n  }, []);\n\n  const flush = useCallback(() => {\n    if (timerRef.current) clearTimeout(timerRef.current);\n    timerRef.current = null;\n    const next = draftRef.current;\n    // Saved verbatim — leading and trailing newlines are part of the document.\n    if (next === savedRef.current || next === sendingRef.current) return;\n    const save = onSaveRef.current;\n    if (!save) {\n      savedRef.current = next;\n      return;\n    }\n    const token = ++saveTokenRef.current;\n    sendingRef.current = next;\n    report(\"saving\");\n    Promise.resolve()\n      .then(() => save(next))\n      .then(() => {\n        // Advanced only once the write lands, so a rejected save stays\n        // pending and the next flush sends it again.\n        savedRef.current = next;\n        if (token === saveTokenRef.current) report(\"saved\");\n      })\n      .catch(() => {\n        if (token === saveTokenRef.current) report(\"error\");\n      })\n      .finally(() => {\n        if (sendingRef.current === next) sendingRef.current = null;\n      });\n  }, [report]);\n  const flushRef = useRef(flush);\n  flushRef.current = flush;\n\n  useEffect(() => {\n    const seed = seedRef.current;\n    const view = new EditorView({\n      parent: containerRef.current!,\n      state: EditorState.create({\n        doc: seed.defaultValue,\n        extensions: [\n          liveMarkdownBase(seed.placeholder),\n          elementsCompartment.of(livePreview(seed.elements)),\n          seed.extensions ?? [],\n          EditorView.updateListener.of((update) => {\n            notify(store);\n            if (!update.docChanged) return;\n            const doc = update.state.doc.toString();\n            draftRef.current = doc;\n            onChangeRef.current?.(doc);\n            if (onSaveRef.current && doc !== savedRef.current) report(\"dirty\");\n            if (timerRef.current) clearTimeout(timerRef.current);\n            timerRef.current = setTimeout(() => flushRef.current(), saveDelayRef.current);\n          }),\n          EditorView.domEventHandlers({\n            blur: () => {\n              flushRef.current();\n            },\n          }),\n        ],\n      }),\n    });\n    viewRef.current = view;\n    store.view = view;\n    notify(store);\n    setMounted(true);\n    return () => {\n      // Flush on unmount so navigating away mid-typing never drops work.\n      flushRef.current();\n      view.destroy();\n      viewRef.current = null;\n      store.view = null;\n      notify(store);\n    };\n  }, [elementsCompartment, report, store]);\n\n  // Keyed on the map's contents, not its identity: a caller passing an inline\n  // object literal would otherwise reconfigure on every render.\n  const elementsKey = JSON.stringify(elements ?? {});\n  useEffect(() => {\n    const view = viewRef.current;\n    if (!view) return;\n    view.dispatch({ effects: elementsCompartment.reconfigure(livePreview(elements)) });\n    // `elements` is tracked through elementsKey — see above.\n     \n  }, [elementsKey, elementsCompartment]);\n\n  const status = showSaveStatus && onSave && saveState !== \"idle\" ? saveState : null;\n\n  return (\n    <EditorContext.Provider value={store}>\n      <div\n        ref={ref}\n        className={cn(\"flex min-h-24 flex-col gap-3 text-base leading-7\", className)}\n        data-slot=\"editor\"\n      >\n        {children}\n        {/* The text and its save chip share a box of their own, so the chip pins\n            to the top of the TEXT — with controls above, the root's corner would\n            put it on top of the toolbar. */}\n        <div className=\"relative flex-1\">\n          {/* Covers the hydration window at the same typography as the editor, so\n              line positions hold and only the syntax marks change when CodeMirror\n              takes over. `min-h` on the root is what gives the mounted editor its\n              click target too — the theme inherits it. */}\n          {!mounted && (\n            <div aria-hidden className=\"whitespace-pre-wrap\">\n              {defaultValue || <span className=\"text-muted-foreground\">{placeholder}</span>}\n            </div>\n          )}\n          <div ref={containerRef} />\n          {status && (\n            // Pinned to the corner rather than placed after the text: it has to\n            // be in the same spot every time you glance for it, and the document\n            // is the wrong length for that. Its own ground keeps it legible over\n            // a long first line.\n            //\n            // Visual only: the announcement is the sr-only region below, which\n            // carries the SETTLED states alone. Announcing \"unsaved\" and \"saving\"\n            // too would narrate every pause in typing — and CodeMirror already\n            // has a polite region of its own inside this editor.\n            <div\n              aria-hidden\n              className=\"bg-background/90 text-muted-foreground pointer-events-none absolute top-0 right-0 flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs select-none\"\n            >\n              <span\n                aria-hidden\n                className={cn(\n                  \"size-1.5 rounded-full\",\n                  status === \"saving\" && \"bg-muted-foreground animate-pulse\",\n                  status === \"dirty\" && \"bg-muted-foreground/50\",\n                  status === \"saved\" && \"bg-muted-foreground/70\",\n                  status === \"error\" && \"bg-destructive\",\n                )}\n              />\n              <span className={cn(status === \"error\" && \"text-destructive\")}>\n                {SAVE_LABEL[status]}\n              </span>\n            </div>\n          )}\n          {onSave && (\n            <span className=\"sr-only\" aria-live=\"polite\">\n              {saveState === \"saved\" || saveState === \"error\" ? SAVE_LABEL[saveState] : \"\"}\n            </span>\n          )}\n        </div>\n      </div>\n    </EditorContext.Provider>\n  );\n});\nEditor.displayName = \"Editor\";\n",
      "type": "registry:ui",
      "target": "components/ui/editor.tsx"
    },
    {
      "path": "registry/ui/editor-controls.tsx",
      "content": "\"use client\";\n\nimport { useEffect, useRef, useState, type ComponentProps } from \"react\";\nimport { indentLess, indentMore, redo, undo } from \"@codemirror/commands\";\nimport type { EditorView } from \"@codemirror/view\";\nimport { Menu } from \"@base-ui/react/menu\";\nimport { Toolbar } from \"@base-ui/react/toolbar\";\n\nimport { useIcons, type IconComponent } from \"@/lib/icon-context\";\nimport {\n  formattingAt,\n  insertHorizontalRule,\n  insertLink,\n  setHeading,\n  toggleLinePrefix,\n  toggleWrap,\n  type Formatting,\n} from \"@/lib/live-markdown\";\nimport { cn } from \"@/lib/utils\";\nimport { Button } from \"@/components/ui/button\";\nimport { useEditorView } from \"@/components/ui/editor\";\nimport { Tooltip, TooltipProvider } from \"@/components/ui/tooltip\";\n\ntype Command = (view: EditorView) => boolean;\n\n// The keyboard shortcut is spelt for the platform the reader is on, since a\n// tooltip that says ⌘B to someone holding Ctrl is a tooltip that lies. Read\n// at render: it never appears in the server markup (tooltips open on hover).\nconst mod = () =>\n  typeof navigator !== \"undefined\" && /Mac|iPhone|iPad/.test(navigator.platform) ? \"⌘\" : \"Ctrl+\";\n\nconst STYLES: { level: 0 | 1 | 2 | 3; label: string }[] = [\n  { level: 0, label: \"Paragraph\" },\n  { level: 1, label: \"Heading 1\" },\n  { level: 2, label: \"Heading 2\" },\n  { level: 3, label: \"Heading 3\" },\n];\n\n/**\n * The formatting toolbar for `<Editor>`, rendered as its child. Every button\n * runs one of the editor's own commands — the same ones its shortcuts run —\n * and reads its pressed state from the caret, so it is a second way in, never\n * a second source of truth.\n */\nexport function EditorControls({ className, style, ...props }: ComponentProps<\"div\">) {\n  const view = useEditorView();\n  const icons = useIcons();\n  const formatting = view ? formattingAt(view.state) : null;\n  const run = (command: Command) => {\n    if (!view) return;\n    command(view);\n    view.focus();\n  };\n  const rootRef = useScrollCue();\n\n  return (\n    <TooltipProvider>\n      <Toolbar.Root\n        ref={rootRef}\n        aria-label=\"Formatting\"\n        // One row that scrolls rather than wraps: on a phone a toolbar folded\n        // into three rows eats the screen the text needed, and a sideways\n        // strip is what the platform's own editors do. The scrollbar is\n        // hidden because the strip is a control, not a document — inline,\n        // so a host stylesheet's own `scrollbar-width` on `*` cannot win.\n        // With the scrollbar gone the only thing left to say there is more\n        // toolbar is the fade — see `useScrollCue` for when it is on.\n        className={cn(\n          \"flex items-center overflow-x-auto py-0.5 [&::-webkit-scrollbar]:hidden\",\n          \"data-[overflow]:[mask-image:linear-gradient(to_right,black_calc(100%-24px),transparent)]\",\n          className,\n        )}\n        style={{ scrollbarWidth: \"none\", ...style }}\n        {...props}\n      >\n        <Group>\n          <Control icon={icons.undo} label=\"Undo\" keys=\"Z\" disabled={!formatting?.canUndo} onRun={() => run(undo)} />\n          <Control icon={icons.redo} label=\"Redo\" keys=\"⇧Z\" disabled={!formatting?.canRedo} onRun={() => run(redo)} />\n        </Group>\n        <Separator />\n        <Group>\n          <StyleMenu heading={formatting?.heading ?? 0} view={view} />\n        </Group>\n        <Separator />\n        <Group>\n          <Control icon={icons.bold} label=\"Bold\" keys=\"B\" pressed={formatting?.strong} onRun={() => run(toggleWrap(\"**\"))} />\n          <Control icon={icons.italic} label=\"Italic\" keys=\"I\" pressed={formatting?.em} onRun={() => run(toggleWrap(\"*\"))} />\n          <Control icon={icons.strikethrough} label=\"Strikethrough\" keys=\"⇧X\" pressed={formatting?.del} onRun={() => run(toggleWrap(\"~~\"))} />\n          <Control icon={icons.code} label=\"Code\" keys=\"E\" pressed={formatting?.code} onRun={() => run(toggleWrap(\"`\"))} />\n        </Group>\n        <Separator />\n        <Group>\n          <Control icon={icons.link} label=\"Link\" keys=\"K\" pressed={formatting?.link} onRun={() => run(insertLink())} />\n          <Control icon={icons.image} label=\"Image\" onRun={() => run(insertLink(true))} />\n          <Control icon={icons.minus} label=\"Horizontal rule\" onRun={() => run(insertHorizontalRule)} />\n        </Group>\n        <Separator />\n        {/* The four that rewrite the head of the line, together: each swaps\n            the marker the others wrote, so a quote sits with the lists. */}\n        <Group>\n          <Control icon={icons.list} label=\"Bullet list\" pressed={formatting?.line === \"bullet\"} onRun={() => run(toggleLinePrefix(\"bullet\"))} />\n          <Control icon={icons[\"list-ordered\"]} label=\"Numbered list\" pressed={formatting?.line === \"ordered\"} onRun={() => run(toggleLinePrefix(\"ordered\"))} />\n          <Control icon={icons[\"list-todo\"]} label=\"Task list\" keys=\"L\" pressed={formatting?.line === \"task\"} onRun={() => run(toggleLinePrefix(\"task\"))} />\n          <Control icon={icons[\"text-quote\"]} label=\"Quote\" pressed={formatting?.line === \"quote\"} onRun={() => run(toggleLinePrefix(\"quote\"))} />\n        </Group>\n        <Separator />\n        {/* Tab and Shift+Tab on a keyboard; on a phone these two are the only\n            way to nest a bullet. */}\n        <Group>\n          {/* Off on the first row of a list: there is no sibling above to nest\n              under, and indenting it anyway turns the marker into literal text. */}\n          <Control icon={icons[\"indent-increase\"]} label=\"Indent\" keys=\"]\" disabled={!formatting?.canIndent} onRun={() => run(indentMore)} />\n          <Control icon={icons[\"indent-decrease\"]} label=\"Outdent\" keys=\"[\" disabled={!formatting?.canOutdent} onRun={() => run(indentLess)} />\n        </Group>\n      </Toolbar.Root>\n    </TooltipProvider>\n  );\n}\n\n/** Marks the row `data-overflow` while there is toolbar past its right edge,\n *  which is what the fade hangs off. Dropped at the end of the scroll, so the\n *  cue only ever points at something there is more of. */\nfunction useScrollCue() {\n  const ref = useRef<HTMLDivElement | null>(null);\n  useEffect(() => {\n    const root = ref.current;\n    if (!root) return;\n    const update = () =>\n      root.toggleAttribute(\"data-overflow\", root.scrollWidth - root.clientWidth - root.scrollLeft > 1);\n    update();\n    const observer = new ResizeObserver(update);\n    observer.observe(root);\n    root.addEventListener(\"scroll\", update, { passive: true });\n    return () => {\n      observer.disconnect();\n      root.removeEventListener(\"scroll\", update);\n    };\n  }, []);\n  return ref;\n}\n\nfunction Group({ children }: { children: React.ReactNode }) {\n  return <Toolbar.Group className=\"flex shrink-0 items-center\">{children}</Toolbar.Group>;\n}\n\nfunction Separator() {\n  return <Toolbar.Separator className=\"mx-1 h-5 w-px shrink-0 bg-border\" />;\n}\n\ninterface ControlProps {\n  icon: IconComponent;\n  label: string;\n  /** The key after the modifier, for the tooltip. */\n  keys?: string;\n  pressed?: boolean;\n  disabled?: boolean;\n  onRun: () => void;\n}\n\nfunction Control({ icon: Icon, label, keys, pressed = false, disabled = false, onRun }: ControlProps) {\n  return (\n    <Tooltip content={keys ? `${label} ${mod()}${keys}` : label}>\n      <Toolbar.Button\n        disabled={disabled}\n        // A control must not take the focus it is about to act on: the click\n        // lands with the caret still in the text, and the selection it wraps\n        // is the one the reader made.\n        onMouseDown={(event) => event.preventDefault()}\n        onClick={onRun}\n        render={\n          <Button\n            variant=\"ghost\"\n            size=\"icon-compact\"\n            active={pressed}\n            aria-label={label}\n            aria-pressed={pressed}\n            // `data-disabled`, not `:disabled`: a toolbar item stays focusable\n            // when it is off, so Base UI never sets the native attribute and\n            // the button's own `disabled:` classes never fire — Undo with\n            // nothing to undo was drawn exactly like Undo with something.\n            // 44px under a fingertip (WCAG 2.2), the dense 28px under a mouse.\n            className=\"data-[disabled]:opacity-30 data-[disabled]:hover:text-muted-foreground pointer-coarse:size-11\"\n          >\n            <Icon />\n          </Button>\n        }\n      />\n    </Tooltip>\n  );\n}\n\nfunction StyleMenu({ heading, view }: { heading: Formatting[\"heading\"]; view: EditorView | null }) {\n  const [open, setOpen] = useState(false);\n  const icons = useIcons();\n  return (\n    <Menu.Root open={open} onOpenChange={setOpen}>\n      <Toolbar.Button\n        render={\n          <Menu.Trigger\n            render={\n              <Button\n                variant=\"ghost\"\n                size=\"compact\"\n                trailingIcon={icons[\"chevron-down\"]}\n                active={open}\n                className=\"pointer-coarse:h-11\"\n              >\n                Style\n              </Button>\n            }\n          />\n        }\n      />\n      <Menu.Portal>\n        <Menu.Positioner sideOffset={6} align=\"start\" className=\"z-50\">\n          <Menu.Popup\n            // Back to the text on close, not the trigger: the reader picked a\n            // style in order to keep writing. This is the ONLY thing that may\n            // take focus here — see the note on onValueChange below.\n            finalFocus={() => view?.contentDOM ?? null}\n            className={cn(\n              \"min-w-40 rounded-[var(--radius-bg,var(--radius,0.5rem))] bg-popover p-1 text-popover-foreground\",\n              \"shadow-[0_0_0_1px_var(--border),0_8px_24px_-8px_rgb(0_0_0/0.25)]\",\n              \"origin-(--transform-origin) transition-[opacity,scale] duration-(--motion-moderate) ease-spring\",\n              \"data-[ending-style]:scale-95 data-[ending-style]:opacity-0 data-[ending-style]:duration-(--motion-moderate-exit)\",\n              \"data-[starting-style]:scale-95 data-[starting-style]:opacity-0\",\n            )}\n          >\n            <Menu.RadioGroup\n              value={heading}\n              // Runs the command WITHOUT focusing the editor, unlike every\n              // other control here. Focusing mid-close moves focus out of the\n              // open popup, which Base UI reads as a focus-out: it suppresses\n              // its own return-focus and re-closes, so `finalFocus` never runs\n              // and the caret is left on <body>. The popup hands focus back.\n              onValueChange={(level) => view && setHeading(level)(view)}\n            >\n              {STYLES.map(({ level, label }) => (\n                <Menu.RadioItem\n                  key={level}\n                  value={level}\n                  closeOnClick\n                  className={cn(\n                    \"flex cursor-default items-center justify-between gap-6 rounded-[calc(var(--radius-bg,var(--radius,0.5rem))-4px)] px-2 py-1.5 text-[13px] outline-none select-none\",\n                    \"data-[highlighted]:bg-hover\",\n                    level === 1 && \"text-base font-semibold\",\n                    level === 2 && \"text-[15px] font-semibold\",\n                    level === 3 && \"font-semibold\",\n                  )}\n                >\n                  {label}\n                  <Menu.RadioItemIndicator render={<icons.check size={14} className=\"size-3.5\" />} />\n                </Menu.RadioItem>\n              ))}\n            </Menu.RadioGroup>\n          </Menu.Popup>\n        </Menu.Positioner>\n      </Menu.Portal>\n    </Menu.Root>\n  );\n}\n",
      "type": "registry:ui",
      "target": "components/ui/editor-controls.tsx"
    },
    {
      "path": "registry/lib/live-markdown.ts",
      "content": "// CodeMirror 6 extension set behind <Editor>: one always-on surface that is\n// both the view and the editor. Markdown renders in place and the raw syntax\n// reveals only where the caret is, Obsidian-style. Pure CM6 — no React — so\n// the decoration logic stays headlessly testable.\n//\n// Type and colour are NOT in here. Every decoration reads an `EditorElements`\n// map, which is this editor's answer to an MDX components map: the same keys,\n// each saying which ELEMENT the construct renders as and which classes it\n// carries. It cannot be a map of React components, because these ranges are\n// live editable text — a `<strong>` here wraps the very characters the caret\n// is moving through, so it has to be a tag CodeMirror can mark text with, not\n// a node handed to a renderer. Emitting the real tags is what makes an\n// existing prose stylesheet apply to the editor without being restated.\n//\n// The theme below holds only what must not vary — padding, caret, selection,\n// list indent, and the box model of those tags (see the reset in it).\n\nimport {\n  defaultKeymap,\n  history,\n  historyKeymap,\n  indentWithTab,\n  redoDepth,\n  undoDepth,\n} from \"@codemirror/commands\";\nimport {\n  deleteMarkupBackward,\n  insertNewlineContinueMarkupCommand,\n  markdownLanguage,\n  pasteURLAsLink,\n} from \"@codemirror/lang-markdown\";\nimport { Language, indentUnit, syntaxTree } from \"@codemirror/language\";\nimport {\n  Decoration,\n  EditorView,\n  ViewPlugin,\n  WidgetType,\n  drawSelection,\n  keymap,\n  placeholder as cmPlaceholder,\n  type DecorationSet,\n  type KeyBinding,\n  type ViewUpdate,\n} from \"@codemirror/view\";\nimport {\n  EditorSelection,\n  StateEffect,\n  StateField,\n  type EditorState,\n  type Extension,\n  type Range,\n  type StateCommand,\n} from \"@codemirror/state\";\nimport type { SyntaxNode } from \"@lezer/common\";\nimport type { MarkdownParser } from \"@lezer/markdown\";\n\n/** What one construct renders as: a class string, or an element and its\n *  classes. `{ tag: \"strong\", className: \"font-semibold\" }` emits\n *  `<strong class=\"font-semibold\">` around the live text. */\nexport type EditorElement = string | { tag?: string; className?: string };\n\n/** The editor's element map. Keys are the HTML elements an MDX components map\n *  uses, plus the three constructs markdown has and HTML doesn't. Anything\n *  omitted falls back to `defaultElements`. */\nexport interface EditorElements {\n  h1?: EditorElement;\n  h2?: EditorElement;\n  h3?: EditorElement;\n  h4?: EditorElement;\n  h5?: EditorElement;\n  h6?: EditorElement;\n  strong?: EditorElement;\n  em?: EditorElement;\n  del?: EditorElement;\n  code?: EditorElement;\n  a?: EditorElement;\n  /** The whole list row. The indent itself is structural and always applied. */\n  li?: EditorElement;\n  /** The whole quoted row. The rule down its left edge is structural. */\n  blockquote?: EditorElement;\n  /** The `<hr>` standing in for `---` once the caret has left its line. */\n  hr?: EditorElement;\n  /** The • / ◦ glyph standing in for a `-` marker. */\n  bullet?: EditorElement;\n  /** The real `<input type=\"checkbox\">` standing in for `[ ]` / `[x]`. */\n  checkbox?: EditorElement;\n  /** The text of a checked task row. */\n  taskDone?: EditorElement;\n}\n\n// Tailwind utilities and the matching tag, so semantics come for free (a\n// screen reader meets a real heading, not a div) and a consumer's own element\n// CSS lands on the right thing. Colours are tokens, which flip on `.dark`, so\n// one set covers both modes and installing the editor needs no stylesheet.\n//\n// The three keys with no tag are the ones where an element would be a lie: a\n// list ROW is a `.cm-line` div (CodeMirror owns it), and an `<li>` outside a\n// list, or a `<del>` around half a line, is worse markup than a class.\nexport const defaultElements: Required<Record<keyof EditorElements, { tag?: string; className: string }>> = {\n  h1: { tag: \"h1\", className: \"text-2xl font-semibold\" },\n  h2: { tag: \"h2\", className: \"text-xl font-semibold\" },\n  h3: { tag: \"h3\", className: \"text-lg font-semibold\" },\n  h4: { tag: \"h4\", className: \"font-semibold\" },\n  h5: { tag: \"h5\", className: \"font-semibold\" },\n  h6: { tag: \"h6\", className: \"font-semibold\" },\n  strong: { tag: \"strong\", className: \"font-semibold\" },\n  em: { tag: \"em\", className: \"italic\" },\n  del: { tag: \"del\", className: \"line-through\" },\n  code: { tag: \"code\", className: \"font-mono text-sm bg-muted rounded px-1\" },\n  a: { tag: \"a\", className: \"underline underline-offset-2 decoration-muted-foreground\" },\n  li: { className: \"\" },\n  blockquote: { className: \"text-muted-foreground\" },\n  hr: { className: \"border-border\" },\n  bullet: { className: \"text-muted-foreground\" },\n  checkbox: { className: \"size-3.5 pointer-coarse:size-[18px] accent-[var(--primary)] cursor-pointer\" },\n  taskDone: { className: \"text-muted-foreground line-through\" },\n};\n\nfunction resolve(\n  elements: EditorElements | undefined,\n  key: keyof EditorElements,\n): { tag?: string; className: string } {\n  const value = elements?.[key];\n  if (value === undefined) return defaultElements[key];\n  if (typeof value === \"string\") return { tag: defaultElements[key].tag, className: value };\n  return { tag: value.tag, className: value.className ?? \"\" };\n}\n\n// Chromeless and type-free: the editor inherits the font, size and leading of\n// whatever it is mounted in, and every colour reads a token. `min-height`\n// inherits so one `min-h-*` on the wrapper sizes both the editor's click\n// target and the pre-hydration fallback.\nconst chromelessTheme = EditorView.theme({\n  \"&\": { backgroundColor: \"transparent\", fontSize: \"inherit\" },\n  \"&.cm-focused\": { outline: \"none\" },\n  \".cm-scroller\": {\n    fontFamily: \"inherit\",\n    lineHeight: \"inherit\",\n    overflow: \"visible\", // the page scrolls, not the editor\n  },\n  \".cm-content\": {\n    padding: \"0\",\n    minHeight: \"inherit\",\n    caretColor: \"var(--foreground)\",\n    // Kill the 300ms double-tap-zoom wait and the grey flash a tap leaves on\n    // mobile WebKit. Neither affects long-press selection or double-tap word\n    // select — those are selection gestures, not browser zoom gestures.\n    touchAction: \"manipulation\",\n    WebkitTapHighlightColor: \"transparent\",\n  },\n  \".cm-line\": { padding: \"0\" },\n  // The emitted tags (h1…h6, strong, code, a) sit INSIDE a line div, and a\n  // source editor's vertical rhythm is its blank lines, not element margins:\n  // a heading that brought `margin: 1rem 0` with it would push the caret off\n  // its own text. Type, weight and colour still come through from whatever\n  // styles the tag — only the box model is pinned.\n  \".cm-line :is(h1,h2,h3,h4,h5,h6,p,blockquote)\": {\n    display: \"inline\",\n    margin: \"0\",\n    padding: \"0\",\n  },\n  // List rows read as a block. Structural, and applied regardless of caret\n  // position — layout must never toggle as the caret moves.\n  \".cm-line.cm-md-li\": { paddingLeft: \"0.5rem\" },\n  // A quoted row reads as a block the same way: the rule is structural and\n  // stays put as the caret moves; what the element map adds is colour.\n  \".cm-line.cm-md-quote\": {\n    paddingLeft: \"0.75rem\",\n    boxShadow: \"inset 2px 0 0 var(--border)\",\n  },\n  // Hanging indent: a wrapped line continues under its own text, not back\n  // at the left edge. `--hang` is the measured width of what precedes the\n  // text — leading spaces, and a bullet or checkbox plus its space — set per\n  // line by the preview (see hangMetrics). Padding pushes every row of the\n  // line in by that much and the negative text-indent pulls only the first\n  // row back out, so the marker still sits flush.\n  \".cm-line.cm-md-hang\": {\n    paddingLeft: \"var(--hang)\",\n    textIndent: \"calc(var(--hang) * -1)\",\n  },\n  \".cm-line.cm-md-li.cm-md-hang\": { paddingLeft: \"calc(0.5rem + var(--hang))\" },\n  // One marker column for every list kind. The bullet glyph, the checkbox and\n  // an ordered row's `1.` each centre in a box `--marker-w` wide — the widest\n  // of the three, measured and set per line beside `--hang` — so the markers\n  // share a centre axis and the text after them starts at the same x. The\n  // column stops at the marker: the space that follows it is document text on\n  // all three, so it lines them up too. `text-indent: 0` because the hanging\n  // indent's negative indent inherits into these boxes and would drag the\n  // marker out of the column. The `auto` fallback is what the metric probes\n  // measure against, before any `--marker-w` exists. A minimum, not a width:\n  // the number is text, and a `10.` wider than the column must spill past\n  // it rather than wrap inside its own box.\n  \".cm-md-bullet, .cm-md-check, .cm-md-num\": {\n    display: \"inline-block\",\n    minWidth: \"var(--marker-w, auto)\",\n    textAlign: \"center\",\n    textIndent: \"0\",\n    whiteSpace: \"nowrap\",\n  },\n  // The checkbox wrapper. Sizing the box is the element map's job; this only\n  // sits it on the text baseline, and `display: block` on the input keeps the\n  // wrapper's baseline at its bottom edge rather than on a line box that\n  // shifts with the box's size. `content-box` so the coarse-pointer padding\n  // below grows OUTSIDE the column and the input stays on the column's centre.\n  \".cm-md-check\": { verticalAlign: \"-0.09375rem\", boxSizing: \"content-box\" },\n  // The rule fills its line and sits on the text's midline, so the row keeps\n  // the height of the `---` it replaces and the caret lands beside it.\n  \".cm-md-hr\": {\n    display: \"inline-block\",\n    width: \"100%\",\n    margin: \"0\",\n    verticalAlign: \"middle\",\n    borderWidth: \"1px 0 0\",\n    borderStyle: \"solid\",\n  },\n  // Centred in the column, not flush against its left edge.\n  \".cm-md-check > input\": { display: \"block\", marginInline: \"auto\" },\n  \".cm-cursor\": { borderLeftColor: \"var(--foreground)\" },\n  // drawSelection() replaces the native selection and caret (the native caret\n  // spans the full line box and reads oversized); its layers need explicit\n  // colours.\n  \".cm-selectionBackground\": {\n    backgroundColor: \"color-mix(in oklab, var(--foreground) 12%, transparent)\",\n  },\n  \"&.cm-focused .cm-selectionBackground\": {\n    backgroundColor: \"color-mix(in oklab, var(--focus-ring, #6B97FF) 30%, transparent)\",\n  },\n  \".cm-placeholder\": { color: \"var(--muted-foreground)\" },\n\n  // --- Touch ---------------------------------------------------------------\n  \"@media (pointer: coarse)\": {\n    // iOS zooms the page when an editable field under 16px takes focus, and\n    // leaves the user zoomed in with no way back. A floor, not a size: a\n    // surface already larger than 16px keeps whatever it inherited.\n    \".cm-content\": { fontSize: \"max(1rem, 1em)\" },\n    // WCAG 2.2 target size (24×24 minimum) — a 14px checkbox is a coin toss\n    // with a fingertip. The HIT AREA grows, not the box: padding takes the\n    // label past 24px in both axes and an equal negative margin gives the\n    // space straight back, so the line keeps its height and the text keeps\n    // its distance. Sizing the box itself to 24px is what made it tower over\n    // 16px type with the sentence jammed against it.\n    \".cm-md-check\": { padding: \"0.375rem\", margin: \"-0.375rem\" },\n  },\n});\n\n/** True on a device whose primary input is a finger. Read once, at mount —\n *  extensions are built there and a pointer type does not change mid-session\n *  in any way worth rebuilding an editor over. */\nfunction isTouchDevice(): boolean {\n  return typeof window !== \"undefined\" && window.matchMedia?.(\"(pointer: coarse)\").matches === true;\n}\n\n/** How much of the window the on-screen keyboard is covering.\n *\n *  iOS and Android open the keyboard OVER the page: the layout viewport keeps\n *  its height and only the visual viewport shrinks, so nothing in CSS knows\n *  the bottom of the window is gone. */\nfunction keyboardInset(): number {\n  const viewport = typeof window !== \"undefined\" ? window.visualViewport : null;\n  if (!viewport) return 0;\n  return Math.max(0, window.innerHeight - viewport.height - viewport.offsetTop);\n}\n\n// Both halves of keeping the caret off the keyboard: tell CodeMirror how much\n// of the window is obscured whenever it scrolls the selection into view, and\n// re-run that scroll when the keyboard opens, closes or changes height (a\n// suggestion strip appearing is a resize too). Without the second half, the\n// keyboard opens over the line you just tapped and nothing moves.\nconst keyboardAware: Extension = [\n  EditorView.scrollMargins.of(() => {\n    const inset = keyboardInset();\n    return inset > 0 ? { bottom: inset + 16 } : null;\n  }),\n  ViewPlugin.fromClass(\n    class {\n      constructor(readonly view: EditorView) {\n        window.visualViewport?.addEventListener(\"resize\", this.onViewportResize);\n      }\n      // A frame later: iOS reports the resize while the keyboard is still\n      // sliding, and scrolling into a viewport that is still moving lands\n      // short of where it settles.\n      onViewportResize = () => {\n        if (!this.view.hasFocus) return;\n        requestAnimationFrame(() => {\n          if (!this.view.hasFocus) return;\n          this.view.dispatch({\n            effects: EditorView.scrollIntoView(this.view.state.selection.main.head),\n          });\n        });\n      };\n      destroy() {\n        window.visualViewport?.removeEventListener(\"resize\", this.onViewportResize);\n      }\n    },\n  ),\n];\n\n/* ------------------------------------------------------------------\n * Formatting shortcuts\n * ------------------------------------------------------------------ */\n\n/** Toggle an inline marker pair (** / * / ~~ / `) around each selection range.\n *  Empty selections get an empty pair with the caret inside; a second\n *  invocation right away (or on an already-wrapped selection) unwraps. */\nexport function toggleWrap(marker: string): StateCommand {\n  return ({ state, dispatch }) => {\n    const len = marker.length;\n    const char = marker[0];\n    // The full run of `char` touching a position, not just one marker's\n    // width of it — `*` and `**` share a character, so telling italic from\n    // bold needs the WHOLE run outside the range, not just its last `len`\n    // characters (which is what let toggling italic on a bold word strip\n    // one star off each side instead of adding a third).\n    const runBefore = (pos: number) => {\n      let n = 0;\n      while (pos - n > 0 && state.sliceDoc(pos - n - 1, pos - n) === char) n++;\n      return n;\n    };\n    const runAfter = (pos: number) => {\n      let n = 0;\n      while (pos + n < state.doc.length && state.sliceDoc(pos + n, pos + n + 1) === char) n++;\n      return n;\n    };\n    const changes = state.changeByRange((range) => {\n      const { from, to } = range;\n      // Markers just outside the range (also the caret-between-markers\n      // case). `*` only counts as already-applied when the run on both\n      // sides is odd — an even run is a `**` pair, not `*` plus leftover —\n      // every other marker has no such overlap, so any run at least its own\n      // length counts.\n      const before = runBefore(from);\n      const after = runAfter(to);\n      const wrapped = marker === \"*\" ? before % 2 === 1 && after % 2 === 1 : before >= len && after >= len;\n      if (wrapped) {\n        return {\n          changes: [\n            { from: from - len, to: from },\n            { from: to, to: to + len },\n          ],\n          range: EditorSelection.range(from - len, to - len),\n        };\n      }\n      // Markers included at the edges of the selection.\n      const inner = state.sliceDoc(from, to);\n      if (inner.length >= 2 * len && inner.startsWith(marker) && inner.endsWith(marker)) {\n        return {\n          changes: [\n            { from, to: from + len },\n            { from: to - len, to },\n          ],\n          range: EditorSelection.range(from, to - 2 * len),\n        };\n      }\n      // Caret sitting right before this marker's own closer (typed content\n      // in between, so `wrapped` above missed it) — step past it instead of\n      // opening a second, empty pair right next to the first.\n      if (\n        range.empty &&\n        state.sliceDoc(to, to + len) === marker &&\n        state.sliceDoc(to + len, to + len + 1) !== char &&\n        state.sliceDoc(to - len, to) !== marker\n      ) {\n        return { range: EditorSelection.cursor(to + len) };\n      }\n      return {\n        changes: [\n          { from, insert: marker },\n          { from: to, insert: marker },\n        ],\n        range: EditorSelection.range(from + len, to + len),\n      };\n    });\n    dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"input\" }));\n    return true;\n  };\n}\n\n/** The block constructs a line can open with. Exactly one applies per line:\n *  the outermost marker, so a `> - item` row is a quote here. */\nexport type LinePrefix = \"quote\" | \"task\" | \"bullet\" | \"ordered\";\n\n// Indent, then the marker with its space. The task pattern comes before the\n// bullet it extends. The heading marker is deliberately absent: a heading and\n// a list marker never share a row, and `setHeading` handles it on its own.\nconst LINE_PREFIX = /^(\\s*)(?:(> )|(- \\[[ xX]\\] )|([-*+] )|(\\d+[.)] ))?/;\n\n/** What a line opens with, and how far it reaches into the text. */\nexport function linePrefixOf(text: string): { indent: number; kind: LinePrefix | null; end: number } {\n  const m = LINE_PREFIX.exec(text)!;\n  const kind = m[2] ? \"quote\" : m[3] ? \"task\" : m[4] ? \"bullet\" : m[5] ? \"ordered\" : null;\n  return { indent: m[1].length, kind, end: m[0].length };\n}\n\n/** Every line the selection touches, once, in document order. */\nfunction selectedLines(state: EditorState) {\n  const seen = new Set<number>();\n  const lines = [];\n  for (const range of state.selection.ranges) {\n    const last = state.doc.lineAt(range.to).number;\n    for (let n = state.doc.lineAt(range.from).number; n <= last; n++) {\n      if (seen.has(n)) continue;\n      seen.add(n);\n      lines.push(state.doc.line(n));\n    }\n  }\n  return lines;\n}\n\n/** Apply a per-line prefix rewrite, keeping the caret after whatever was\n *  inserted in front of it. Without `assoc: 1` the default mapping leaves it\n *  before a fresh \"- [ ] \", visually hidden behind the checkbox. */\nfunction rewriteLines(\n  { state, dispatch }: Parameters<StateCommand>[0],\n  rewrite: (line: { from: number; text: string }, index: number) => { from: number; to?: number; insert?: string } | null,\n): boolean {\n  const changes = selectedLines(state)\n    .map((line, i) => rewrite(line, i))\n    .filter((c) => c !== null);\n  if (changes.length === 0) return false;\n  const changeSet = state.changes(changes);\n  dispatch(\n    state.update({\n      changes: changeSet,\n      selection: state.selection.map(changeSet, 1),\n      userEvent: \"input\",\n    }),\n  );\n  return true;\n}\n\n/** Toggle a block prefix on every selected line: a line already carrying\n *  `kind` loses it, one carrying another marker swaps, a plain line gains it.\n *  So Cmd+L on a bullet turns it into a task and again into plain text. */\nexport function toggleLinePrefix(kind: LinePrefix): StateCommand {\n  return (target) =>\n    rewriteLines(target, (line, i) => {\n      const { indent, kind: current, end } = linePrefixOf(line.text);\n      const from = line.from + indent;\n      if (current === kind) return { from, to: line.from + end };\n      const marker =\n        kind === \"quote\" ? \"> \" : kind === \"task\" ? \"- [ ] \" : kind === \"bullet\" ? \"- \" : `${i + 1}. `;\n      return { from, to: line.from + end, insert: marker };\n    });\n}\n\nconst HEADING = /^(#{1,6}) /;\n\n/** Set the heading level of every selected line — 0 is a paragraph. A line\n *  already at that level is left alone rather than toggled, so a menu that\n *  re-selects \"Heading 2\" is a no-op, not a demotion. */\nexport function setHeading(level: 0 | 1 | 2 | 3 | 4 | 5 | 6): StateCommand {\n  return (target) =>\n    rewriteLines(target, (line) => {\n      const current = HEADING.exec(line.text);\n      const currentLevel = current ? current[1].length : 0;\n      if (currentLevel === level) return null;\n      const insert = level ? \"#\".repeat(level) + \" \" : \"\";\n      return { from: line.from, to: line.from + (current?.[0].length ?? 0), insert };\n    });\n}\n\n/** Wrap each range as `[text](url)` — or `![text](url)` for an image — and\n *  leave the placeholder URL selected, so typing replaces it. An empty range\n *  gets a placeholder label too. The image form is written raw: rendering an\n *  image is the `extensions` seam's job, not the text surface's. */\nexport function insertLink(image = false): StateCommand {\n  return ({ state, dispatch }) => {\n    const open = image ? \"![\" : \"[\";\n    const changes = state.changeByRange((range) => {\n      const label = state.sliceDoc(range.from, range.to) || (image ? \"alt\" : \"link\");\n      const insert = `${open}${label}](url)`;\n      const urlFrom = range.from + open.length + label.length + 2;\n      return {\n        changes: { from: range.from, to: range.to, insert },\n        range: EditorSelection.range(urlFrom, urlFrom + 3),\n      };\n    });\n    dispatch(state.update(changes, { scrollIntoView: true, userEvent: \"input\" }));\n    return true;\n  };\n}\n\n/** Put a `---` on a line of its own after the caret's line, and the caret on\n *  a fresh line under it. The blank line before it is not optional: markdown\n *  reads `text` directly over `---` as a setext heading, not a rule. */\nexport const insertHorizontalRule: StateCommand = ({ state, dispatch }) => {\n  const line = state.doc.lineAt(state.selection.main.head);\n  const previousHasText = line.number > 1 && state.doc.line(line.number - 1).length > 0;\n  const lead = line.length > 0 ? \"\\n\\n\" : previousHasText ? \"\\n\" : \"\";\n  const insert = `${lead}---\\n`;\n  dispatch(\n    state.update({\n      changes: { from: line.to, insert },\n      selection: { anchor: line.to + insert.length },\n      scrollIntoView: true,\n      userEvent: \"input\",\n    }),\n  );\n  return true;\n};\n\n/** What is in force at the caret, for a toolbar's pressed states. Inline\n *  constructs come from the syntax tree (so only closed ones count, which is\n *  also what the eager styling of an unclosed `**` would mislead about); the\n *  block state is read off the line the same way the commands write it. */\nexport interface Formatting {\n  heading: 0 | 1 | 2 | 3 | 4 | 5 | 6;\n  line: LinePrefix | null;\n  strong: boolean;\n  em: boolean;\n  del: boolean;\n  code: boolean;\n  link: boolean;\n  canUndo: boolean;\n  canRedo: boolean;\n  /** Whether the caret's line can take another indent step. */\n  canIndent: boolean;\n  /** Whether the caret's line has an indent to give back. */\n  canOutdent: boolean;\n}\n\nconst LIST_KINDS: LinePrefix[] = [\"bullet\", \"task\", \"ordered\"];\n\n/** A list row nests under the row above it, so the FIRST item of a list has\n *  nothing to nest under: indenting it writes `    - a`, which markdown reads\n *  as a paragraph continuation of the item before, not a nested list — the\n *  marker comes back as a literal `-`. A plain line has no such constraint. */\nfunction canIndentLine(state: EditorState, line: { number: number; text: string }): boolean {\n  const { indent, kind } = linePrefixOf(line.text);\n  if (!kind || !LIST_KINDS.includes(kind)) return true;\n  for (let n = line.number - 1; n >= 1; n--) {\n    const previous = state.doc.line(n);\n    if (previous.text.trim() === \"\") continue;\n    const above = linePrefixOf(previous.text);\n    // Same indent is the previous sibling; deeper is a child of it, and its\n    // own parent is then a sibling of ours.\n    return above.kind !== null && LIST_KINDS.includes(above.kind) && above.indent >= indent;\n  }\n  return false;\n}\n\nconst INLINE_NODES: Record<string, \"strong\" | \"em\" | \"del\" | \"code\" | \"link\"> = {\n  StrongEmphasis: \"strong\",\n  Emphasis: \"em\",\n  Strikethrough: \"del\",\n  InlineCode: \"code\",\n  Link: \"link\",\n  Image: \"link\",\n};\n\nexport function formattingAt(state: EditorState): Formatting {\n  const head = state.selection.main.head;\n  const line = state.doc.lineAt(head);\n  const formatting: Formatting = {\n    heading: (HEADING.exec(line.text)?.[1].length ?? 0) as Formatting[\"heading\"],\n    line: linePrefixOf(line.text).kind,\n    strong: false,\n    em: false,\n    del: false,\n    code: false,\n    link: false,\n    canUndo: undoDepth(state) > 0,\n    canRedo: redoDepth(state) > 0,\n    canIndent: canIndentLine(state, line),\n    canOutdent: linePrefixOf(line.text).indent > 0,\n  };\n  // Side -1 so a caret sitting just past `**bold**|` still reads as bold,\n  // which is where it lands the moment the closing marks are typed.\n  for (let node: SyntaxNode | null = syntaxTree(state).resolveInner(head, -1); node; node = node.parent) {\n    const key = INLINE_NODES[node.name];\n    if (key) formatting[key] = true;\n  }\n  return formatting;\n}\n\nconst EMPTY_QUOTE = /^\\s*(> ?)+$/;\n\n/** Enter on a row that is only a quote marker leaves the quote — and leaves\n *  a BLANK line behind it. Clearing the marker in place is not enough: in\n *  CommonMark the next sentence typed directly under a quote is a lazy\n *  continuation of it, and the rule carries on down the left edge.\n *\n *  Lists are left to CodeMirror, which clears the marker and stays on the\n *  row: the glyph goes and the caret does not move, which is what a second\n *  Enter feels like it should do. A sentence typed there is a continuation\n *  of the item in markdown terms, but nothing on the surface says so, so the\n *  extra row would only read as a jump. `> > ` leaves the whole nesting at\n *  once, as it always has. */\nconst exitEmptyQuote: StateCommand = ({ state, dispatch }) => {\n  const { main } = state.selection;\n  if (!main.empty) return false;\n  const line = state.doc.lineAt(main.head);\n  if (!EMPTY_QUOTE.test(line.text)) return false;\n  dispatch(state.update({ changes: { from: line.from, to: line.to, insert: \"\\n\" }, userEvent: \"input\" }));\n  return true;\n};\n\n/** Home on a row that opens with a marker goes to the start of the TEXT. The\n *  marker is chrome — a bullet glyph or a checkbox — and landing in front of\n *  it is never what was meant; returning false at the text start hands the\n *  second press to the stock command, which is the row start. */\nconst cursorTextStart: StateCommand = ({ state, dispatch }) => {\n  const { main } = state.selection;\n  const line = state.doc.lineAt(main.head);\n  const { indent, end } = linePrefixOf(line.text);\n  if (end === indent || main.head <= line.from + end) return false;\n  dispatch(state.update({ selection: { anchor: line.from + end }, scrollIntoView: true }));\n  return true;\n};\n\n/** Enter at the start of a list item's text opens an empty item above it and\n *  keeps the caret on its own words. CodeMirror's continuation writes the new\n *  marker with NO trailing space (`-\\n- one`), and a space is what commits a\n *  block marker here — so its row came out as a bare `-`. */\nconst openItemAbove: StateCommand = ({ state, dispatch }) => {\n  const { main } = state.selection;\n  if (!main.empty) return false;\n  const line = state.doc.lineAt(main.head);\n  const { indent, kind, end } = linePrefixOf(line.text);\n  if (kind === null || kind === \"quote\") return false;\n  if (main.head !== line.from + end || line.length === end) return false;\n  const lead = line.text.slice(0, indent);\n  const marker = line.text.slice(indent, end);\n  // The row being pushed down becomes the second item, so its number moves on.\n  const next = kind === \"ordered\" ? marker.replace(/^\\d+/, (n) => String(Number(n) + 1)) : marker;\n  const insert = `${lead}${marker}\\n${lead}${next}`;\n  dispatch(\n    state.update({\n      changes: { from: line.from, to: line.from + end, insert },\n      selection: { anchor: line.from + insert.length },\n      scrollIntoView: true,\n      userEvent: \"input\",\n    }),\n  );\n  return true;\n};\n\nconst formattingKeymap: readonly KeyBinding[] = [\n  { key: \"Mod-b\", run: toggleWrap(\"**\"), preventDefault: true },\n  { key: \"Mod-i\", run: toggleWrap(\"*\"), preventDefault: true },\n  { key: \"Mod-e\", run: toggleWrap(\"`\"), preventDefault: true },\n  { key: \"Mod-Shift-x\", run: toggleWrap(\"~~\"), preventDefault: true },\n  { key: \"Mod-k\", run: insertLink(), preventDefault: true },\n  { key: \"Mod-l\", run: toggleLinePrefix(\"task\"), preventDefault: true },\n];\n\n// Escape and Cmd+Enter blur. Saving is the component's debounced autosave, so\n// blur is \"I'm done here\" — it flushes, but it isn't the commit gesture.\nconst blurKeymap: readonly KeyBinding[] = [\n  {\n    key: \"Escape\",\n    run: (view) => {\n      view.contentDOM.blur();\n      return true;\n    },\n  },\n  {\n    key: \"Mod-Enter\",\n    run: (view) => {\n      view.contentDOM.blur();\n      return true;\n    },\n  },\n];\n\n/* ------------------------------------------------------------------\n * Hanging-indent metrics\n * ------------------------------------------------------------------\n * The editor sits in a proportional prose font, so the width of the indent\n * cannot be written in `ch` — a space, a bullet glyph and the checkbox are\n * each measured once, inside `.cm-content` so they inherit its type, and\n * again when the geometry changes (a web font landing, a resize). Ordinary\n * lines never touch the DOM for this.\n */\n\ninterface HangMetrics {\n  space: number;\n  bullet: number;\n  subBullet: number;\n  checkbox: number;\n  ordered: number;\n}\n\n/** The shared marker column. Every list marker — the bullet glyph, the\n *  checkbox, an ordered row's `1.` — centres in a box this wide, so the three\n *  sit on one axis and their text starts at the same x. The widest marker\n *  wins. It tracks `1.`, not `10.`: a two-digit number spills into the space\n *  that follows it rather than widening the column for every other row, which\n *  is what most editors do. */\nfunction markerColumn(metrics: HangMetrics): number {\n  return Math.max(metrics.bullet, metrics.subBullet, metrics.checkbox, metrics.ordered);\n}\n\nconst setHangMetrics = StateEffect.define<HangMetrics>();\n\nconst hangMetrics = StateField.define<HangMetrics | null>({\n  create: () => null,\n  update(value, tr) {\n    for (const effect of tr.effects) if (effect.is(setHangMetrics)) return effect.value;\n    return value;\n  },\n});\n\nfunction measureHangMetrics(view: EditorView, marks: Marks): HangMetrics {\n  const probe = document.createElement(\"span\");\n  probe.style.cssText = \"position:absolute;visibility:hidden;white-space:pre\";\n  view.contentDOM.appendChild(probe);\n  const width = (child: Node, className = \"\") => {\n    probe.className = className;\n    probe.replaceChildren(child);\n    return probe.getBoundingClientRect().width;\n  };\n  const text = (value: string, className?: string) =>\n    width(document.createTextNode(value), className);\n  const metrics = {\n    space: text(\" \"),\n    bullet: text(\"•\", `cm-md-bullet ${marks.bullet}`),\n    subBullet: text(\"◦\", `cm-md-bullet ${marks.bullet}`),\n    // The real widget, margins and all: on touch it carries a padding the\n    // negative margin gives straight back, so only the wrapper's width is\n    // the advance the text sees.\n    checkbox: width(new CheckboxWidget(false, marks.checkbox).toDOM(view)),\n    // An ordered row's marker is the document's own text, so it is measured\n    // as text — with the widest digit, because `1` is the narrowest in a\n    // proportional face and a column cut to it wrapped `2.` inside itself.\n    // The probes see `min-width: var(--marker-w, auto)` and fall through to\n    // auto — `--marker-w` is set per line, never on the probe.\n    ordered: text(\"0.\"),\n  };\n  probe.remove();\n  return metrics;\n}\n\n// Measured off the DOM, so it goes through requestMeasure — a plugin's own\n// update() may not read layout — and lands in state through an effect, so\n// the decorations rebuild from state alone. The measure phase runs inside\n// an update, where a dispatch throws, so the effect goes out a microtask\n// later, once the cycle has closed.\nfunction hangMeasurer(marks: Marks) {\n  return ViewPlugin.fromClass(\n    class {\n      destroyed = false;\n      constructor(readonly view: EditorView) {\n        this.schedule();\n      }\n      update(update: ViewUpdate) {\n        if (update.geometryChanged) this.schedule();\n      }\n      destroy() {\n        this.destroyed = true;\n      }\n      schedule() {\n        this.view.requestMeasure({\n          read: () => measureHangMetrics(this.view, marks),\n          write: (next, view) => {\n            const current = view.state.field(hangMetrics, false);\n            if (\n              current &&\n              current.space === next.space &&\n              current.bullet === next.bullet &&\n              current.subBullet === next.subBullet &&\n              current.checkbox === next.checkbox &&\n              current.ordered === next.ordered\n            )\n              return;\n            queueMicrotask(() => {\n              if (!this.destroyed) view.dispatch({ effects: setHangMetrics.of(next) });\n            });\n          },\n        });\n      }\n    },\n  );\n}\n\n// One line decoration per distinct pair of widths, so unchanged lines compare\n// equal across rebuilds instead of being redrawn. `--marker-w` rides the same\n// decoration as `--hang`: every row that has a marker has a hanging indent, so\n// this is already the one place a per-line width reaches the markers inside.\nconst hangDecorations = new Map<string, Decoration>();\nfunction hangLine(width: number, column: number): Decoration {\n  const round = (value: number) => Math.round(value * 100) / 100;\n  const px = round(width);\n  const columnPx = round(column);\n  const key = `${px}|${columnPx}`;\n  let deco = hangDecorations.get(key);\n  if (!deco) {\n    deco = Decoration.line({\n      class: \"cm-md-hang\",\n      attributes: { style: `--hang:${px}px;--marker-w:${columnPx}px` },\n    });\n    hangDecorations.set(key, deco);\n  }\n  return deco;\n}\n\n/* ------------------------------------------------------------------\n * Live-preview decorations\n * ------------------------------------------------------------------\n * Conceal markdown syntax marks except where the selection touches the\n * construct (node-scoped reveal — never whole-line, which is where the\n * Obsidian-style jitter comes from). Heading classes are LINE decorations\n * applied unconditionally, so the line box never changes with the caret;\n * only the \"#\" marker's visibility does.\n */\n\nclass BulletWidget extends WidgetType {\n  constructor(\n    readonly glyph: string,\n    readonly className: string,\n  ) {\n    super();\n  }\n  eq(other: BulletWidget) {\n    return other.glyph === this.glyph && other.className === this.className;\n  }\n  toDOM() {\n    const span = document.createElement(\"span\");\n    span.className = `cm-md-bullet ${this.className}`;\n    span.textContent = this.glyph;\n    return span;\n  }\n}\n\nclass HrWidget extends WidgetType {\n  constructor(readonly className: string) {\n    super();\n  }\n  eq(other: HrWidget) {\n    return other.className === this.className;\n  }\n  toDOM() {\n    const hr = document.createElement(\"hr\");\n    hr.className = `cm-md-hr ${this.className}`;\n    return hr;\n  }\n}\n\nclass CheckboxWidget extends WidgetType {\n  constructor(\n    readonly checked: boolean,\n    readonly className: string,\n    /** How far past the widget's own start the `[ ]` sits: the decoration\n     *  covers the whole `- [ ]`, so its position is the ROW's, not the\n     *  marker's. */\n    readonly markerOffset = 0,\n  ) {\n    super();\n  }\n  eq(other: CheckboxWidget) {\n    return (\n      other.checked === this.checked &&\n      other.className === this.className &&\n      other.markerOffset === this.markerOffset\n    );\n  }\n  toDOM(view: EditorView) {\n    // A <label>, not a bare input: on touch the hit area has to reach past\n    // the box (see the target-size rule in the theme), and a label forwards a\n    // click on that margin to the input natively — no handler of our own.\n    const label = document.createElement(\"label\");\n    label.className = \"cm-md-check\";\n    const input = document.createElement(\"input\");\n    input.type = \"checkbox\";\n    input.checked = this.checked;\n    input.className = `cm-md-checkbox ${this.className}`;\n    input.setAttribute(\"aria-label\", this.checked ? \"Mark task not done\" : \"Mark task done\");\n    input.addEventListener(\"change\", () => {\n      // Toggle by rewriting the three characters of the marker, which sits\n      // markerOffset past where the widget starts.\n      const pos = view.posAtDOM(label) + this.markerOffset;\n      view.dispatch({\n        changes: { from: pos, to: pos + 3, insert: this.checked ? \"[ ]\" : \"[x]\" },\n      });\n    });\n    // Ticking a task is not editing. Without this the press focuses the\n    // editor it lands in, and on a phone that raises the keyboard over the\n    // list being ticked. Cancelling the press keeps focus wherever it was —\n    // the click, and so the toggle, still goes through.\n    label.addEventListener(\"mousedown\", (event) => event.preventDefault());\n    label.appendChild(input);\n    return label;\n  }\n  // Default ignoreEvent() is true: CM leaves clicks to the checkbox, so\n  // toggling doesn't move the caret.\n}\n\n// An ordered row's marker stays the document's own \"1.\" — no widget to centre\n// it, so the column class goes on the text itself. Structural only: colour and\n// type are the surrounding line's, as before.\nconst orderedMark = Decoration.mark({ class: \"cm-md-num\" });\n\ninterface Marks {\n  hide: Decoration;\n  strong: Decoration;\n  em: Decoration;\n  del: Decoration;\n  code: Decoration;\n  link: Decoration;\n  taskDone: Decoration;\n  listLine: Decoration;\n  quoteLine: Decoration;\n  hr: string;\n  headingLines: Decoration[];\n  /** Null where the heading key carries no tag — then the line class is the\n   *  whole treatment. */\n  headingTags: (Decoration | null)[];\n  bullet: string;\n  checkbox: string;\n  /** Unclosed delimiters, in match priority order. */\n  unclosed: { re: RegExp; len: number; deco: Decoration }[];\n}\n\nexport function createMarks(elements?: EditorElements): Marks {\n  const at = (key: keyof EditorElements) => resolve(elements, key);\n  const marked = (key: keyof EditorElements) => {\n    const { tag, className } = at(key);\n    // The link keeps its href off (Cmd+click is what opens it), so it says\n    // what it is with a role instead — for screen readers, and for crawlers\n    // that otherwise report a bare <a> as an uncrawlable link.\n    const attributes = tag === \"a\" ? { role: \"link\" } : undefined;\n    return Decoration.mark({ tagName: tag, class: className, attributes });\n  };\n  const strong = marked(\"strong\");\n  const em = marked(\"em\");\n  const del = marked(\"del\");\n  const code = marked(\"code\");\n  const headings = ([\"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\"] as const).map(at);\n  return {\n    hide: Decoration.replace({}),\n    strong,\n    em,\n    del,\n    code,\n    link: marked(\"a\"),\n    taskDone: marked(\"taskDone\"),\n    listLine: Decoration.line({ class: `cm-md-li ${at(\"li\").className}` }),\n    quoteLine: Decoration.line({ class: `cm-md-quote ${at(\"blockquote\").className}` }),\n    hr: at(\"hr\").className,\n    // The SIZE rides the line, not the tag: it has to apply to the whole line\n    // box or a wrapped heading's second row would come out at body size.\n    headingLines: headings.map((h) => Decoration.line({ class: h.className })),\n    headingTags: headings.map((h) => (h.tag ? Decoration.mark({ tagName: h.tag }) : null)),\n    bullet: at(\"bullet\").className,\n    checkbox: at(\"checkbox\").className,\n    // The parser only creates emphasis/code nodes for CLOSED constructs, so\n    // \"**hello\" being typed would stay plain until the closing \"**\" —\n    // headings style eagerly (no closer needed) and users expect the same\n    // here. A delimiter must be followed by a non-space (mirrors CommonMark's\n    // left-flanking rule; also keeps \"* \" list bullets out).\n    unclosed: [\n      { re: /\\*\\*(?=\\S)/, len: 2, deco: strong },\n      { re: /(?<!\\*)\\*(?=[^\\s*])/, len: 1, deco: em },\n      { re: /~~(?=\\S)/, len: 2, deco: del },\n      { re: /`(?=\\S)/, len: 1, deco: code },\n    ],\n  };\n}\n\n/** Where a task row's marker starts: at the list bullet, not at the `[`. The\n *  whole `- [ ]` is drawn as one checkbox, so that is where the decoration and\n *  the atomic range both begin. */\nfunction taskMarkerFrom(taskMarker: SyntaxNode): number {\n  return taskMarker.parent?.parent?.getChild(\"ListMark\")?.from ?? taskMarker.from;\n}\n\n/** `- [ ] ` counts as one character to the caret. The marker and the space\n *  after it render as a single checkbox, so every position inside them is\n *  invisible — arrow keys and clicks land at the row start or the text start,\n *  never in between, where Backspace used to eat the space and with it the\n *  checkbox. */\nexport function taskMarkerRanges(\n  state: EditorState,\n  visible: readonly { from: number; to: number }[],\n): DecorationSet {\n  const ranges: Range<Decoration>[] = [];\n  const tree = syntaxTree(state);\n  for (const { from, to } of visible) {\n    tree.iterate({\n      from,\n      to,\n      enter: (node) => {\n        if (node.name !== \"TaskMarker\") return;\n        const line = state.doc.lineAt(node.to);\n        ranges.push(atomicMarker.range(taskMarkerFrom(node.node), Math.min(node.to + 1, line.to)));\n      },\n    });\n  }\n  return Decoration.set(ranges, true);\n}\n\n// Never rendered — atomicRanges reads only the range bounds.\nconst atomicMarker = Decoration.replace({});\n\nconst atomicTaskMarkers = EditorView.atomicRanges.of((view) =>\n  taskMarkerRanges(view.state, view.visibleRanges),\n);\n\n/** Pure decoration computation, separated from the view for testability.\n *\n *  `hasFocus` gates the caret-reveal: an unfocused editor still HAS a\n *  selection (position 0 on load), which would otherwise keep the first\n *  construct's syntax revealed until the user clicks — everything conceals\n *  when the editor isn't focused.\n *\n *  Walks only `visible` (the viewport, plus CodeMirror's own overdraw\n *  margin) rather than the whole document — cost per keystroke must not grow\n *  with document length. */\nexport function computeLiveDecorations(\n  state: EditorState,\n  hasFocus: boolean,\n  marks: Marks,\n  visible: readonly { from: number; to: number }[],\n): DecorationSet {\n  const ranges: Range<Decoration>[] = [];\n  const sel = state.selection.main;\n  const touches = (from: number, to: number) => hasFocus && sel.from <= to && sel.to >= from;\n  // A block marker only counts once a space follows it. Markdown already\n  // calls a lone \"*\" or \"#\" an empty list item or heading, so without this a\n  // \"*\" typed to open *italic* flashes a bullet, and \"#\" jumps to heading size\n  // before there is a heading. Until the space it is the text that was typed.\n  const committed = (markerEnd: number) => /[ \\t]/.test(state.doc.sliceString(markerEnd, markerEnd + 1));\n  const tree = syntaxTree(state);\n  const metrics = state.field(hangMetrics, false) ?? null;\n  // What stands before the text on a list row, in px, keyed by the row's line\n  // start — filled from the tree walk, read in the line loop. Every kind of\n  // marker occupies the same column, so it is the same number on all three.\n  const markerWidth = new Map<number, number>();\n  const column = metrics ? markerColumn(metrics) : 0;\n\n  for (const { from: rangeFrom, to: rangeTo } of visible) {\n    // Inline constructs the parser DID match, per line — used to scan only\n    // leftover text for unclosed delimiters below.\n    const covered: [number, number][] = [];\n\n    tree.iterate({\n      from: rangeFrom,\n      to: rangeTo,\n      enter: (node) => {\n        if (node.name.startsWith(\"ATXHeading\")) {\n          const headerMark = node.node.getChild(\"HeaderMark\");\n          if (!headerMark || !committed(headerMark.to)) return;\n          const level = Number(node.name.slice(\"ATXHeading\".length));\n          const line = state.doc.lineAt(node.from);\n          ranges.push(marks.headingLines[level - 1].range(line.from));\n          const tag = marks.headingTags[level - 1];\n          if (tag && node.to > node.from) ranges.push(tag.range(node.from, node.to));\n          if (!touches(node.from, node.to)) {\n            // Swallow the space after \"#\" too, so the text sits flush left.\n            const end =\n              state.doc.sliceString(headerMark.to, headerMark.to + 1) === \" \"\n                ? headerMark.to + 1\n                : headerMark.to;\n            ranges.push(marks.hide.range(headerMark.from, end));\n          }\n          return;\n        }\n        switch (node.name) {\n          case \"StrongEmphasis\":\n          case \"Emphasis\":\n          case \"Strikethrough\": {\n            covered.push([node.from, node.to]);\n            const mark =\n              node.name === \"StrongEmphasis\" ? marks.strong : node.name === \"Emphasis\" ? marks.em : marks.del;\n            ranges.push(mark.range(node.from, node.to));\n            if (!touches(node.from, node.to)) {\n              const markName = node.name === \"Strikethrough\" ? \"StrikethroughMark\" : \"EmphasisMark\";\n              for (const child of node.node.getChildren(markName)) {\n                ranges.push(marks.hide.range(child.from, child.to));\n              }\n            }\n            break;\n          }\n          case \"HorizontalRule\": {\n            // The three dashes come back while the caret is on the line, the\n            // way a heading's `#` does — that is how the rule is edited.\n            if (touches(node.from, node.to)) break;\n            ranges.push(Decoration.replace({ widget: new HrWidget(marks.hr) }).range(node.from, node.to));\n            break;\n          }\n          case \"Blockquote\": {\n            // Every row of the quote carries the rule, lazy continuation lines\n            // included. The markers themselves are handled by the QuoteMark\n            // case: only the FIRST row's `>` is a child of the Blockquote —\n            // a continued row's belongs to the Paragraph inside it.\n            const opener = node.node.getChild(\"QuoteMark\");\n            if (!opener || !committed(opener.to)) break;\n            const last = state.doc.lineAt(node.to).number;\n            for (let n = state.doc.lineAt(node.from).number; n <= last; n++) {\n              ranges.push(marks.quoteLine.range(state.doc.line(n).from));\n            }\n            break;\n          }\n          case \"QuoteMark\": {\n            // Concealed even with the caret on the row, as a bullet is: the\n            // rule already says \"quote\", and a `>` surfacing on the line you\n            // are typing is noise. Backspace at the head still removes it.\n            // Nested `> > ` gives two adjacent marks, which do not overlap.\n            if (!committed(node.to)) break;\n            ranges.push(marks.hide.range(node.from, node.to + 1));\n            break;\n          }\n          case \"InlineCode\": {\n            covered.push([node.from, node.to]);\n            ranges.push(marks.code.range(node.from, node.to));\n            if (!touches(node.from, node.to)) {\n              for (const mark of node.node.getChildren(\"CodeMark\")) {\n                ranges.push(marks.hide.range(mark.from, mark.to));\n              }\n            }\n            break;\n          }\n          case \"ListItem\": {\n            const listMark = node.node.getChild(\"ListMark\");\n            if (!listMark || !committed(listMark.to)) break;\n            ranges.push(marks.listLine.range(state.doc.lineAt(node.from).from));\n            break;\n          }\n          case \"ListMark\": {\n            if (!committed(node.to)) break;\n            const item = node.node.parent; // ListItem\n            const lineFrom = state.doc.lineAt(node.from).from;\n            // Whatever the marker is, it fills the column and the document's\n            // own space follows it, so the text starts at the same x on all\n            // three kinds of row — and the row wraps under that text.\n            if (metrics) markerWidth.set(lineFrom, column + metrics.space);\n            if (item?.parent?.name !== \"BulletList\") {\n              // An ordered row keeps its \"1.\" as text; only the column is ours.\n              ranges.push(orderedMark.range(node.from, node.to));\n              break;\n            }\n            const isTask = item.getChild(\"Task\") !== null;\n            // Bullets render as glyphs even with the caret adjacent — a fresh\n            // \"- \" from Enter shows its bullet before any content is typed.\n            // Backspace still removes the marker via deleteMarkupBackward.\n            if (isTask) {\n              // Nothing here: the TaskMarker case draws \"- [ ]\" as ONE\n              // checkbox, so the bullet is inside that decoration.\n            } else {\n              // Nesting depth picks the glyph (• then ◦).\n              let depth = 0;\n              for (let p = item.parent.parent; p; p = p.parent) {\n                if (p.name === \"BulletList\" || p.name === \"OrderedList\") depth++;\n              }\n              ranges.push(\n                Decoration.replace({\n                  widget: new BulletWidget(depth === 0 ? \"•\" : \"◦\", marks.bullet),\n                }).range(node.from, node.to),\n              );\n            }\n            break;\n          }\n          case \"TaskMarker\": {\n            const checked = state.doc.sliceString(node.from, node.to).toLowerCase().includes(\"x\");\n            // One decoration over the whole \"- [ ]\", not a hidden \"- \" beside\n            // a checkbox: the seam between two replaced ranges is a legal\n            // caret position that renders nowhere, and Backspace in it ate the\n            // space and took the checkbox with it.\n            const from = taskMarkerFrom(node.node);\n            ranges.push(\n              Decoration.replace({\n                widget: new CheckboxWidget(checked, marks.checkbox, node.from - from),\n              }).range(from, node.to),\n            );\n            if (checked) {\n              const line = state.doc.lineAt(node.to);\n              if (line.to > node.to + 1) {\n                ranges.push(marks.taskDone.range(node.to + 1, line.to));\n              }\n            }\n            break;\n          }\n          case \"Link\": {\n            // [label](url) — conceal to just the styled label; reveal raw when\n            // the selection is anywhere inside. Cmd+click opens (handler below).\n            const linkMarks = node.node.getChildren(\"LinkMark\");\n            if (linkMarks.length < 2) break;\n            covered.push([node.from, node.to]);\n            const labelFrom = linkMarks[0].to;\n            const labelTo = linkMarks[1].from;\n            if (labelTo > labelFrom) ranges.push(marks.link.range(labelFrom, labelTo));\n            if (!touches(node.from, node.to)) {\n              ranges.push(marks.hide.range(node.from, labelFrom));\n              ranges.push(marks.hide.range(labelTo, node.to));\n            }\n            break;\n          }\n        }\n      },\n    });\n\n    // Eager styling for unclosed constructs: scan each line's text that isn't\n    // part of a parsed construct; the first unmatched delimiter styles the\n    // rest of the line, and (like closed constructs) the delimiter itself\n    // conceals once the caret leaves the range.\n    //\n    // `covered` is in tree pre-order, so already ascending by `from`: `first`\n    // only moves forward, where filtering it per line was quadratic.\n    let first = 0;\n    const firstLine = state.doc.lineAt(rangeFrom).number;\n    const lastLine = state.doc.lineAt(rangeTo).number;\n    for (let lineNo = firstLine; lineNo <= lastLine; lineNo++) {\n      const line = state.doc.line(lineNo);\n      if (line.length === 0) continue;\n      if (metrics) {\n        // Leading whitespace plus the row's marker, if any. A tab counts as\n        // one space's width — the indent unit writes spaces, so a tab here\n        // was pasted in and is rare enough to be off by a little.\n        const indent = /^[ \\t]*/.exec(line.text)![0].length * metrics.space;\n        const hang = indent + (markerWidth.get(line.from) ?? 0);\n        if (hang > 0) ranges.push(hangLine(hang, column).range(line.from));\n      }\n      while (first < covered.length && covered[first][1] <= line.from) first++;\n      const segments: [number, number][] = [];\n      let cursor = line.from;\n      for (let j = first; j < covered.length && covered[j][0] < line.to; j++) {\n        const [f, t] = covered[j];\n        if (t <= line.from) continue;\n        if (f > cursor) segments.push([cursor, Math.min(f, line.to)]);\n        cursor = Math.max(cursor, t);\n      }\n      if (cursor < line.to) segments.push([cursor, line.to]);\n\n      outer: for (const [segFrom, segTo] of segments) {\n        const segText = state.doc.sliceString(segFrom, segTo);\n        for (const { re, len, deco } of marks.unclosed) {\n          const m = re.exec(segText);\n          if (!m) continue;\n          const delimFrom = segFrom + m.index;\n          ranges.push(deco.range(delimFrom + len, line.to));\n          if (!touches(delimFrom, line.to)) {\n            ranges.push(marks.hide.range(delimFrom, delimFrom + len));\n          }\n          break outer;\n        }\n      }\n    }\n  }\n\n  return Decoration.set(ranges, true);\n}\n\n// Cmd/Ctrl+click opens the link under the pointer (plain click edits).\nconst linkClickHandler = EditorView.domEventHandlers({\n  mousedown(event, view) {\n    if (!(event.metaKey || event.ctrlKey)) return false;\n    const pos = view.posAtCoords({ x: event.clientX, y: event.clientY });\n    if (pos == null) return false;\n    let node: SyntaxNode | null = syntaxTree(view.state).resolveInner(pos, 0);\n    while (node && node.name !== \"Link\") node = node.parent;\n    const url = node?.getChild(\"URL\");\n    if (!url) return false;\n    window.open(view.state.doc.sliceString(url.from, url.to), \"_blank\", \"noopener\");\n    return true;\n  },\n});\n\n/** The live-preview plugin alone, so an element-map change can be swapped\n *  through a `Compartment` without rebuilding the editor's history. */\nexport function livePreview(elements?: EditorElements): Extension {\n  const marks = createMarks(elements);\n  return [\n    hangMeasurer(marks),\n    ViewPlugin.fromClass(\n    class {\n      decorations: DecorationSet;\n      constructor(view: EditorView) {\n        this.decorations = computeLiveDecorations(view.state, view.hasFocus, marks, view.visibleRanges);\n      }\n      update(update: ViewUpdate) {\n        // IME guard: rebuilding decorations mid-composition detaches the\n        // candidate popup. Map the existing ones through the change instead.\n        if (update.view.composing) {\n          this.decorations = this.decorations.map(update.changes);\n          return;\n        }\n        // The tree check is not optional: Lezer parses in time-sliced chunks\n        // and reports each one as a transaction that changes neither the doc\n        // nor the selection. Without it, a document whose first parse pass\n        // ran out of budget — a long one, or a busy page with several\n        // editors — keeps the decorations of the fragment that WAS parsed and\n        // shows the rest as raw markdown, at random. `viewportChanged` covers\n        // scrolling into a new part of the document, which touches none of\n        // the above but still needs its own now-visible range decorated.\n        if (\n          update.docChanged ||\n          update.selectionSet ||\n          update.focusChanged ||\n          update.viewportChanged ||\n          syntaxTree(update.startState) !== syntaxTree(update.state) ||\n          update.startState.field(hangMetrics, false) !== update.state.field(hangMetrics, false)\n        ) {\n          this.decorations = computeLiveDecorations(\n            update.state,\n            update.view.hasFocus,\n            marks,\n            update.view.visibleRanges,\n          );\n        }\n      }\n    },\n    { decorations: (v) => v.decorations },\n    ),\n  ];\n}\n\n// The same language, minus CommonMark's indented code blocks: four leading\n// spaces are what Tab writes here, and a paragraph someone indented to set it\n// apart must keep its **bold** and its links rather than turn into verbatim\n// code (which also let the eager unclosed-`**` styling run away with the\n// rest of the line). Fenced ``` blocks are untouched. Built the way\n// lang-markdown builds its own, so no other behaviour changes.\nconst proseMarkdown = new Language(\n  markdownLanguage.data,\n  // Typed as the generic Parser; it is lezer-markdown's, which configures.\n  (markdownLanguage.parser as MarkdownParser).configure({ remove: [\"IndentedCode\"] }),\n  [],\n  \"markdown\",\n);\n\n/** Everything that is not typography: the markdown language, the keymaps,\n *  history, the placeholder and the chromeless theme. Pair with\n *  `livePreview()`. */\nexport function liveMarkdownBase(placeholderText = \"\"): Extension[] {\n  return [\n    // The keymap below is ours rather than markdownKeymap: its default Enter\n    // command turns a tight list non-tight on the second empty item (blank\n    // line + carried bullet) — nonTightLists: false makes double-Enter exit\n    // the list, removing the empty item's marker instead.\n    //\n    // The bare language, not markdown(): that wrapper drags the HTML, CSS\n    // and JS language packages (plus autocomplete) into a prose editor.\n    // pasteURLAsLink is the one piece of it this editor uses.\n    proseMarkdown,\n    pasteURLAsLink,\n    atomicTaskMarkers,\n    keymap.of([\n      { key: \"Enter\", run: exitEmptyQuote },\n      { key: \"Enter\", run: openItemAbove },\n      { key: \"Enter\", run: insertNewlineContinueMarkupCommand({ nonTightLists: false }) },\n      { key: \"Backspace\", run: deleteMarkupBackward },\n      { key: \"Home\", run: cursorTextStart, preventDefault: true },\n      // Cmd+Left only, mirroring standardKeymap: `Mod-ArrowLeft` is word-left\n      // off the Mac, and line start is a Mac-only binding there too.\n      { mac: \"Cmd-ArrowLeft\", run: cursorTextStart, preventDefault: true },\n    ]),\n    linkClickHandler,\n    hangMetrics,\n    history(),\n    // drawSelection() forces `caret-color: transparent` and paints its own\n    // caret and selection. On a desktop that is an improvement — the native\n    // caret spans the whole line box and reads oversized. On a phone it takes\n    // away the things a finger actually uses: the caret you drag, the\n    // selection handles, the magnifier. The platform keeps its own there.\n    ...(isTouchDevice() ? [] : [drawSelection()]),\n    // Tab is trapped here for indenting every selected line (Shift+Tab\n    // outdents); Escape, bound above in blurKeymap, is the keyboard way out.\n    // Four spaces a step: a nested bullet still nests, and the extra width\n    // reads as a level in prose type where two spaces barely register. See\n    // proseMarkdown for why that doesn't turn a paragraph into code.\n    indentUnit.of(\"    \"),\n    keymap.of([...blurKeymap, ...formattingKeymap, indentWithTab, ...defaultKeymap, ...historyKeymap]),\n    EditorView.lineWrapping,\n    // Only with text to show: the extension writes `aria-placeholder` from\n    // whatever it is given, and an empty one is an attribute that says nothing.\n    ...(placeholderText ? [cmPlaceholder(placeholderText)] : []),\n    keyboardAware,\n    EditorView.contentAttributes.of({\n      // A textbox has to be named. The placeholder is the caller's own words\n      // for this field, so it names it when there is one; without it the\n      // fallback at least says what the field is, where \"\" left a screen\n      // reader announcing an unlabelled edit box.\n      \"aria-label\": placeholderText || \"Markdown editor\",\n      // CodeMirror ships code-editor defaults (spellcheck off, autocorrect\n      // off, autocapitalize off). This is prose: without these, typing a\n      // sentence on a phone gives you no capital, no autocorrect and no\n      // spellcheck, which reads as a broken text field rather than a choice.\n      autocorrect: \"on\",\n      autocapitalize: \"sentences\",\n      spellcheck: \"true\",\n    }),\n    chromelessTheme,\n  ];\n}\n",
      "type": "registry:lib",
      "target": "lib/live-markdown.ts"
    }
  ],
  "docs": "Docs & live playground: https://www.deltacomponents.dev/docs/editor.",
  "categories": [
    "components"
  ],
  "type": "registry:ui"
}
