@estiva-app/ui 0.108.0 → 0.108.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/SelectionToolbar.tsx", "../src/CommentBox.tsx", "../node_modules/@estiva-app/conversation/src/refusals.ts", "../src/BlockNodes.tsx", "../src/LinkPlaces.ts", "../src/ReferenceMenu.tsx", "../src/LinkChips.ts", "../src/ReferenceCards.ts", "../src/suggestionPopup.tsx", "../src/commentBoxFrame.tsx", "../src/looks.ts", "../src/ComposerTriggers.tsx", "../src/links.ts", "../src/PastedImages.ts", "../src/InlineText.tsx", "../src/CommentHighlights.ts", "../src/PastedMarkdown.ts", "../src/CodeBlockColours.ts", "../src/codeColours.ts", "../src/EditorBlockHandle.tsx", "../src/EditorTableControls.tsx", "../src/DocumentEditor.tsx", "../src/AskedBlocks.ts", "../src/DocumentField.tsx"],
4
- "sourcesContent": ["import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'\nimport type { Editor } from '@tiptap/react'\nimport { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport { IconBold, IconCode, IconItalic, IconLink, IconUnderline } from '@tabler/icons-react'\nimport { Form } from './Form'\nimport { Popover } from './Popover'\nimport { TextInput } from './TextInput'\nimport { Toolbar, ToolbarButton, ToolbarSeparator } from './Toolbar'\nimport { shortcutLabel } from './shortcuts'\n\n/**\n * The selection, kept visible while something else has the focus \u2014 Peek's\n * `src/extensions/keptSelection.ts` (PEE-19), moved into the package with the\n * `SelectionToolbar` that needs it (UIG-31, Katerina's ruling 29 September).\n *\n * The toolbar's address field takes the focus, and with it the document's\n * one selection, so the words being linked lost their highlight the moment\n * the field opened (measured 2026-09-07). Linear keeps it, and Katerina asked\n * for the same. The editor's own selection never moved \u2014 ProseMirror keeps it\n * while unfocused \u2014 so this only *draws* it: an inline decoration over the\n * range, in `bg-selected` \u2014 the token every kit editor paints `::selection` in\n * (`EDITOR_SELECTION_CLASSES`) \u2014 mapped through edits and cleared when the field closes.\n *\n * A decoration rather than a second selection, because a document has one\n * and the field needs it. Editor-internal by design (the editor owns its own\n * drawing); nothing here floats, focuses or handles a key.\n */\n\nexport interface KeptRange {\n from: number\n to: number\n}\n\n/** The plugin's key: read what is being kept, or dispatch a change to it. */\nexport const keptSelectionKey = new PluginKey<KeptRange | null>('keptSelection')\n\n/** The extension an editor registers so a selection can stay drawn while a field has the focus. */\nexport const KeptSelection = Extension.create({\n name: 'keptSelection',\n\n addProseMirrorPlugins() {\n return [\n new Plugin<KeptRange | null>({\n key: keptSelectionKey,\n state: {\n init: () => null,\n apply(tr, previous) {\n const meta = tr.getMeta(keptSelectionKey) as KeptRange | null | undefined\n if (meta !== undefined) return meta\n if (!previous) return null\n // Follow the words through an edit, so applying the link to them\n // (or typing before them) does not leave the highlight behind.\n return { from: tr.mapping.map(previous.from), to: tr.mapping.map(previous.to) }\n },\n },\n props: {\n decorations(state) {\n const range = keptSelectionKey.getState(state)\n if (!range || range.from === range.to) return null\n return DecorationSet.create(state.doc, [\n Decoration.inline(range.from, range.to, { class: 'kept-selection bg-bg-selected' }),\n ])\n },\n },\n }),\n ]\n },\n})\n\n/** Draw the selection as it is now, until `releaseSelection`. */\nexport function keepSelection(editor: Editor) {\n const { from, to } = editor.state.selection\n editor.view.dispatch(editor.state.tr.setMeta(keptSelectionKey, { from, to }))\n}\n\n/** Stop drawing it. Nothing kept, nothing dispatched. */\nexport function releaseSelection(editor: Editor) {\n if (editor.isDestroyed || !keptSelectionKey.getState(editor.state)) return\n editor.view.dispatch(editor.state.tr.setMeta(keptSelectionKey, null))\n}\n\n/** What is being drawn, or null. */\nexport function keptSelection(editor: Editor): KeptRange | null {\n return keptSelectionKey.getState(editor.state) ?? null\n}\n\n/** A mark the strip can toggle \u2014 the suite's inline vocabulary (SPEC \u00A713.1) less link and reference. */\nexport type MarkId = 'bold' | 'italic' | 'underline' | 'code'\n\nconst MARKS: Record<MarkId, { label: string; keys: string }> = {\n bold: { label: 'Bold', keys: 'Mod-B' },\n italic: { label: 'Italic', keys: 'Mod-I' },\n underline: { label: 'Underline', keys: 'Mod-U' },\n code: { label: 'Code', keys: 'Mod-E' },\n}\n\n/**\n * Toggle one mark over the current selection. The core `toggleMark`, which\n * each mark's own `toggleBold` and the like wrap: the package names no Tiptap\n * extension, only the marks the suite's format has (SPEC \u00A713.1).\n */\nfunction toggleMark(editor: Editor, id: MarkId): boolean {\n return editor.chain().focus().toggleMark(id).run()\n}\n\n/** The address the selection sits in, or '' \u2014 what the link field opens with. */\nexport function currentLink(editor: Editor): string {\n const href: unknown = editor.getAttributes('link').href\n return typeof href === 'string' ? href : ''\n}\n\n/**\n * What somebody typed into the link field \u2192 an `href`, or null when it cannot\n * be one. A bare host (`google.com`) gets `https://`. A scheme is kept only when\n * SPEC \u00A713.1 lets a reader follow it (http, https, mailto); `javascript:` and\n * the like are refused here. `localhost:5173` is a host and a port: a scheme is\n * never followed by a digit.\n */\nexport function normalizeHref(raw: string): string | null {\n const s = raw.trim()\n if (!s || /\\s/.test(s)) return null\n if (/^(https?:|mailto:)/i.test(s)) return s\n if (/^[a-z][a-z0-9+.-]*:(?!\\d)/i.test(s)) return null\n return `https://${s}`\n}\n\n/**\n * Apply the link field to the selection. Empty removes the link; an address\n * sets it, over the whole link when the caret sits inside one. `false` means\n * the text could not be an address, and the field should stay open.\n */\nexport function applyLink(editor: Editor, raw: string): boolean {\n const chain = editor.chain().focus().extendMarkRange('link')\n // The core commands the Link extension's `setLink` and `unsetLink` wrap, with\n // the same meta; `normalizeHref` has already refused what it would refuse.\n if (!raw.trim()) return chain.unsetMark('link', { extendEmptyMarkRange: true }).setMeta('preventAutolink', true).run()\n const href = normalizeHref(raw)\n if (!href) return false\n return chain.setMark('link', { href }).setMeta('preventAutolink', true).run()\n}\n\n/**\n * Bold / italic / underline / link over selected text \u2014 Peek's\n * `SelectionToolbar` (PEE-18, PEE-19), moved into the package at Katerina's\n * word (29 September, UIG-31) when Ship's description became its second user.\n * Unchanged but for two props: `marks`, which buttons the strip has (Peek's\n * three by default; Ship adds code), and `link`, whether it has the Link button\n * and its field (Peek's editor has a link mark; an editor without one leaves it\n * off). The editor must register `KeptSelection` when `link` is on.\n *\n * The marks apply to a run you have already written, which is why they are\n * not in the `/` menu: typing `/` replaces the selection, so by definition\n * there is nothing selected to apply them to.\n *\n * **The chrome is the shared `Popover`, anchored** (P26). It was a `Menu`, and\n * it never was one: a menu gives its contents roving focus and typeahead,\n * which would fight the link field this panel exists for. An anchored\n * `Popover` is the mode built for exactly this \u2014 it takes no focus, so the\n * caret stays in the text. It is laid out as a row instead of a column\n * through `className`, which `cn` merges last. The panel still portals out of\n * the composer, so no overflow clips it, and Floating UI clamps it on screen.\n *\n * **The anchor is the selection's own point** since 0.12.2. This toolbar is\n * *centred* over the selection (her design, PEE-19, after Linear), and the\n * package's `Popover` aligns left or right only \u2014 Base UI has `center`, the\n * package does not expose it (ADOPTION **B21**). So the placement arithmetic\n * and the hand-measured `SIZE` box stay for now, and the rect handed over is\n * positioned so the panel lands on the same pixel it always has: the\n * package's own 4px gap is subtracted from this file's 8px, and the rect's\n * left edge is the panel's. When `align=\"center\"` exists, `SIZE`, `GAP` and\n * `placement` all go and the anchor becomes the selection's own rect.\n *\n * **Two faces** (PEE-19 \u2014 Katerina, 2026-09-07, after Linear). `marks` is the\n * row of four buttons. `link` is one text field for the address: it opens from\n * the Link button, and opens by itself when the settled selection sits inside\n * a link, with that link's address in it. There is no open, embed or delete\n * button, by her call: the field is the whole control.\n *\n * **What applies the field** (her rule, same day): Enter, and clicking away \u2014\n * anywhere outside the toolbar, the editor included. Enter on an empty field\n * removes the link; clicking away with an empty field changes nothing, since\n * removing is deliberate and leaving is not. Escape drops what was typed and\n * puts the caret back. Once applied, the caret lands after the link, and\n * typing goes on as plain text \u2014 the mark is not inclusive (editorKit).\n *\n * While the field has focus the editor has not, so everything below that\n * hides the toolbar on blur or on an empty editor selection stands down in\n * `link` mode. The editor keeps its selection while unfocused; `focus()` in\n * the apply command puts it back.\n *\n * **Why it waits.** Showing on every selection change put the toolbar under the\n * pointer mid-drag, and made it blink on a plain click \u2014 ProseMirror restores\n * the previous selection when the editor takes focus and collapses it a tick\n * later, so there is a real, non-empty range in between. Both go away by\n * refusing to show while the pointer is down and re-reading the selection after\n * a short settle rather than trusting the event that woke us.\n */\n\nconst ICONS: Record<MarkId, typeof IconBold> = {\n bold: IconBold,\n italic: IconItalic,\n underline: IconUnderline,\n code: IconCode,\n}\n\ntype Mode = 'marks' | 'link'\n\n/** How long a selection must stand still before the toolbar appears. */\nconst SETTLE_MS = 250\nconst GAP = 8\n/** The gap the package's `Popover` adds of its own, subtracted above so the\n * panel keeps this file's 8px. Read from `Popover.tsx`, not guessed. */\nconst POPOVER_GAP = 4\n\nexport interface SelectionToolbarProps {\n /** The editor whose selection the strip follows. `null` while it loads. */\n editor: Editor | null\n /** Which marks the strip toggles, in order. Default bold, italic, underline. */\n marks?: readonly MarkId[]\n /** The Link button and its address field. Needs a link mark in the editor and `KeptSelection`. Default off. */\n link?: boolean\n /**\n * More of the strip, after the marks: the app's own `ToolbarButton`s for what\n * is selected \u2014 a chip's card, say. Each keeps the selection by preventing\n * its press's default, as the marks do. Nothing is added when it renders\n * nothing.\n */\n children?: ReactNode\n /**\n * The app's own buttons after the marks, past a separator: \"Comment\". Each\n * runs with the selection still in place, and the strip closes after it.\n */\n actions?: readonly SelectionAction[]\n}\n\n/** One of the app's buttons in the strip. */\nexport interface SelectionAction {\n /** Says what it does: the tooltip and the button's name. */\n label: string\n /** A 16px icon. */\n icon: ReactNode\n /** The keys that do the same, shown in the tooltip (\"Mod-Shift-M\"). */\n keys?: string\n /** What it does, with the selection as it is. */\n run: (editor: Editor) => void\n}\n\nexport function SelectionToolbar({ editor, marks = ['bold', 'italic', 'underline'], link = false, children, actions = [] }: SelectionToolbarProps) {\n /** The selection's top edge and horizontal centre; the face decides the rest. */\n const [anchor, setAnchor] = useState<{ top: number; centre: number } | null>(null)\n const [mode, setMode] = useState<Mode>('marks')\n const [url, setUrl] = useState('')\n // Re-render as marks turn on and off while the caret moves through the\n // selection, so the pressed states stay honest.\n const [, setTick] = useState(0)\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const pointerDown = useRef(false)\n const field = useRef<HTMLInputElement>(null)\n /** What the field holds while it is open; null while it is closed. The\n * listeners below are bound once, so they read this rather than state. */\n const draft = useRef<string | null>(null)\n // Read by the same listeners. Kept in an effect, declared before the focus\n // effect below so the ref already says `link` when the field's focus blurs\n // the editor.\n const modeRef = useRef<Mode>('marks')\n useEffect(() => {\n modeRef.current = mode\n }, [mode])\n // Read by `settle`, which is bound once: words already a link open the field only when there is one.\n const linkOn = useRef(link)\n linkOn.current = link\n\n const hide = useCallback(() => {\n clearTimeout(timer.current)\n draft.current = null\n if (editor) releaseSelection(editor)\n setAnchor(null)\n setMode('marks')\n }, [editor])\n\n /**\n * Leaving the field applies it (Enter or a click away). An address links the\n * words and the caret moves past them; an empty field on the way out is a\n * shrug, not a removal. Idempotent: the outside click reaches this twice,\n * once from the editor press and once from the Menu's own listener.\n */\n const commit = useCallback(() => {\n const text = draft.current\n if (text === null || !editor) return\n draft.current = null\n if (text.trim() && applyLink(editor, text)) {\n editor.commands.setTextSelection(editor.state.selection.to)\n }\n hide()\n }, [editor, hide])\n\n /** Read the selection as it is *now* and place the toolbar, or hide it. */\n const settle = useCallback(() => {\n if (!editor || editor.isDestroyed) return\n // Keeping the selection drawn is itself a transaction, which schedules\n // this; by then the field has the focus, and reading `hasFocus()` here\n // would close it.\n if (modeRef.current === 'link') return\n const { state, view } = editor\n const { empty, from, to } = state.selection\n if (empty || from === to || !view.hasFocus() || pointerDown.current) {\n setAnchor(null)\n setMode('marks')\n return\n }\n const start = view.coordsAtPos(from)\n const end = view.coordsAtPos(to)\n const centre = (Math.min(start.left, end.left) + Math.max(start.right, end.right)) / 2\n // Words that are already a link open on the field, with their address in it.\n const inLink = linkOn.current && editor.isActive('link')\n const address = inLink ? currentLink(editor) : ''\n draft.current = inLink ? address : null\n // The field is about to take the focus; the words stay highlighted.\n if (inLink) keepSelection(editor)\n setMode(inLink ? 'link' : 'marks')\n setUrl(address)\n setAnchor({ top: start.top, centre })\n }, [editor])\n\n useEffect(() => {\n if (!editor) return\n\n const schedule = () => {\n // The field owns the keyboard and the focus; the editor's own events\n // stand down until it closes.\n if (modeRef.current === 'link') return\n setTick((t) => t + 1)\n clearTimeout(timer.current)\n // A collapsed selection hides at once \u2014 waiting to hide is what made the\n // click blink. Only *showing* is deferred.\n if (editor.state.selection.empty) {\n setAnchor(null)\n return\n }\n timer.current = setTimeout(settle, SETTLE_MS)\n }\n\n // The field taking focus is the one blur that must not hide us.\n const onBlur = () => {\n if (modeRef.current !== 'link') hide()\n }\n\n // Only a press *inside the editor* starts a selection. A press on the\n // toolbar itself must not hide it \u2014 doing so unmounted the button before\n // its click could land, so nothing ever applied.\n const startsSelection = (e: MouseEvent) =>\n e.target instanceof Node && editor.view.dom.contains(e.target)\n\n const onPointerDown = (e: MouseEvent) => {\n if (!startsSelection(e)) return\n // A press in the editor while the field is open is a click away: apply\n // first, before the editor moves the caret under the press.\n commit()\n pointerDown.current = true\n hide()\n }\n const onPointerUp = () => {\n if (!pointerDown.current) return\n pointerDown.current = false\n schedule()\n }\n\n editor.on('selectionUpdate', schedule)\n editor.on('transaction', schedule)\n editor.on('blur', onBlur)\n // @estiva-escape(no-hand-rolled-behaviour): watches presses in the editor to follow a text selection; the Popover it opens in has no trigger to own that (Peek's UIG-8 escape, moved here with the part, UIG-31)\n document.addEventListener('mousedown', onPointerDown, true)\n document.addEventListener('mouseup', onPointerUp, true)\n\n return () => {\n clearTimeout(timer.current)\n editor.off('selectionUpdate', schedule)\n editor.off('transaction', schedule)\n editor.off('blur', onBlur)\n document.removeEventListener('mousedown', onPointerDown, true)\n document.removeEventListener('mouseup', onPointerUp, true)\n }\n }, [editor, settle, hide, commit])\n\n // The field takes focus once it is on screen. Not `autoFocus`, and not in\n // the same frame: the Menu renders once hidden to measure itself, and a\n // hidden input cannot take focus \u2014 measured 2026-09-07, the field opened\n // unfocused on a re-selected link. An address already in it is selected\n // whole, so typing replaces it.\n useEffect(() => {\n if (mode !== 'link' || !anchor) return\n const frame = requestAnimationFrame(() => {\n field.current?.focus()\n field.current?.select()\n })\n return () => cancelAnimationFrame(frame)\n }, [mode, anchor])\n\n if (!editor || !anchor) return null\n\n const openField = () => {\n const address = currentLink(editor)\n draft.current = address\n keepSelection(editor)\n setUrl(address)\n setMode('link')\n }\n /** Enter. Unlike a click away, an empty field here means remove. */\n const submit = () => {\n if (!url.trim()) {\n applyLink(editor, '')\n hide()\n editor.commands.focus()\n return\n }\n commit()\n }\n const discard = () => {\n hide()\n editor.commands.focus()\n }\n\n /* A zero-sized rect at the selection's own top edge and centre. The panel's\n width is no longer this file's business: `align=\"center\"` puts the\n panel's middle over this point (B21, package 0.12.2), so the measured\n `SIZE` table and the placement arithmetic that stood in for it are gone.\n The top is this file's GAP less the package's own 4, so the panel keeps\n the 8px it has always had. */\n const anchorRect = new DOMRect(anchor.centre, anchor.top - (GAP - POPOVER_GAP), 0, 0)\n\n return (\n <Popover\n anchor={anchorRect}\n open\n side=\"top\"\n align=\"center\"\n onOpenChange={(next) => {\n if (!next) commit()\n }}\n ariaLabel=\"Text formatting\"\n // The panel gives up its column; the strip inside draws the row. The 4px\n // around it is `contentClassName`'s: on `className` it was added to the\n // package's 8px from 0.12.6 on, and the toolbar grew 8px a side\n // (Katerina, 2026-09-13; migration docs D68, Finding 60). This is the\n // package's own `Popover/A toolbar` story, class for class.\n className=\"w-auto min-w-0\"\n contentClassName=\"p-1\"\n >\n {mode === 'link' ? (\n /* One field, so no strip: a toolbar of one control is a toolbar in\n name only, and `ToolbarInput` cannot take the ref this field is\n focused by (ADOPTION B25). */\n // The package Form (UIG-7): Enter applies the link. `free` and `flex`: one field, which keeps its own height.\n <Form onSubmit={submit} layout=\"free\" className=\"flex\">\n <TextInput\n ref={field}\n value={url}\n onChange={(e) => {\n setUrl(e.target.value)\n draft.current = e.target.value\n }}\n onKeyDown={(e) => {\n if (e.key === 'Escape') {\n // Before the Menu's own Escape, which would apply instead.\n e.stopPropagation()\n discard()\n }\n }}\n placeholder=\"Enter link URL\"\n aria-label=\"Link URL\"\n className=\"w-[264px]\"\n />\n </Form>\n ) : (\n /* Four marks and a link button: one Tab stop, \u2190 \u2192 along them (D29). */\n <Toolbar aria-label=\"Text formatting\" surface={false}>\n {marks.map((id) => {\n const Icon = ICONS[id]\n const active = editor.isActive(id)\n return (\n <ToolbarButton\n key={id}\n aria-label={MARKS[id].label}\n pressed={active}\n tooltip={MARKS[id].label}\n tooltipShortcut={shortcutLabel(MARKS[id].keys)}\n // Keep the selection: focus must not leave the editor on press.\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => toggleMark(editor, id)}\n >\n <Icon size={16} stroke={1.5} />\n </ToolbarButton>\n )\n })}\n {link && (\n <ToolbarButton\n aria-label=\"Link\"\n tooltip=\"Link\"\n onMouseDown={(e) => e.preventDefault()}\n onClick={openField}\n >\n <IconLink size={16} stroke={1.5} />\n </ToolbarButton>\n )}\n {children}\n {/* Between the marks and the app's buttons: with no mark or Link before them (read only), nothing to part. */}\n {actions.length > 0 && (marks.length > 0 || link || children) && <ToolbarSeparator />}\n {actions.map((action) => (\n <ToolbarButton\n key={action.label}\n aria-label={action.label}\n tooltip={action.label}\n tooltipShortcut={action.keys ? shortcutLabel(action.keys) : undefined}\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => {\n // Closing first: it lets go of a kept selection, which the action may want to keep.\n hide()\n action.run(editor)\n }}\n >\n {action.icon}\n </ToolbarButton>\n ))}\n </Toolbar>\n )}\n </Popover>\n )\n}\n", "import { Fragment, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'\nimport { Extension, nodePasteRule, type AnyExtension, type EditorOptions } from '@tiptap/core'\nimport { Editor, type JSONContent } from '@tiptap/react'\nimport { REFUSAL_REASONS, refusalCause, refusalReason, tooLarge, uploadRefusal } from '@estiva-app/conversation'\nimport { IconLock, IconPaperclip, IconSquareRounded, IconX } from '@tabler/icons-react'\nimport { AttachedCard } from './AttachedCard'\nimport { AttachmentCard } from './AttachmentCard'\nimport { ReferenceNode, type ReferenceViewProps } from './BlockNodes'\nimport { Button } from './Button'\nimport { Card } from './Card'\nimport { cn } from './cn'\nimport { BoxFrame, ComposeKeys, COMPOSE_EDITOR_CLASSES, isEmptyDoc as isEmpty, SendBox } from './commentBoxFrame'\nimport {\n CaptionedReference,\n PersonMention,\n ReferenceTrigger,\n SlashCommands,\n UrgentPersonMention,\n formatSection,\n typeTrigger,\n type CodeFormat,\n type MentionPerson,\n type ReferenceSection,\n type SlashCommand,\n type SlashSection,\n} from './ComposerTriggers'\nimport { FieldLine } from './Field'\nimport { FilePicker } from './FilePicker'\nimport { IconButton } from './IconButton'\nimport { inTheBox } from './linked'\nimport { LinkedIcon } from './LinkParts'\nimport { linkedKindOfReference } from './LinkPlaces'\nimport { BoxKit, LINK_MARK_ATTRIBUTES, PasteOverWords } from './links'\nimport { PastedImages } from './PastedImages'\nimport { KeptSelection } from './SelectionToolbar'\nimport { isSuggestionOpen } from './suggestionPopup'\nimport { ToolbarButton } from './Toolbar'\nimport { caretOnOpen } from './threadCard'\nimport { sendsInLayout } from './conversationScroll'\n\n/**\n * The one box every app writes a comment, a reply and a chat line in, from the\n * approved prototype (`concept/comments-everywhere`, Miky 17 October): the\n * box's one frame (`commentBoxFrame`) with everything each app built around it \u2014 `@`,\n * `!@`, `[` and `/`, the keys, drafts, files, the edit mode, sending and a\n * refused send. An app hands over only its people, its `[` sections, its `/`\n * Insert rows and a send that says whether the relay accepted it.\n *\n * It speaks the editor's document. What that document writes as a message,\n * and the document an edit or a draft opens with, are `@estiva-app/conversation`'s\n * (`composerText`, `composerDocument`, `composerDraft`).\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-writes-and-reacts-with-one-shared-box.md\n */\n\n/**\n * What the relay said about a send, an edit or a reaction. `reason` is the refusal as it came (the relay's words, an\n * `Error`, an HTTP body, or `{ cause }` for an app's own): the box says it in `@estiva-app/conversation`'s plain words\n * (`refusalReason`), the same in every app, never the relay's.\n */\nexport type SendAnswer = { accepted: true } | { accepted: false; reason: unknown }\n\n/** What an upload answered: the app's own record of the file, or why not, as it came; the card says `uploadRefusal`'s line. */\nexport type UploadAnswer = { accepted: true; value: unknown } | { accepted: false; reason: unknown }\n\n/** Where a file in the box is: Send waits for one uploading. */\nexport type BoxFileState = 'uploading' | 'ready' | 'failed'\n\n/** A file in the box. */\nexport interface BoxFile {\n id: string\n name: string\n size?: number\n contentType?: string\n state: BoxFileState\n /** Why it failed, under its name. */\n note?: string\n /** What `upload` answered for it: the app's own record (an `imeta`, a URL). */\n value?: unknown\n}\n\n/**\n * Why a send was refused. \"This message was deleted\" is an edit's or a reaction's (Decided, ONE-4): a new message\n * refused the same way (a reply whose message went) is one you can no longer write here.\n */\nfunction sendRefusal(reason: unknown): string {\n const cause = refusalCause(reason)\n return REFUSAL_REASONS[cause === 'gone' ? 'no-access' : cause]\n}\n\n/** A draft, in the box's terms \u2014 `@estiva-app/conversation`'s `composerDraft` is one. */\nexport interface CommentBoxDraft {\n read(): JSONContent | undefined\n write(body: JSONContent): void\n clear(): void\n}\n\n/** Editing something already sent: the same box, with Cancel and Save. */\nexport interface CommentBoxEdit {\n /** What it says now, as `composerDocument` opens it. */\n body: JSONContent\n /** Its files, which can be taken off; with `upload` and `writesFiles`, more can be added by `/` \u2192 Upload, a paste or a drop. A box reopened after a refusal is given the files that save carried. */\n files?: BoxFile[]\n /**\n * The app's `onSave` writes the files it is handed, so a file can be added while editing (with `upload`).\n * Opt-in, so an app whose save drops them never offers it: a file added and silently lost.\n */\n writesFiles?: boolean\n /** Why the relay refused this edit, as it came, when the app reopens a box it closed at once: said under it as it opens. Read as the box opens, so a reopen is a new box (a new `key`). */\n refused?: unknown\n onCancel: () => void\n /** Save; the box holds the words until the answer, and a refusal is said under it. */\n onSave: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => Promise<SendAnswer>\n}\n\n/**\n * What a draft shows under the box, as the app reads it from the box's\n * document \u2014 `@estiva-app/conversation`'s `boxReadOf`, which reads it as the\n * message will be sent (why:\n * https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-on-words-counts-toward-the-card.md).\n */\nexport interface BoxUnderRead {\n /** The one card, before any \u2715: what it names, and the app's own view of it, drawn as it draws a sent one. */\n card?: { value: string; view: ReactNode }\n /** The live parts, drawn as the app draws them under a sent message. An edit carries none, so the edit box shows none. */\n parts?: readonly { key: string; view: ReactNode }[]\n /** Everything the draft names. A \u2715 is forgotten once what it took off is no longer named, so a link put back gets its card again. */\n names: readonly string[]\n}\n\n/** What the box shows under itself while something is written. */\nexport interface BoxUnder {\n /** Read on every change, and once more as it is sent. */\n read: (body: JSONContent) => BoxUnderRead\n /** Called with a listener; call it when `read` would answer differently (what a link names came back). */\n changed?: (listener: () => void) => () => void\n}\n\n/** What was under the box as it was sent or saved. */\nexport interface BoxSentUnder {\n /** The card still shown, by what it names: absent when there was none, or \u2715 took it off. */\n card?: string\n}\n\n/** What a new comment will be on, above the box (Leaf's \"On \u201Cwords\u201D\", Ship's block: each hand-made until 3 November). */\nexport interface BoxAbout {\n /** The line: what the posted card's `about` will show. */\n view: ReactNode\n /** \u2715 beside it, in the app's words: \"Comment on the whole document instead\", \"Remove\". Absent, no \u2715. */\n remove?: { label: string; onRemove: () => void }\n}\n\nexport interface CommentBoxProps {\n /** Who `@` and `!@` offer. */\n people: readonly MentionPerson[]\n /** What `[` lists for what was typed, already in the app's order. Absent, `[` opens nothing. */\n references?: (query: string) => readonly ReferenceSection[]\n /** Called with a listener while `[` is open; call it when `references` would answer differently (a search landed). */\n referencesChanged?: (listener: () => void) => () => void\n /**\n * A `[` row's and chip's 16px icon from what it points at. Absent, the kit's icon for the kind its address names\n * (`LinkedIcon`), and a neutral square for an address that names none.\n */\n referenceIcon?: (uri: string | null) => ReactNode | undefined\n /** The app's own `/` Insert rows, after the shared Format section: {@link commentBoxRows} and its own. */\n insert?: readonly SlashCommand[]\n /** `/` \u2192 Code: a mark inside the line, or a block. */\n code?: CodeFormat\n /** Send what is written, with the files that are ready and the card still shown; resolves with the relay's answer. */\n send: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => Promise<SendAnswer>\n /** The card and parts in the box while something is written, with the files, \u2715 on the card. Absent, there are none. */\n under?: BoxUnder\n /**\n * What the new comment will be on, in a strip above the box on the inset fill: the `about` the posted card will carry\n * (a `QuotedLine`, the app's words for a block), with \u2715 in it, in the app's words, to drop it. Not drawn on an edit or\n * a closed box.\n */\n about?: BoxAbout\n /**\n * The app shows a send before the relay answers: the box empties at once,\n * and a refusal puts the words back. Otherwise the box holds the words, shut,\n * until the answer.\n */\n showsAtOnce?: boolean\n /** The editor's accessible name: what the box is for. */\n label: string\n /** Said in the empty box. */\n placeholder: ReactNode\n /** Keeps what is written when the box goes away. Give the box a React `key` per destination. */\n draft?: CommentBoxDraft\n /** Editing something already sent. */\n edit?: CommentBoxEdit\n /** Offers the paperclip, `/` \u2192 File, a pasted picture and a dropped file: uploads one, and answers. */\n upload?: (file: File) => Promise<UploadAnswer>\n /** The file picker's `accept`. */\n accept?: string\n /** The box cannot write here (an archived file, signed out): a line saying why takes its place. Closed from the start, it builds no editor. */\n closed?: { reason: ReactNode }\n /**\n * How a link the box holds is drawn \u2014 a pasted one, a pasted `nostr:` address, and a `[` pick alike: the app's view\n * of the kit's `LinkChip`, told it is being edited (no preview; a click stays in the draft). Absent, a `nostr:`\n * reference reads as its URI and a `[` pick as its caption.\n */\n referenceView?: ComponentType<ReferenceViewProps>\n /** The app's own extra editor extensions: link chips, highlights. */\n extensions?: readonly AnyExtension[]\n autoFocus?: boolean\n /** Called with what was sent once it went out: at once when `showsAtOnce`, else on the answer. */\n onSent?: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => void\n /** Called when a send shown at once was refused, so the app takes it back. */\n onRefused?: () => void\n /** The bar down the text's left edge shows while this holds, besides while an urgent mention is in the box: the app's own marks (a highlight). */\n marked?: (editor: Editor) => boolean\n /** Called with the box's editor once it is drawn, and with `null` as it goes: an app's launcher inserts into the box last used. */\n onEditor?: (editor: Editor | null) => void\n className?: string\n}\n\nconst ATTACH_EVENT = 'commentbox:attach'\n\n/** Asks the box around the editor for a file, as the paperclip does. */\nconst askForFile = (editor: Editor) => editor.view.dom.dispatchEvent(new CustomEvent(ATTACH_EVENT, { bubbles: true }))\n\n/**\n * The `/` Insert rows the kit offers. Pass the ones an app can perform, in\n * its order, with its own after them; an edit drops Upload and Urgent itself.\n * `file` is the Upload row, named as in a document's `/`.\n */\nexport const commentBoxRows: Readonly<Record<'file' | 'mention' | 'urgent' | 'reference', SlashCommand>> = {\n file: { key: 'insert-file', row: { label: 'Upload' }, keywords: ['attach', 'file', 'picture'], run: askForFile },\n mention: { key: 'insert-mention', row: { label: 'Mention', shortcut: '@' }, keywords: ['@', 'Mention a person'], run: typeTrigger('@') },\n urgent: { key: 'insert-urgent', row: { label: 'Urgent', shortcut: '!@' }, keywords: ['!@', 'Urgent mention'], run: typeTrigger('!@') },\n reference: { key: 'insert-reference', row: { label: 'Reference', shortcut: '[' }, keywords: ['[', 'Reference'], run: typeTrigger('[') },\n}\n\n/** Ctrl/Cmd+Enter sends as Enter does; Escape cancels an edit (an open list, or the selection strip, takes Escape first). */\nconst BoxKeys = Extension.create<{ onEscape: (editor: Editor) => boolean }>({\n name: 'commentBoxKeys',\n addOptions() {\n return { onEscape: () => false }\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Enter': ({ editor }) => (editor.storage as unknown as { composeKeys?: { send: (() => boolean) | null } }).composeKeys?.send?.() ?? false,\n // Open now, with no grace: the first Escape closes a list, the next is a deliberate cancel (suggestionPopup).\n Escape: ({ editor }) => (isSuggestionOpen() ? false : this.options.onEscape(editor as unknown as Editor)),\n }\n },\n})\n\n/** What `removed` still holds of what the draft names; the same set when nothing was forgotten. */\nconst stillNamed = (removed: ReadonlySet<string>, names: readonly string[]): ReadonlySet<string> =>\n [...removed].every((value) => names.includes(value)) ? removed : new Set([...removed].filter((value) => names.includes(value)))\n\nconst SQUARE = <IconSquareRounded size={16} stroke={1.5} className=\"text-text-secondary\" />\nconst SMALL_SQUARE = <IconSquareRounded size={14} stroke={1.5} />\n\n/** The kit's icon for the kind a `nostr:` address names, at a row's or a chip's size; nothing for one that names none. */\nfunction kindIconOf(uri: string | null, size: 14 | 16): ReactNode | undefined {\n const kind = uri ? linkedKindOfReference(uri) : undefined\n return kind ? <LinkedIcon kind={kind} size={size} /> : undefined\n}\n\n/**\n * A `nostr:` address pasted into the box becomes its link at once, as a pasted app URL does (Katerina, 30 Oct): a file\n * (`naddr`) or a message (`nevent`, `note`), drawn by the app's `referenceView`. A person's (`npub`) stays the text\n * it is; `@` names a person.\n */\nconst PastedAddresses = Extension.create({\n name: 'pastedAddresses',\n addPasteRules() {\n const type = this.editor.schema.nodes.reference\n if (!type) return []\n return [\n nodePasteRule({\n find: /nostr:(?:naddr1|nevent1|note1)[023456789acdefghjklmnpqrstuvwxyz]+/g,\n type,\n getAttributes: (match) => ({ uri: match[0] }),\n }),\n ]\n },\n})\n\n/** What the box's editor reads as it runs: the box holding it now, swapped in when a box takes a spare. */\ninterface BoxLive {\n edit?: CommentBoxEdit\n people: readonly MentionPerson[]\n references?: CommentBoxProps['references']\n referencesChanged?: CommentBoxProps['referencesChanged']\n referenceIcon?: CommentBoxProps['referenceIcon']\n /** Takes pasted pictures; false when the box takes no files. */\n attach: (files: File[]) => boolean\n}\n\n/** One editor's link to the box holding it: the live props, and the `/` sections the box refills every render. */\ninterface BoxHold {\n current: BoxLive\n sections: SlashSection[]\n}\n\n/** What an app adds to every box's editor: a spare is built only for these. */\ninterface BoxApp {\n extensions: readonly AnyExtension[]\n referenceView: ComponentType<ReferenceViewProps> | null\n}\n\nconst NO_EXTENSIONS: readonly AnyExtension[] = []\nconst sameApp = (a: BoxApp, b: BoxApp) =>\n a.referenceView === b.referenceView && a.extensions.length === b.extensions.length && a.extensions.every((one, i) => one === b.extensions[i])\n\nfunction boxExtensions(hold: BoxHold, app: BoxApp): AnyExtension[] {\n // The app's icons when it gives them; the kit's for the kind each address names otherwise (Katerina, 30 Oct).\n const own = (uri: string | null, size: 14 | 16) => (hold.current.referenceIcon ? hold.current.referenceIcon(uri) : kindIconOf(uri, size))\n const iconFor = (uri: string | null) => own(uri, 16)\n return [\n // A link drawn as one, as in a document: it read as plain words in the box before (Katerina, 29 Oct).\n BoxKit.configure({ link: { openOnClick: false, HTMLAttributes: LINK_MARK_ATTRIBUTES } }),\n PasteOverWords,\n KeptSelection,\n ComposeKeys,\n BoxKeys.configure({\n onEscape: (ed) => {\n const editing = hold.current.edit\n if (!editing) return false\n // Words selected: the strip is over them, and the first Escape closes it, leaving the caret at their end.\n // The next is the deliberate cancel, as with an open list (Katerina, 21 Oct: the edit box gets the strip).\n const { selection } = ed.state\n if (!selection.empty) {\n ed.commands.setTextSelection(selection.to)\n return true\n }\n editing.onCancel()\n return true\n },\n }),\n PersonMention.configure({ people: () => hold.current.people }),\n // An edit makes nobody urgent (CON-24): `!@` opens no list there, as `/` offers no Urgent.\n UrgentPersonMention.extend({\n addOptions() {\n const parent = this.parent!()\n return { ...parent, suggestion: { ...parent.suggestion, allow: () => !hold.current.edit } }\n },\n }).configure({ people: () => hold.current.people }),\n // A `[` pick draws as the app draws every other link in the box (Katerina, 30 Oct: one chip look in every box).\n CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor: (uri) => own(uri, 14), view: app.referenceView }),\n ReferenceTrigger.configure({\n items: () => [],\n sections: (query) => hold.current.references?.(query) ?? [],\n subscribe: (listener) => hold.current.referencesChanged?.(listener) ?? (() => {}),\n ariaLabel: 'References',\n sectionLabel: 'References',\n icon: SQUARE,\n iconFor,\n }),\n SlashCommands.configure({ sections: hold.sections }),\n ReferenceNode.configure({ view: app.referenceView }),\n ...(app.referenceView ? [PastedAddresses] : []),\n PastedImages.configure({ onImages: (files: File[]) => hold.current.attach(files) }),\n ...app.extensions,\n ]\n}\n\ninterface Held {\n editor: Editor\n hold: BoxHold\n destroyAt?: ReturnType<typeof setTimeout>\n}\n\nfunction buildBox(app: BoxApp, options: Partial<EditorOptions>): Held {\n const hold: BoxHold = { current: { people: [], attach: () => false }, sections: [] }\n return { editor: new Editor({ ...options, extensions: boxExtensions(hold, app) }), hold }\n}\n\n/*\n A box's editor, built ahead, as Peek's composer has been since 4ef41d41:\n building one (schema, commands, view) is the longest single step in drawing\n a box. One is built while the page is idle for the app `keepCommentBoxWarm`\n names, and the next empty box with those extensions takes it and builds the\n next; any other box builds its own on the spot.\n*/\nlet warmApp: BoxApp | null = null\nlet spare: Held | null = null\nlet sparing = false\n\nfunction scheduleSpare() {\n if (!warmApp || spare || sparing || typeof window === 'undefined' || !window.requestIdleCallback) return\n sparing = true\n window.requestIdleCallback(() => {\n sparing = false\n // No autofocus: it would fire on the detached spare. The box that takes it focuses it.\n if (warmApp && !spare) spare = buildBox(warmApp, { autofocus: false })\n })\n}\n\n/** Keeps an editor built ahead for the next empty box given these `extensions` and `referenceView`, so it opens at once. */\nexport function keepCommentBoxWarm(app: { extensions?: readonly AnyExtension[]; referenceView?: ComponentType<ReferenceViewProps> } = {}): void {\n const next = { extensions: app.extensions ?? NO_EXTENSIONS, referenceView: app.referenceView ?? null }\n if (warmApp && sameApp(warmApp, next)) return\n warmApp = next\n spare?.editor.destroy()\n spare = null\n scheduleSpare()\n}\n\n/** `useEditor` with no deps, taking a spare when one fits: built once, given the latest `editorProps`, destroyed when the box goes. */\nfunction useBoxEditor(app: BoxApp, content: JSONContent | undefined, options: Pick<EditorOptions, 'editable' | 'editorProps'>): Held {\n const args = useRef({ app, content, options })\n args.current = { app, content, options }\n const [held, setHeld] = useState(() => {\n const fits = !content && spare && !spare.editor.isDestroyed && warmApp && sameApp(warmApp, app)\n const taken = fits ? spare : null\n if (taken) {\n spare = null\n taken.editor.setOptions(options)\n }\n const one = taken ?? buildBox(app, { ...options, content })\n // A render thrown away never mounts: what it built goes with it. Later than React lets a transition run (5 s).\n one.destroyAt = setTimeout(() => one.editor.destroy(), 10_000)\n scheduleSpare()\n return one\n })\n // Mounted, it is this box's until it unmounts \u2014 and not remounted at once, as in StrictMode.\n useLayoutEffect(() => {\n clearTimeout(held.destroyAt)\n /*\n Shown again after React kept its state but ran this cleanup (a Suspense boundary\n that suspended again, an <Activity> that hid it): the editor went, so build one\n from what the box would open with now \u2014 its draft holds what was typed.\n */\n if (held.editor.isDestroyed) {\n const { app: now, content: opening, options: current } = args.current\n setHeld(buildBox(now, { ...current, content: opening }))\n return\n }\n return () => {\n held.destroyAt = setTimeout(() => held.editor.destroy(), 1)\n }\n }, [held])\n // The attributes are what changes after it is built: the label.\n const props = useRef(options.editorProps)\n props.current = options.editorProps\n const attributes = JSON.stringify(options.editorProps.attributes ?? {})\n useEffect(() => {\n if (!held.editor.isDestroyed) held.editor.setOptions({ editorProps: props.current })\n }, [held, attributes])\n return held\n}\n\n/** Whether the document holds an urgent mention: the box draws its bar while one is in it. */\nconst holdsUrgent = (editor: Editor): boolean => {\n let found = false\n editor.state.doc.descendants((node) => {\n if (node.type.name === 'urgentMention') found = true\n return !found\n })\n return found\n}\n\nlet fileCount = 0\n\n/** The line that takes the box's place where nothing can be written: a lock and why. */\nfunction ClosedLine({ reason, className }: { reason: ReactNode; className?: string }) {\n return (\n <Card fill=\"inset\" className={cn('flex items-start gap-3 px-4 py-3', className)}>\n <IconLock size={16} stroke={1.5} className=\"mt-0.5 shrink-0 text-text-muted\" aria-hidden />\n <p className=\"text-body-2 text-text-secondary\">{reason}</p>\n </Card>\n )\n}\n\nexport function CommentBox(props: CommentBoxProps) {\n const { closed, className } = props\n /*\n Closed from the start (an archived file, signed out), nothing is written here: the line alone, and no editor is\n built to say it. Once opened, the box keeps its editor through a close, so what was written comes back with it.\n */\n const [built, setBuilt] = useState(!closed)\n if (!closed && !built) setBuilt(true)\n if (closed && !built) return <ClosedLine reason={closed.reason} className={className} />\n return <OpenCommentBox {...props} />\n}\n\nfunction OpenCommentBox({\n people,\n references,\n referencesChanged,\n referenceIcon,\n insert = [],\n code = 'block',\n send,\n under,\n about,\n showsAtOnce = false,\n label,\n placeholder,\n draft,\n edit,\n upload,\n accept,\n closed,\n referenceView,\n extensions = NO_EXTENSIONS,\n autoFocus,\n onSent,\n onRefused,\n marked,\n onEditor,\n className,\n}: CommentBoxProps) {\n const [files, setFiles] = useState<BoxFile[]>(edit?.files ?? [])\n const [sending, setSending] = useState(false)\n // The plain reason, never the relay's words (ONE-4).\n const [refused, setRefused] = useState<string | null>(edit?.refused ? refusalReason(edit.refused) : null)\n // What shows under the box, and what \u2715 took off.\n const [reading, setReading] = useState<BoxUnderRead | undefined>(undefined)\n const [removed, setRemoved] = useState<ReadonlySet<string>>(() => new Set())\n const picker = useRef<HTMLInputElement>(null)\n const root = useRef<HTMLDivElement>(null)\n // The latest props, for callbacks made once.\n const latest = useRef({ edit, upload, draft, under })\n latest.current = { edit, upload, draft, under }\n const save = useRef<() => boolean>(() => false)\n\n const attachFiles = useCallback((picked: File[]): boolean => {\n const uploadOne = latest.current.upload\n if (!uploadOne || (latest.current.edit && !latest.current.edit.writesFiles)) return false\n for (const file of picked) {\n fileCount += 1\n const id = `file-${fileCount}`\n const card = { id, name: file.name, size: file.size, contentType: file.type }\n // Over the server's limit for its type: said on its card before anything uploads (Miky, 4 Nov).\n const over = tooLarge(file)\n if (over) {\n setFiles((all) => [...all, { ...card, state: 'failed', note: over }])\n continue\n }\n setFiles((all) => [...all, { ...card, state: 'uploading' }])\n const failed = (reason: unknown) => setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'failed', note: uploadRefusal(reason, file) } : f)))\n uploadOne(file).then((answer) => {\n if (!answer.accepted) return failed(answer.reason)\n setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'ready', value: answer.value } : f)))\n }, failed)\n }\n return true\n }, [])\n\n // An edit can add a file, in every app (Miky, 26 Oct, PEEKM-4) whose save writes it, but makes nobody urgent (CON-24); no upload, no File.\n const takesFiles = !!upload && (!edit || !!edit.writesFiles)\n const rows = insert.filter((c) => !(!takesFiles && c.key === commentBoxRows.file.key) && !(edit && c.key === commentBoxRows.urgent.key))\n const { editor, hold } = useBoxEditor({ extensions, referenceView: referenceView ?? null }, edit?.body ?? draft?.read(), {\n editable: !closed,\n editorProps: { attributes: { class: COMPOSE_EDITOR_CLASSES, role: 'textbox', 'aria-multiline': 'true', 'aria-label': label } },\n })\n // The editor's callbacks are made once, with the editor: they read this box's latest props through its hold.\n hold.current = { edit, people, references, referencesChanged, referenceIcon, attach: attachFiles }\n // `/` reads its sections each time it opens, from this one array: refilled every render, so a row that\n // comes or goes with `upload`, `insert` or `code` after the box opened is offered as it is now.\n hold.sections.splice(0, hold.sections.length, formatSection(code), ...(rows.length > 0 ? [{ label: 'Insert', commands: rows }] : []))\n\n // The bar down the text's left edge, while an urgent mention or the app's own mark is in the box.\n const [marking, setMarking] = useState(false)\n const markedBy = useRef(marked)\n markedBy.current = marked\n // Before paint: an edit or a draft opening with an urgent mention draws its bar in its first frame.\n useLayoutEffect(() => {\n const read = () => setMarking(holdsUrgent(editor) || !!markedBy.current?.(editor))\n read()\n editor.on('update', read)\n return () => {\n editor.off('update', read)\n }\n }, [editor])\n\n const handOut = useRef(onEditor)\n handOut.current = onEditor\n useEffect(() => {\n handOut.current?.(editor)\n return () => handOut.current?.(null)\n }, [editor])\n\n // Whether the edit's words are gone: Save waits for something to save, and a refusal says the changes are in the box only while they are.\n const editing = !!edit\n const [wordless, setWordless] = useState(() => editing && !!editor && isEmpty(editor))\n useEffect(() => {\n if (!editor || !editing) return\n const read = () => setWordless(isEmpty(editor))\n read()\n editor.on('update', read)\n return () => {\n editor.off('update', read)\n }\n }, [editor, editing])\n\n // Drafts: every change is kept, and an empty box is no draft.\n useEffect(() => {\n if (!editor || edit) return\n const keep = () => {\n const kept = latest.current.draft\n if (!kept) return\n if (isEmpty(editor)) kept.clear()\n else kept.write(editor.getJSON())\n }\n editor.on('update', keep)\n return () => {\n editor.off('update', keep)\n }\n }, [editor, edit])\n\n // What shows under the box, read on every change and whenever the app's answers change.\n const reads = !!under\n useEffect(() => {\n if (!editor || !reads) {\n setReading(undefined)\n return\n }\n const read = () => {\n const now = latest.current.under?.read(editor.getJSON())\n setReading(now)\n setRemoved((was) => stillNamed(was, now?.names ?? []))\n }\n read()\n editor.on('update', read)\n const unsubscribe = latest.current.under?.changed?.(read)\n return () => {\n editor.off('update', read)\n unsubscribe?.()\n }\n }, [editor, reads])\n\n // What goes with a send or a save: read from what is sent, minus what \u2715 took off.\n const underOf = useCallback(\n (body: JSONContent): BoxSentUnder => {\n const card = latest.current.under?.read(body).card?.value\n return card && !removed.has(card) ? { card } : {}\n },\n [removed],\n )\n\n useEffect(() => {\n editor?.setEditable(!closed && !sending)\n }, [editor, closed, sending])\n\n useEffect(() => {\n if (!editor || !(autoFocus || edit)) return\n const frame = requestAnimationFrame(() => editor.commands.focus('end'))\n return () => cancelAnimationFrame(frame)\n // Once, as the box opens.\n }, [editor])\n\n // At a thread's foot in a ConversationLayout: the caret, each time the thread opens, with no scroll to it.\n const caret = useContext(caretOnOpen)\n useEffect(() => {\n if (!editor || !caret) return\n const frame = requestAnimationFrame(() => editor.commands.focus('end', { scrollIntoView: false }))\n return () => cancelAnimationFrame(frame)\n }, [editor, caret])\n\n // `/` \u2192 File asks for a file the way the paperclip does.\n useEffect(() => {\n const box = root.current\n if (!box || !takesFiles) return\n const ask = () => picker.current?.click()\n box.addEventListener(ATTACH_EVENT, ask)\n return () => box.removeEventListener(ATTACH_EVENT, ask)\n }, [takesFiles])\n\n const uploading = files.some((f) => f.state === 'uploading')\n // A file that did not upload holds Send until its \u2715 takes it off, so it is never sent without it unnoticed.\n const failed = files.filter((f) => f.state === 'failed').length\n const ready = files.some((f) => f.state === 'ready')\n\n // In a ConversationLayout's box: the reader's own comment brings the comments down to it as it is drawn.\n const layout = useContext(sendsInLayout)\n const go = useCallback(\n (ed: Editor): boolean => {\n layout?.sending()\n const body = ed.getJSON()\n const sent = files.filter((f) => f.state === 'ready')\n const sentUnder = underOf(body)\n setRefused(null)\n const answered = (answer: Promise<SendAnswer>) => answer.catch((reason: unknown): SendAnswer => ({ accepted: false, reason }))\n if (showsAtOnce) {\n // Shown at once: the box empties now (the send box clears it); a refusal puts the words back above anything written since,\n // and what \u2715 took off with them.\n const took = removed\n setFiles((all) => all.filter((f) => f.state !== 'ready'))\n draft?.clear()\n onSent?.(body, sent, sentUnder)\n void answered(send(body, sent, sentUnder)).then((answer) => {\n if (answer.accepted) return\n layout?.refused()\n onRefused?.()\n if (ed.isDestroyed) {\n // The box went away before the answer: the words wait in its draft.\n draft?.write(body)\n return\n }\n if (isEmpty(ed)) ed.commands.setContent(body)\n else ed.commands.insertContentAt(0, body.content ?? [])\n ed.commands.focus('end')\n setRemoved((now) => new Set([...now, ...took]))\n setFiles((all) => [...sent, ...all])\n setRefused(sendRefusal(answer.reason))\n })\n return true\n }\n // Held: the words stay, shut, until the relay answers.\n setSending(true)\n void answered(send(body, sent, sentUnder)).then((answer) => {\n setSending(false)\n if (!answer.accepted) {\n layout?.refused()\n setRefused(sendRefusal(answer.reason))\n return\n }\n if (!ed.isDestroyed) ed.commands.clearContent(true)\n setRemoved(new Set())\n setFiles((all) => all.filter((f) => !sent.includes(f)))\n draft?.clear()\n onSent?.(body, sent, sentUnder)\n })\n return false\n },\n [files, removed, underOf, showsAtOnce, send, draft, onSent, onRefused, layout],\n )\n\n // An edit holding nothing, no words and no file, cannot be saved: Save is off, and nothing is said (Miky, 4 Nov). One\n // emptied of its words that keeps a file is saved, in every app.\n const holdsNothing = !!edit && wordless && files.length === 0\n save.current = () => {\n if (!editor || !edit || sending || uploading || failed > 0 || (isEmpty(editor) && files.length === 0)) return true\n setRefused(null)\n setSending(true)\n const body = editor.getJSON()\n void edit\n .onSave(body, files, underOf(body))\n .catch((reason: unknown): SendAnswer => ({ accepted: false, reason }))\n .then((answer) => {\n setSending(false)\n if (!answer.accepted) setRefused(refusalReason(answer.reason))\n })\n return true\n }\n\n // Enter and Ctrl/Cmd+Enter save an edit; the send box wires them itself.\n useEffect(() => {\n if (!editor || !edit) return\n const storage = (editor.storage as unknown as { composeKeys?: { send: (() => boolean) | null } }).composeKeys\n if (!storage) return\n storage.send = () => save.current()\n return () => {\n storage.send = null\n }\n }, [editor, edit])\n\n if (closed) return <ClosedLine reason={closed.reason} className={className} />\n\n const fileCards =\n files.length > 0 ? (\n <>\n {files.map((f) => (\n <AttachmentCard\n key={f.id}\n pending\n name={f.name}\n size={f.size}\n contentType={f.contentType}\n state={f.state}\n note={f.note}\n onRemove={() => setFiles((all) => all.filter((one) => one !== f))}\n />\n ))}\n </>\n ) : undefined\n\n // In the box, under the text with the files (Katerina, 29 Oct: \"the file's \u2715 and inside the box\"): the files, then\n // the card with its \u2715 and the live parts on a line of their own (none in an edit, which carries none). On the files'\n // fill, the card's values as words until it is sent (`inTheBox`).\n const card = reading?.card && !removed.has(reading.card.value) ? reading.card : undefined\n const parts = edit ? [] : (reading?.parts ?? [])\n const attached =\n card || parts.length > 0 ? (\n <>\n {fileCards}\n <inTheBox.Provider value>\n {/* min-w-0: a card with a long title would otherwise be as wide as its title, past the box's edge (29 Oct). */}\n <div data-box-under className=\"flex min-w-0 basis-full flex-col gap-2\">\n {card && <AttachedCard onRemove={() => setRemoved((was) => new Set([...was, card.value]))}>{card.view}</AttachedCard>}\n {parts.map((part) => (\n <Fragment key={part.key}>{part.view}</Fragment>\n ))}\n </div>\n </inTheBox.Provider>\n </>\n ) : (\n fileCards\n )\n\n const refusedLine = refused && (\n <FieldLine tone=\"error\">\n {edit ? `Not saved: ${refused}.${holdsNothing ? '' : ' Your changes are still in the box.'}` : `Not sent: ${refused}. Your text is back in the box.`}\n </FieldLine>\n )\n\n const onDrop = (event: DragEvent<HTMLDivElement>) => {\n const dropped = Array.from(event.dataTransfer?.files ?? [])\n if (dropped.length === 0 || !takesFiles) return\n event.preventDefault()\n attachFiles(dropped)\n }\n\n const fileLines = (\n <>\n {uploading && !sending && <FieldLine>Uploading\u2026 {edit ? 'Save' : 'Send'} waits for the file.</FieldLine>}\n {failed > 0 && !uploading && !sending && (\n <FieldLine>\n {failed === 1 ? 'Remove the file that did not upload' : 'Remove the files that did not upload'} to {edit ? 'save' : 'send'}.\n </FieldLine>\n )}\n </>\n )\n\n if (edit) {\n // No paperclip: the edit box shows only its keys (Decided 2026-10-17); a file comes by `/` \u2192 Upload, a paste or a drop.\n return (\n <div ref={root} className={cn('flex flex-col gap-1', className)} onDragOver={takesFiles ? (e) => e.preventDefault() : undefined} onDrop={onDrop}>\n <BoxFrame\n editor={editor}\n marked={marking}\n // The same strip as the send box: writing and editing work the same way (Katerina, 21 Oct).\n selection={{ link: true }}\n ring={false}\n attachments={attached}\n className={cn(sending && '[&_.ProseMirror]:text-text-muted')}\n footer={\n // No keys written under the edit box: Cancel and Save say it (Katerina, 1 November).\n <div className=\"flex items-center justify-end gap-2\">\n <div className=\"flex shrink-0 items-center gap-2\">\n <Button variant=\"outlined\" size=\"small\" onClick={edit.onCancel}>\n Cancel\n </Button>\n <Button variant=\"primary\" size=\"small\" disabled={uploading || failed > 0 || sending || holdsNothing} onClick={() => save.current()}>\n Save\n </Button>\n </div>\n </div>\n }\n />\n {takesFiles && <FilePicker ref={picker} multiple accept={accept} onPick={attachFiles} />}\n {sending && <FieldLine>Saving\u2026</FieldLine>}\n {fileLines}\n {refusedLine}\n </div>\n )\n }\n\n return (\n <div ref={root} className={cn('flex flex-col gap-1', className)} onDragOver={upload ? (e) => e.preventDefault() : undefined} onDrop={onDrop}>\n {about && (\n // The whole strip, its \u2715 in it, on the inset fill the closed box's line has (Katerina, 3 November: B); 8px above\n // the box with the column's 4px. 36px tall with or without \u2715, so the box does not move when an app offers none.\n <Card data-box-about fill=\"inset\" className=\"mb-1 flex min-h-9 items-center gap-2 py-1 pl-3 pr-1\">\n <div className=\"min-w-0 flex-1\">{about.view}</div>\n {about.remove && (\n <IconButton tooltip={about.remove.label} aria-label={about.remove.label} onClick={about.remove.onRemove}>\n <IconX size={16} stroke={1.5} />\n </IconButton>\n )}\n </Card>\n )}\n <SendBox\n editor={editor}\n onSend={go}\n placeholder={placeholder}\n tools={\n upload ? (\n <ToolbarButton tooltip=\"Attach a file\" aria-label=\"Attach a file\" disabled={sending} onClick={() => picker.current?.click()}>\n <IconPaperclip size={16} stroke={1.5} />\n </ToolbarButton>\n ) : undefined\n }\n attachments={attached}\n ready={ready}\n marked={marking}\n holding={uploading || failed > 0 || sending}\n selection={{ link: true }}\n className={cn(sending && '[&_[data-composer-editor]]:text-text-muted')}\n />\n {upload && <FilePicker ref={picker} multiple accept={accept} onPick={attachFiles} />}\n {sending && <FieldLine>Sending\u2026</FieldLine>}\n {fileLines}\n {refusedLine}\n </div>\n )\n}\n", "/**\n * refusals, the one set of words every app says when a send, an edit, a\n * reaction or a file is refused (ONE-4).\n *\n * A refusal comes from the relay (`invalid: \u2026`, `restricted: \u2026`, an HTTP body),\n * from Estiva ID, from the builders' own checks (`content is N bytes, max M`),\n * from the network, or from the app itself. Whatever it was, a person reads\n * one plain reason for its cause, the same in Peek, Ship and Leaf, and never\n * the relay's words: those go to the console. The comment box and the cards\n * put the reason in their sentence (\"Not sent: <reason>. Your text is back in\n * the box.\"), so a reason is lower case and ends with no full stop.\n *\n * An app with a cause of its own hands `{ cause }` rather than a sentence, so\n * its words are these too. A file's own words (`uploadRefusal`) are a whole\n * line on its card, and `tooLarge` stops a file over the relay's limit before\n * it uploads (Miky, 4 Nov: the server's limits, checked in every app first).\n */\n\n/** Why something was refused, as far as a person needs to know. */\nexport type RefusalCause =\n | 'too-long'\n | 'gone'\n | 'no-access'\n | 'archived'\n | 'busy'\n | 'clock'\n | 'signed-out'\n | 'unknown'\n\n/**\n * Each cause's reason, put in a sentence by the box or the card. `gone` is\n * what the relay says for an edit or a reaction on a message that was deleted\n * or that you can no longer write beside: it does not say which.\n */\nexport const REFUSAL_REASONS: Readonly<Record<RefusalCause, string>> = {\n 'too-long': 'it is too long',\n gone: 'this message was deleted, or you can no longer write here',\n 'no-access': 'you can no longer write here',\n archived: 'this team is archived',\n busy: 'too many at once, try again in a moment',\n clock: 'your computer\u2019s clock is wrong; set it and try again',\n 'signed-out': 'you are signed out; sign in again',\n unknown: 'something went wrong, try again',\n}\n\n/** The text a refusal carries: a string, an `Error`'s message, or `{ error }` / `{ message }` / `{ reason }`, one JSON body deep. */\nfunction textOf(reason: unknown): string {\n if (reason == null) return ''\n if (typeof reason === 'string') {\n const json = reason.trim()\n if (json.startsWith('{')) {\n try {\n return textOf(JSON.parse(json)) || reason\n } catch {\n return reason\n }\n }\n return reason\n }\n if (reason instanceof Error) return textOf(reason.message)\n if (typeof reason === 'object') {\n const r = reason as Record<string, unknown>\n for (const key of ['error', 'message', 'reason']) {\n const value = r[key]\n if (typeof value === 'string') return textOf(value)\n if (value && typeof value === 'object') return textOf(value)\n }\n }\n return String(reason)\n}\n\nconst CAUSES = new Set<string>(Object.keys(REFUSAL_REASONS))\n\n/*\n In order: the first that matches is the cause. Scope and identity before\n `restricted:`, which also prefixes \"insufficient scope\". Each reason above\n maps back to its own cause, so a reason passed on twice stays the same.\n\n Words, because the relay sends no reason code yet (SPEC: \"until then a\n refusal is its sentence alone\"). When the TEA issue \"When the server says\n no, every app knows why\" adds them, `refusalCause` reads the code first and\n these rules stay only for a refusal that carries none.\n why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-refusal-starts-with-a-reason-code-every-app-reads.md\n*/\nconst RULES: readonly [RegExp, RefusalCause][] = [\n [/content (is \\d+ bytes, max|exceeds maximum size)|too long/i, 'too-long'],\n [/rate-limited|quota|too many|too busy|relay is busy|admission|\\b429\\b|concurrency/i, 'busy'],\n [/timestamp too far|clock/i, 'clock'],\n [/auth-required|insufficient scope|does not match authenticated|signed out|sign in|\\b401\\b|token_rejected|session_expired/i, 'signed-out'],\n [/archived/i, 'archived'],\n [/target (event )?not found|not (editable|deletable) by you|was deleted|no longer on this page/i, 'gone'],\n [/^(restricted|blocked):|not a (channel |relay )?member|only members|no longer (post|write)|banned|timed out until|writes are fenced|\\b403\\b/i, 'no-access'],\n]\n\n/** What a refusal comes to; `{ cause }` is taken as it is. */\nexport function refusalCause(reason: unknown): RefusalCause {\n if (reason && typeof reason === 'object' && 'cause' in reason) {\n const cause = (reason as { cause: unknown }).cause\n if (typeof cause === 'string' && CAUSES.has(cause)) return cause as RefusalCause\n }\n const text = textOf(reason)\n for (const [rule, cause] of RULES) if (rule.test(text)) return cause\n return 'unknown'\n}\n\n/** The plain reason for any refusal, to say after \"Not sent:\", \"Not saved:\" or \"Not reacted:\". */\nexport function refusalReason(reason: unknown): string {\n return REFUSAL_REASONS[refusalCause(reason)]\n}\n\n/** Why a file did not upload, as far as a person needs to know. */\nexport type UploadCause = 'too-large' | 'type' | 'unreadable' | 'busy' | 'signed-out' | 'no-access' | 'unknown'\n\nconst MB = 1024 * 1024\n\n/**\n * The relay's size limits (buzz `BUZZ_MAX_*_BYTES`, read back on production on\n * 4 Nov): a GIF 10 MB, another picture 50 MB, anything else 100 MB, since\n * Cloudflare refuses a larger body before the relay sees it (a video's 500 MB\n * is never reached). Cloudflare's 100 MB is taken as decimal, the lower\n * reading, so nothing that passes here is turned away there.\n */\nexport const UPLOAD_LIMITS = { gif: 10 * MB, image: 50 * MB, other: 100_000_000 } as const\n\n/** The most a file of this type may be, in bytes. */\nexport function uploadLimit(type: string | undefined): number {\n const t = (type ?? '').toLowerCase()\n if (t === 'image/gif') return UPLOAD_LIMITS.gif\n if (t.startsWith('image/')) return UPLOAD_LIMITS.image\n return UPLOAD_LIMITS.other\n}\n\n// Whole MB either way: 10,485,760 bytes and 100,000,000 bytes both say what the limit is called.\nconst tooLargeLine = (bytes: number) => `Too large: the most is ${bytes % MB === 0 ? bytes / MB : Math.round(bytes / 1e6)} MB`\n\n/** The line for a file over its limit, said before it uploads; undefined when it fits. */\nexport function tooLarge(file: { size: number; type?: string }): string | undefined {\n const limit = uploadLimit(file.type)\n return file.size > limit ? tooLargeLine(limit) : undefined\n}\n\nconst UPLOAD_LINES: Readonly<Record<Exclude<UploadCause, 'too-large'>, string>> = {\n type: 'This type of file can\u2019t be added',\n unreadable: 'This file could not be read',\n busy: 'Too many at once, try again in a moment',\n 'signed-out': 'Sign in again',\n 'no-access': 'You can no longer add files here',\n unknown: 'Could not upload, try again',\n}\n\n/**\n * The line on a file's card when its upload was refused: from protocol's\n * `upload failed: <status> <body>`, any other error, or `{ cause }`. A 413\n * names the limit the relay gave, or the type's own when Cloudflare answered.\n */\nexport function uploadRefusal(reason: unknown, file?: { type?: string }): string {\n if (reason && typeof reason === 'object' && 'cause' in reason) {\n const cause = (reason as { cause: unknown }).cause\n if (cause === 'too-large') return tooLargeLine(uploadLimit(file?.type))\n if (typeof cause === 'string' && Object.hasOwn(UPLOAD_LINES, cause)) return UPLOAD_LINES[cause as keyof typeof UPLOAD_LINES]\n }\n const raw = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : textOf(reason)\n const status = Number(/upload failed:\\s*(\\d{3})/i.exec(raw)?.[1] ?? 0)\n const said = textOf(raw.replace(/^.*?upload failed:\\s*\\d{3}\\s*/is, ''))\n if (status === 413 || /file too large/i.test(said)) {\n const max = Number(/max (\\d+)\\)?/i.exec(said)?.[1] ?? 0)\n if (/dimensions/i.test(said)) return UPLOAD_LINES.unreadable\n return tooLargeLine(max || uploadLimit(file?.type))\n }\n if (status === 415 || /content type|unsupported container/i.test(said)) return UPLOAD_LINES.type\n if (status === 422 || /metadata|invalid image|duration|resolution/i.test(said)) return UPLOAD_LINES.unreadable\n if (status === 429 || /rate limit|concurrency/i.test(said)) return UPLOAD_LINES.busy\n if (status === 401 || /authentication failed|signed out/i.test(said)) return UPLOAD_LINES['signed-out']\n if (status === 403) return UPLOAD_LINES['no-access']\n return UPLOAD_LINES.unknown\n}\n", "import type { ComponentType, MouseEvent } from 'react'\nimport { Extension, InputRule, Node, type Editor } from '@tiptap/core'\nimport { DOMSerializer, type Node as ProseMirrorNode, type Slice } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state'\nimport { Mapping, ReplaceAroundStep } from '@tiptap/pm/transform'\nimport { Decoration, DecorationSet, type EditorView, type NodeView } from '@tiptap/pm/view'\nimport { NodeViewWrapper, ReactNodeViewRenderer, ReactRenderer, type ReactNodeViewProps } from '@tiptap/react'\nimport { Checkbox, type CheckboxProps } from './Checkbox'\nimport { calloutLook } from './RichText'\nimport { placeOf, type LinkPlace } from './LinkPlaces'\nimport { referenceMenuClick } from './ReferenceMenu'\nimport { isSuggestionOpen } from './suggestionPopup'\n\n/*\n * The four nodes an editor of a block document needs that a stock schema does\n * not have (SPEC \u00A713.3) \u2014 moved here from Ship's `editorSchema.tsx` (RIC-14,\n * SHI-2) when Peek became the second editor of the same documents (MAN-9).\n *\n * They are one half of a pair. The other half is `@estiva-app/protocol`'s\n * `toEditorDocument` / `fromEditorDocument`, which turn a stored document into\n * the JSON these nodes read and back: the node names (`unknownBlock`,\n * `reference`, `attachment`) and the `blockId` attribute are that translation's,\n * and must not drift from it. This package does not import protocol, as\n * `RichText` does not: the translation hands over everything a view draws.\n *\n * Everything else a document can contain is already a ProseMirror node of the\n * same name \u2014 StarterKit's and TableKit's \u2014 which is why this file is short.\n */\n\n/**\n * The block types \u00A713.3 puts an id on, as the editor's node names \u2014\n * protocol's `EDITOR_BLOCK_TYPES`, less `unknownBlock`, which declares its own.\n */\nconst BLOCK_TYPES = [\n 'paragraph',\n 'heading',\n 'bulletList',\n 'orderedList',\n 'listItem',\n 'blockquote',\n 'codeBlock',\n 'horizontalRule',\n // A table and everything inside it (UIG-18): a row or a cell whose id was\n // re-minted on each save would detach any comment anchored to it.\n 'table',\n 'tableRow',\n 'tableHeader',\n 'tableCell',\n // Without this an attachment's id is re-minted on every save, and every\n // comment anchored to it stops resolving.\n 'attachment',\n]\nconst BLOCK_TYPE_SET = new Set(BLOCK_TYPES)\n\n/** protocol's `newBlockId`: six random bytes as hex. */\nfunction newBlockId(): string {\n return Array.from(crypto.getRandomValues(new Uint8Array(6)), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** Whether anything typed or inserted is inside \u2014 protocol's `holdsText`. An empty paragraph is not; a lone line break is. */\nfunction holdsText(node: ProseMirrorNode): boolean {\n let found = false\n node.descendants((child) => {\n if (found) return false\n if ((child.isText && child.text !== '') || child.type.name === 'hardBreak' || child.type.name === 'reference') found = true\n return !found\n })\n return found\n}\n\ninterface Claim {\n pos: number\n node: ProseMirrorNode\n /** An unknown block: the translation hands its source back untouched, so re-minting it here would be undone on save. */\n fixed: boolean\n}\n\n/** Every block that claims an id, by id, in document order. */\nfunction claimsIn(doc: ProseMirrorNode): Map<string, Claim[]> {\n const claims = new Map<string, Claim[]>()\n doc.descendants((node, pos, parent) => {\n const fixed = node.type.name === 'unknownBlock'\n if (!fixed && !BLOCK_TYPE_SET.has(node.type.name)) return\n // A list inside a list item is no block (MAN-13): an id it arrived with is\n // cleared, never a claim that could take a real block's.\n if (parent?.type.name === 'listItem' && LISTS.has(node.type.name)) return\n const id = node.attrs.blockId\n if (typeof id !== 'string' || id === '') return\n const copies = claims.get(id)\n if (copies) copies.push({ pos, node, fixed })\n else claims.set(id, [{ pos, node, fixed }])\n })\n return claims\n}\n\n/**\n * The copy the block that was there before carried on into: where the start\n * of its content landed. Enter at the very start pushes that content into the\n * lower half; a split anywhere else leaves it in the upper; a pasted copy,\n * above or below, never moves it out of the original.\n */\nfunction carriedOn(copies: Claim[], before: Claim, mapping: Mapping): Claim | undefined {\n if (before.node.isLeaf) {\n const at = mapping.map(before.pos, 1)\n return copies.find((c) => c.pos === at)\n }\n const at = mapping.map(textStart(before), 1)\n return copies.find((c) => c.pos < at && at < c.pos + c.node.nodeSize)\n}\n\n/** The start of a block's text, inside the paragraph a list item or quote wraps it in. */\nfunction textStart({ pos, node }: { pos: number; node: ProseMirrorNode }): number {\n let start = pos + 1\n if (!node.isTextblock) {\n let found = false\n node.descendants((child, at) => {\n if (found) return false\n if (child.isTextblock) {\n start = pos + 1 + at + 1\n found = true\n }\n return !found\n })\n }\n return start\n}\n\n/**\n * Where a block claims an id another block keeps \u2014 see {@link BlockId}. An\n * unknown block always keeps its id; otherwise the copy the original carried\n * on into, and failing that protocol's rule: the first that holds text, or\n * the first.\n */\nfunction repeatedBlockIds(doc: ProseMirrorNode, before: ProseMirrorNode, mapping: Mapping): number[] {\n const claims = claimsIn(doc)\n let previous: Map<string, Claim[]> | undefined\n const losers: number[] = []\n for (const [id, copies] of claims) {\n if (copies.length < 2) continue\n previous ??= claimsIn(before)\n const original = previous.get(id)?.[0]\n const owner =\n copies.find((c) => c.fixed) ??\n (original && carriedOn(copies, original, mapping)) ??\n copies.find((c) => holdsText(c.node)) ??\n copies[0]\n for (const copy of copies) if (copy !== owner && !copy.fixed) losers.push(copy.pos)\n }\n return losers\n}\n\n/**\n * The blocks a save turns into blocks \u2014 exactly what protocol's\n * `blockFromEditor` walks \u2014 so a list, a table and its rows and cells are\n * walked into, and a list item or a quote is not: the save flattens their\n * paragraph wrappers into inline runs, so an id there would be dropped.\n */\nconst BLOCK_CONTAINERS = new Set(['bulletList', 'orderedList', 'table', 'tableRow', 'tableHeader', 'tableCell'])\n\n/** The wrappers the save flattens: their paragraphs become inline runs of theirs. */\nconst FLATTENED = new Set(['listItem', 'blockquote'])\n\n/**\n * The lists Tab puts inside a list item (MAN-13). \u00A713.3 keeps a list flat and\n * marks an item's depth, so the save walks into such a list for its items and\n * writes no block for the list itself: its items get ids, it gets none.\n */\nconst LISTS = new Set(['bulletList', 'orderedList'])\n\n/** The lists inside a list item, with where each starts. */\nfunction innerLists(item: ProseMirrorNode, pos: number): { pos: number; node: ProseMirrorNode }[] {\n const out: { pos: number; node: ProseMirrorNode }[] = []\n item.forEach((child, offset) => {\n if (LISTS.has(child.type.name)) out.push({ pos: pos + 1 + offset, node: child })\n })\n return out\n}\n\nconst idOf = (node: ProseMirrorNode): string | undefined => {\n const id = node.attrs.blockId\n return typeof id === 'string' && id !== '' ? id : undefined\n}\n\n/** Every block the save turns into a block, in document order. */\nfunction addressedBlocks(doc: ProseMirrorNode): { pos: number; node: ProseMirrorNode }[] {\n const out: { pos: number; node: ProseMirrorNode }[] = []\n const visit = (node: ProseMirrorNode, pos: number) => {\n if (!BLOCK_TYPE_SET.has(node.type.name)) return\n out.push({ pos, node })\n if (BLOCK_CONTAINERS.has(node.type.name)) node.forEach((child, offset) => visit(child, pos + 1 + offset))\n if (node.type.name === 'listItem') {\n for (const list of innerLists(node, pos)) list.node.forEach((child, offset) => visit(child, list.pos + 1 + offset))\n }\n }\n doc.forEach((node, offset) => visit(node, offset))\n return out\n}\n\n/** Where a block the save would give an id has none, so it would get a new one on every save. */\nfunction unnamedBlocks(doc: ProseMirrorNode): number[] {\n return addressedBlocks(doc)\n .filter((b) => idOf(b.node) === undefined)\n .map((b) => b.pos)\n}\n\n/**\n * Where a paragraph inside a list item or a quote claims an id, or a list\n * inside a list item does \u2014 both of which the save drops.\n */\nfunction hiddenIds(doc: ProseMirrorNode): number[] {\n const out: number[] = []\n doc.descendants((node, pos) => {\n if (!FLATTENED.has(node.type.name)) return\n node.forEach((child, offset) => {\n const inner = child.isTextblock || (node.type.name === 'listItem' && LISTS.has(child.type.name))\n if (inner && idOf(child) !== undefined) out.push(pos + 1 + offset)\n })\n })\n return out\n}\n\n/**\n * The id each block a wrap or a lift brought in takes over \u2014 see\n * {@link BlockId}. An id the save addressed before the change and does not\n * now goes to the innermost new block its text was carried into: the quote or\n * the list item around a paragraph, or the paragraph lifted out of one.\n * A block the change deleted hands nothing on. What it asks is whether the\n * block's own opening survived, the token left of its text, not its first\n * character: the `/` menu and a typed `> ` or `- ` delete what was typed at\n * the very start of the text in the same change as the wrap.\n */\nfunction handedOver(doc: ProseMirrorNode, before: ProseMirrorNode, mapping: Mapping, unnamed: number[]): Map<number, string> {\n const out = new Map<number, string>()\n if (unnamed.length === 0) return out\n const now = new Set(addressedBlocks(doc).map((b) => idOf(b.node)))\n // By where their text starts, and of a list and its item around the same text, the item first.\n const gone = addressedBlocks(before)\n .filter((b) => !b.node.isLeaf && idOf(b.node) !== undefined && !now.has(idOf(b.node)))\n .map((b) => ({ ...b, start: textStart(b) }))\n .sort((a, b) => a.start - b.start || b.pos - a.pos)\n for (const old of gone) {\n const id = idOf(old.node)!\n const { pos: at, deleted } = mapping.mapResult(old.start, -1)\n if (deleted) continue\n let inner: number | undefined\n for (const pos of unnamed) {\n if (out.has(pos)) continue\n if (pos < at && at < pos + doc.nodeAt(pos)!.nodeSize && (inner === undefined || pos > inner)) inner = pos\n }\n if (inner !== undefined) {\n out.set(inner, id)\n now.add(id)\n }\n }\n return out\n}\n\n/**\n * Whether a change could have made a repeat or a block without an id: only a\n * step that brings in blocks can, or one that wraps or lifts them \u2014 lifting\n * the paragraph out of a quote or a one-item list brings in nothing, yet\n * leaves a block the save addresses with the wrapper's missing id. Typing,\n * deleting and marks do neither, so most keystrokes skip the walk.\n */\nfunction bringsInBlocks(transactions: readonly Transaction[]): boolean {\n return transactions.some((tr) =>\n tr.steps.some((step) => {\n if (step instanceof ReplaceAroundStep) return true\n const slice = (step as { slice?: Slice }).slice\n let blocks = false\n slice?.content.forEach((node) => {\n if (node.isBlock) blocks = true\n })\n return blocks\n }),\n )\n}\n\n/**\n * `id` on every block, carried as the `blockId` attribute.\n *\n * A global attribute rather than one per node type, because \u00A713.3 puts an id\n * on **every** block and a type that quietly lacked one would mint a fresh id\n * on every save \u2014 detaching each anchored comment on it (RFC 0.4 \u00A76) with\n * nothing on screen to say so.\n *\n * Rendered as `data-block-id`, which is what `RichText` already emits, so the\n * reading and the editing surface address a block the same way.\n *\n * **A split gives the new half its own id, the moment it happens** (MAN-10).\n * ProseMirror copies a split node's attrs to both halves, so Enter leaves two\n * blocks claiming one id. Enter at the very start of a paragraph puts the\n * copy *above* it \u2014 and once something is typed there, nothing at save time\n * can tell which half was the original, so protocol's `fromEditorDocument`\n * gave the id, and every comment anchored to it, to the new line. Settled\n * here instead, in the same transaction, where the change itself says which\n * copy the original carried on into \u2014 so a copy pasted above a block does\n * not take its id either. The others get fresh ids. `fromEditorDocument`\n * keeps its own rule (the copy that holds text) as the backstop for an\n * editor without this extension; where the change says nothing, this falls\n * back to that rule too.\n *\n * **A block that arrives without an id gets one, the moment it arrives**\n * (MAN-11): a paste, a `/` menu insert, the empty paragraph a new editor\n * starts with and the one StarterKit keeps at the end. `fromEditorDocument`\n * mints an id for such a block on every save and the editor never sees it, so\n * each save gave it a different one \u2014 a blur with no edit published again, and\n * a comment anchored to it in between was detached. The editor's first\n * document is filled in when it is created, outside the undo history and\n * without an update, so opening a description is not an edit.\n *\n * **A wrap or a lift hands the id on** (MAN-12). Turning a paragraph into a\n * quote or a list wraps it, and ProseMirror leaves its attrs on the paragraph\n * inside \u2014 where the save flattens it and drops the id, so the quote or list\n * item was published under a new one and every comment anchored to the\n * paragraph was detached. The quote or the list item takes the paragraph's id\n * instead, and the list around it a fresh one; lifting the text back out hands\n * the id to the paragraph again. The paragraph inside keeps no id, as one\n * loaded from a stored document has none.\n */\nexport const BlockId = Extension.create({\n name: 'blockId',\n onCreate() {\n const { state, view } = this.editor\n const unnamed = unnamedBlocks(state.doc)\n if (unnamed.length === 0) return\n const tr = state.tr\n for (const pos of unnamed) tr.setNodeAttribute(pos, 'blockId', newBlockId())\n view.dispatch(tr.setMeta('addToHistory', false).setMeta('preventUpdate', true))\n },\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('blockIdSplit'),\n appendTransaction: (transactions, old, state) => {\n if (!bringsInBlocks(transactions)) return null\n const mapping = new Mapping()\n for (const tr of transactions) mapping.appendMapping(tr.mapping)\n const unnamed = unnamedBlocks(state.doc)\n const handed = handedOver(state.doc, old.doc, mapping, unnamed)\n const ids = new Map<number, string | null>()\n for (const pos of repeatedBlockIds(state.doc, old.doc, mapping)) ids.set(pos, newBlockId())\n for (const pos of unnamed) ids.set(pos, handed.get(pos) ?? newBlockId())\n for (const pos of hiddenIds(state.doc)) ids.set(pos, null)\n if (ids.size === 0) return null\n const tr = state.tr\n for (const [pos, id] of ids) tr.setNodeAttribute(pos, 'blockId', id)\n return tr\n },\n }),\n ]\n },\n addGlobalAttributes() {\n return [\n {\n types: BLOCK_TYPES,\n attributes: {\n blockId: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute('data-block-id'),\n renderHTML: (attributes: Record<string, unknown>) =>\n attributes.blockId ? { 'data-block-id': String(attributes.blockId) } : {},\n },\n },\n },\n ]\n },\n})\n\n/** An http(s) URL, or null. */\nconst webUrl = (raw: string | null): string | null => (raw && /^https?:\\/\\/\\S+$/i.test(raw) ? raw : null)\n\n/** What a reference's view is handed: the `nostr:` URI it stands for, and the URL a URL chip was written as. */\nexport interface ReferenceViewProps {\n uri: string\n href?: string\n /**\n * Where it sits, so how it draws: `chip` in a sentence, `row` alone on its\n * line, `card` in the row's place (`LinkPlaces`, \u00A713.3). Always `chip` in an\n * editor without `LinkPlaces`.\n */\n place?: LinkPlace\n /**\n * Being edited, so a chip or a row shows no hover preview: a click on it opens its menu, or does nothing in a box\n * being written in. In a box, always while it can be written in; in a document (`editingLine`), only while the\n * caret is on its line, so a link elsewhere on the page previews on hover.\n */\n editing?: boolean\n}\n\nexport interface ReferenceNodeOptions {\n /**\n * Draws the reference as the thing it points at \u2014 the app's own chip, which\n * knows how to resolve it. Without one, the URI is drawn as text.\n */\n view: ComponentType<ReferenceViewProps> | null\n /**\n * A link counts as being edited (`editing`) only while the caret is on its\n * line: its textblock, between the hard breaks either side, while the editor\n * has focus. `DocumentEditor` sets it, so a page that is always editable\n * still previews the links its writer is not working on (Katerina, 30 Oct).\n * Off, every link is being edited while the editor is editable, as in a\n * message's box.\n */\n editingLine: boolean\n}\n\n/** A card's own controls: a press on one stays theirs, see `keepCardPresses`. */\nconst CARD_CONTROLS = 'button, [role=\"combobox\"]'\n\n/** What a click in a card goes on to: its links (the title, the count) and its controls. Its empty space opens the menu. */\nconst CARD_CLICKS = `a[href], input, select, ${CARD_CONTROLS}`\n\n/**\n * ProseMirror sees a press before React does and takes the caret into the\n * text, which closed a card's picker before it opened (Leaf's fix, moved here\n * so every app has it). It leaves alone a press whose default is prevented.\n */\nfunction keepCardPresses(element: HTMLElement | null): (() => void) | undefined {\n if (!element) return undefined\n const keep = (event: globalThis.MouseEvent) => {\n if (event.target instanceof Element && event.target.closest(CARD_CONTROLS)) event.preventDefault()\n }\n element.addEventListener('mousedown', keep)\n return () => element.removeEventListener('mousedown', keep)\n}\n\n/** Every reference on the caret's line: the textblock it is in, between the hard breaks either side of it. */\nfunction caretLineReferences(state: EditorState): { pos: number; size: number }[] {\n const { $head } = state.selection\n const block = $head.parent\n if (!block.isTextblock) return []\n const start = $head.start()\n const at = $head.parentOffset\n const lines: { from: number; to: number; references: { pos: number; size: number }[] }[] = [{ from: 0, to: block.content.size, references: [] }]\n block.forEach((child, offset) => {\n const line = lines[lines.length - 1]\n if (child.type.name === 'hardBreak') {\n line.to = offset\n lines.push({ from: offset + child.nodeSize, to: block.content.size, references: [] })\n } else if (child.type.name === 'reference') line.references.push({ pos: start + offset, size: child.nodeSize })\n })\n return lines.find((line) => at >= line.from && at <= line.to)?.references ?? []\n}\n\n/** Whether a node view's decorations put it on the caret's line. */\nfunction onCaretLine(decorations: readonly Decoration[] | undefined): boolean {\n return (decorations ?? []).some((decoration) => (decoration.spec as { caretLine?: boolean }).caretLine === true)\n}\n\n/**\n * A `nostr:` reference, drawn as the thing it points at \u2014 SPEC \u00A713.1.\n *\n * An **atom**: it has no editable interior, because its text is the URI and\n * nobody edits half a `naddr`. Selecting it selects the whole reference, which\n * is also how deleting one works. `marks` carries the run's other marks, so a\n * bold reference comes back bold.\n *\n * `embed` is the card its writer chose \u2014 `detailed`, drawn in the row's place\n * when the reference is alone on its line, or null for its row (SPEC \u00A713.3, \"A\n * reference's card\"; older writers wrote `compact`, which draws the row) \u2014 and\n * `extra` every key of the mark this version does not know. Both are declared\n * so that ProseMirror keeps them: an undeclared attribute is dropped when the\n * node is made, and the card with it. With `LinkPlaces`, the view is told where\n * the reference sits (`place`) and draws its chip, row or card.\n *\n * `href` makes it a **URL chip**: an app URL that reads as the chip of what it\n * names, and is that URL on the wire (\u00A713.3). `uri` is what it names, filled in\n * by `LinkChips` once the app has resolved it; until then it draws as the URL.\n */\nexport const ReferenceNode = Node.create<ReferenceNodeOptions>({\n name: 'reference',\n group: 'inline',\n inline: true,\n atom: true,\n selectable: true,\n draggable: false,\n addOptions() {\n return { view: null, editingLine: false }\n },\n addProseMirrorPlugins() {\n if (!this.options.editingLine) return []\n const editor = this.editor\n return [\n new Plugin({\n key: new PluginKey('referenceCaretLine'),\n props: {\n // Read on every update, a focus and a blur included (Tiptap sends a transaction for each), so it follows the caret.\n decorations: (state) =>\n editor.isFocused && editor.isEditable\n ? DecorationSet.create(\n state.doc,\n caretLineReferences(state).map(({ pos, size }) => Decoration.node(pos, pos + size, {}, { caretLine: true })),\n )\n : null,\n },\n }),\n ]\n },\n addAttributes() {\n return {\n // A pasted URL chip keeps only its URL: what it names is the editor's to resolve (`LinkChips`), never\n // the clipboard's, which could show one object while saving another URL (security review).\n uri: { default: '', parseHTML: (element: HTMLElement) => (webUrl(element.getAttribute('data-href')) ? '' : (element.getAttribute('data-reference') ?? '')) },\n marks: { default: [] as string[] },\n embed: { default: null as string | null, parseHTML: (element: HTMLElement) => element.getAttribute('data-embed') },\n extra: { default: null as Record<string, unknown> | null, parseHTML: () => null },\n // An http(s) URL only: `LinkChips` makes no other, and a pasted `javascript:` must not reach a saved link.\n href: { default: null as string | null, parseHTML: (element: HTMLElement) => webUrl(element.getAttribute('data-href')) },\n }\n },\n parseHTML() {\n return [{ tag: 'span[data-reference]' }]\n },\n renderHTML({ node }) {\n // A copy to the clipboard as HTML, and the whole drawing when no view is given.\n // The card goes along, so a paste keeps it; a URL chip copies as its URL.\n const embed = typeof node.attrs.embed === 'string' ? { 'data-embed': node.attrs.embed } : {}\n // Only a web address: the document's `href` is whatever its writer saved, and this attribute is read back by a paste.\n const web = webUrl(typeof node.attrs.href === 'string' ? node.attrs.href : null)\n const href = web ? { 'data-href': web } : {}\n return ['span', { 'data-reference': String(node.attrs.uri), ...embed, ...href }, String(node.attrs.href || node.attrs.uri)]\n },\n renderText({ node }) {\n return String(node.attrs.href || node.attrs.uri)\n },\n addNodeView() {\n const View = this.options.view\n if (!View) return null\n const { editingLine } = this.options\n return ReactNodeViewRenderer(({ node, editor, getPos, decorations }: ReactNodeViewProps) => {\n const uri = String(node.attrs.uri ?? '')\n const href = typeof node.attrs.href === 'string' && node.attrs.href ? node.attrs.href : undefined\n const place = placeOf(decorations)\n const editing = editor.isEditable && (!editingLine || onCaretLine(decorations))\n return (\n <NodeViewWrapper\n as=\"span\"\n // A row or a card is the whole line.\n className={place === 'chip' ? 'inline' : 'block w-full'}\n // A card keeps its pickers while the text is edited too (Katerina, 30 Oct): a press on one is not the text's.\n ref={place === 'card' ? keepCardPresses : undefined}\n // While editing, a click opens the chip's menu (`ReferenceMenu`) rather than following the chip.\n onClickCapture={(event: MouseEvent) => {\n // A click in something the view portals out \u2014 a picker's list, a hover card \u2014 reaches here through React's\n // tree, not the page's: it is that thing's, not a click on the link.\n const pos = getPos()\n if (typeof pos !== 'number') return\n // (`Node` here is Tiptap's; a click's target is an Element.)\n const own = editor.view.nodeDOM(pos)\n if (!(event.target instanceof Element) || !own || !own.contains(event.target)) return\n // A card's own links and controls take the click, while editing too: its title opens the file, its count the\n // conversation, its status and owner change it. Only its empty space opens the menu (Katerina, 30 Oct).\n if (place === 'card' && event.target.closest(CARD_CLICKS)) return\n if (referenceMenuClick(editor, pos)) {\n event.preventDefault()\n event.stopPropagation()\n return\n }\n // Being written with no menu to open \u2014 a message's box: a click on the link does not leave the draft\n // (Katerina, 30 Oct: a chip in the box does not follow a click).\n if (!editingLine && editor.isEditable && event.target.closest('a[href]')) event.preventDefault()\n }}\n >\n {/* A URL chip not resolved yet reads as the URL it was written as. */}\n {uri ? <View uri={uri} {...(href ? { href } : {})} place={place} editing={editing} /> : <span>{href}</span>}\n </NodeViewWrapper>\n )\n }, {\n // Words typed beside a link leave its node as it was, and Tiptap then skips the redraw; its place has changed (code\n // review), or the caret came onto its line or left it.\n update: ({ oldNode, newNode, oldDecorations, newDecorations, updateProps }) => {\n const moved = placeOf(oldDecorations) !== placeOf(newDecorations) || onCaretLine(oldDecorations) !== onCaretLine(newDecorations)\n if (oldNode !== newNode || moved) updateProps()\n return true\n },\n })\n },\n})\n\n/**\n * A block this editor has no design for, kept whole.\n *\n * \u00A713.3: a reader MUST render an unknown block's inline text and MUST NOT drop\n * it silently. **An editor is the dangerous case** \u2014 ProseMirror discards a\n * node its schema does not know, and the save after that would delete somebody\n * else's block with no error anywhere on the way. So the block's own JSON\n * rides in `source`, and protocol's `fromEditorDocument` hands it back\n * untouched; `text` is its inline text, worked out by `toEditorDocument`.\n *\n * Not editable, deliberately: an affordance that lets a person change\n * something they cannot see is worse than one that says the content is there\n * and belongs to another surface.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/the-block-editor-kit-lives-in-protocol-and-ui.md\n */\nexport const UnknownBlock = Node.create({\n name: 'unknownBlock',\n group: 'block',\n atom: true,\n selectable: true,\n addAttributes() {\n return {\n blockId: { default: null },\n source: { default: null },\n text: { default: '' },\n }\n },\n parseHTML() {\n return [{ tag: 'div[data-unknown-block]' }]\n },\n renderHTML({ node }) {\n return ['div', { 'data-unknown-block': String(node.attrs.blockId ?? '') }, String(node.attrs.text ?? '')]\n },\n addNodeView() {\n return ReactNodeViewRenderer(UnknownBlockView)\n },\n})\n\nfunction UnknownBlockView({ node }: ReactNodeViewProps) {\n const source = node.attrs.source as { id?: string; type?: string } | null\n const text = String(node.attrs.text ?? '')\n return (\n <NodeViewWrapper\n data-block-id={source?.id}\n data-block-type={source?.type}\n className=\"rounded-md border border-border-default bg-bg-inset px-2 py-1 text-text-secondary\"\n >\n {text || `A ${source?.type ?? 'block'} this app cannot edit yet.`}\n </NodeViewWrapper>\n )\n}\n\n/** What an attachment's view is handed: the block's `imeta` fields. */\nexport interface AttachmentViewProps {\n attrs: Record<string, unknown>\n}\n\nexport interface AttachmentNodeOptions {\n /** Draws the file \u2014 the app's own attachment card. Without one, its name is drawn as text. */\n view: ComponentType<AttachmentViewProps> | null\n}\n\n/**\n * A file placed in a document \u2014 SPEC \u00A713.3's `attachment` block (SHI-2).\n *\n * An atom: the file is the block, there is nothing inside it to edit, and a\n * caret that could sit \"inside\" an image is a way to produce documents no\n * reader has a rule for. Selectable and deletable, so removing one is Backspace\n * like anything else.\n *\n * Its attributes are the `imeta` fields exactly, because that is what \u00A713.3\n * specifies. Each is declared, and that is not boilerplate: ProseMirror **drops\n * an attribute its schema does not name**, so an undeclared `thumb` would\n * survive the editor and vanish on save \u2014 the silent deletion `UnknownBlock`\n * exists to prevent.\n */\nexport const AttachmentNode = Node.create<AttachmentNodeOptions>({\n name: 'attachment',\n group: 'block',\n atom: true,\n selectable: true,\n draggable: false,\n addOptions() {\n return { view: null }\n },\n addAttributes() {\n return {\n url: { default: '' },\n m: { default: '' },\n x: { default: '' },\n size: { default: 0 },\n dim: { default: null },\n thumb: { default: null },\n alt: { default: null },\n filename: { default: null },\n }\n },\n parseHTML() {\n return [{ tag: 'div[data-attachment-block]' }]\n },\n renderHTML({ node }) {\n // A copy to the clipboard, and the whole drawing when no view is given.\n return ['div', { 'data-attachment-block': String(node.attrs.x ?? '') }, String(node.attrs.filename ?? 'attachment')]\n },\n addNodeView() {\n const View = this.options.view\n if (!View) return null\n return ReactNodeViewRenderer(({ node }: ReactNodeViewProps) => (\n <NodeViewWrapper className=\"my-2\">\n <View attrs={node.attrs} />\n </NodeViewWrapper>\n ))\n },\n})\n\nconst TICK = 'checklistTick'\n\n/**\n * Whether a change is a click on a checklist item's box. The click does not\n * focus the editor, so no blur follows it: an editor that saves on blur saves\n * a tick straight away instead (RIC-19, Miky 2026-10-13: one click ticks).\n */\nexport function isChecklistTick(transaction: Transaction): boolean {\n return transaction.getMeta(TICK) === true\n}\n\n/** A list or quote command by name: StarterKit's declare them, and this package builds without StarterKit. */\ntype Chain = ReturnType<Editor['chain']>\nfunction named(chain: Chain, command: string, ...args: unknown[]): Chain {\n const own = (chain as unknown as Record<string, ((...a: unknown[]) => Chain) | undefined>)[command]\n return own ? own(...args) : chain\n}\n\n/** The list item the caret's paragraph is the first line of, if it is. */\nfunction itemAtCaret(state: EditorState): { node: ProseMirrorNode; pos: number } | null {\n const { $from } = state.selection\n if ($from.depth < 2) return null\n const item = $from.node(-1)\n if (item.type.name !== 'listItem' || $from.index(-1) !== 0) return null\n return { node: item, pos: $from.before(-1) }\n}\n\nconst sameAttrs = (a: ProseMirrorNode, b: ProseMirrorNode) =>\n Object.keys({ ...a.attrs, ...b.attrs }).every((key) => a.attrs[key] === b.attrs[key])\n\n/**\n * A list item, drawn with a box before it when it is a checklist item. The box\n * is the package's `Checkbox`, as `RichText` draws it, and the item's own\n * text and inner lists follow it in a `div`. Any change to the item's\n * attributes draws it again, which is what a tick is.\n *\n * The box is named by the item's words, and follows them as they are typed.\n * Whether it ticks follows the editor's `editable`, read again on every\n * update \u2014 `setEditable` sends one \u2014 not only when the item was drawn\n * (Katerina, review of #170). Not editable, it is a picture, and the box around\n * it says done or not to a screen reader, as `RichText`'s does.\n */\nfunction listItemView(editor: Editor, node: ProseMirrorNode, view: EditorView, getPos: () => number | undefined): NodeView {\n const toDOM = node.type.spec.toDOM\n const { dom, contentDOM } = toDOM ? DOMSerializer.renderSpec(document, toDOM(node)) : { dom: document.createElement('li'), contentDOM: undefined }\n const checked = node.attrs.checked\n if (typeof checked !== 'boolean') return { dom, contentDOM: contentDOM ?? dom, update: (next) => next.type === node.type && sameAttrs(next, node) }\n\n const li = dom as HTMLElement\n const box = document.createElement('span')\n box.contentEditable = 'false'\n box.setAttribute('data-checklist-box', '')\n const body = document.createElement('div')\n li.replaceChildren(box, body)\n const tick = (next: boolean) => {\n const pos = getPos()\n if (pos === undefined || !view.editable) return\n view.dispatch(view.state.tr.setNodeAttribute(pos, 'checked', next).setMeta(TICK, true))\n }\n let words = node.firstChild?.textContent.trim() || 'Item'\n const props = (): CheckboxProps => ({ checked, onChange: view.editable ? tick : undefined, 'aria-label': words })\n const renderer = new ReactRenderer<unknown, CheckboxProps>(Checkbox, { editor, props: props(), as: 'span' })\n box.appendChild(renderer.element)\n // What the box last drew: an update that changes neither leaves it alone, so typing does not draw every box again.\n let drawn = ''\n const sync = () => {\n const now = `${view.editable}:${words}`\n if (now === drawn) return\n drawn = now\n renderer.updateProps(props())\n for (const [name, value] of Object.entries({ role: 'checkbox', 'aria-checked': String(checked), 'aria-readonly': 'true', 'aria-label': words })) {\n if (view.editable) box.removeAttribute(name)\n else box.setAttribute(name, value)\n }\n }\n sync()\n editor.on('update', sync)\n return {\n dom: li,\n contentDOM: body,\n update: (next) => {\n if (next.type !== node.type || !sameAttrs(next, node)) return false\n words = next.firstChild?.textContent.trim() || 'Item'\n sync()\n return true\n },\n stopEvent: (event) => box.contains(event.target as globalThis.Node),\n ignoreMutation: (mutation) => box.contains(mutation.target),\n destroy: () => {\n editor.off('update', sync)\n renderer.destroy()\n },\n }\n}\n\n/**\n * A checklist item \u2014 SPEC \u00A713.3's `checked` on a list item (RIC-19): `true`\n * ticked, `false` not, absent a plain item. Add it beside `BlockId`.\n *\n * - **The box ticks with one click**, where the description is read, and the\n * change says so (`isChecklistTick`), so the app saves it at once.\n * - **`[ ] ` or `[] ` at the start of a line** makes it, `[x] ` ticked; in a\n * list it turns that item into one.\n * - **Enter** starts the next item unticked: a new item never takes the tick\n * of the one it was split from. At the start of an item, the text moves down\n * with its tick and the empty item above is unticked. On an empty item Enter\n * leaves the list, as in any list.\n * - **Backspace** at the start of a checklist item takes its box away first;\n * the next one joins it to the item above, as in any list.\n *\n * An editor without it drops `checked` on save and keeps the item and its text.\n */\nexport const Checklist = Extension.create({\n name: 'checklist',\n // Before the list item's own Enter and Backspace.\n priority: 101,\n addGlobalAttributes() {\n return [\n {\n types: ['listItem'],\n attributes: {\n checked: {\n default: null,\n keepOnSplit: false,\n parseHTML: (element: HTMLElement) => {\n const value = element.getAttribute('data-checked')\n return value === 'true' ? true : value === 'false' ? false : null\n },\n renderHTML: (attributes: Record<string, unknown>) =>\n typeof attributes.checked === 'boolean' ? { 'data-checked': String(attributes.checked) } : {},\n },\n },\n },\n ]\n },\n addInputRules() {\n return [\n new InputRule({\n find: /^\\[([ xX]?)\\]\\s$/,\n handler: ({ state, range, match, chain }) => {\n const checked = match[1].toLowerCase() === 'x'\n const inList = itemAtCaret(state) !== null\n // Without a bullet list to make, the typed text stays as it was typed.\n if (!inList && !(chain() as unknown as Record<string, unknown>).toggleBulletList) return null\n const deleted = chain().deleteRange(range)\n const listed = inList ? deleted : named(deleted, 'toggleBulletList')\n listed.updateAttributes('listItem', { checked }).run()\n },\n }),\n ]\n },\n addKeyboardShortcuts() {\n return {\n Enter: () => {\n // An open `/`, `@` or `[` list picks its row: running first, this split the line under it and left the `/` behind (LFB-3).\n if (isSuggestionOpen()) return false\n const { state } = this.editor\n const item = itemAtCaret(state)\n const { $from, empty } = state.selection\n if (!item || typeof item.node.attrs.checked !== 'boolean') return false\n // Over a selection: the selection goes and the next item is unticked, as for a caret in the text.\n if (!empty) return this.editor.chain().deleteSelection().splitListItem('listItem', { checked: false }).run()\n // An empty item: the list item's own Enter, which leaves the list.\n if ($from.parent.content.size === 0) return false\n if ($from.parentOffset > 0) return this.editor.commands.splitListItem('listItem', { checked: false })\n return this.editor\n .chain()\n .splitListItem('listItem', { checked: item.node.attrs.checked })\n .command(({ tr }) => {\n tr.setNodeAttribute(tr.mapping.map(item.pos), 'checked', false)\n return true\n })\n .run()\n },\n Backspace: () => {\n const { state } = this.editor\n const item = itemAtCaret(state)\n const { $from, empty } = state.selection\n if (!item || !empty || $from.parentOffset > 0 || typeof item.node.attrs.checked !== 'boolean') return false\n this.editor.view.dispatch(state.tr.setNodeAttribute(item.pos, 'checked', null))\n return true\n },\n }\n },\n addProseMirrorPlugins() {\n const editor = this.editor\n return [\n new Plugin({\n key: new PluginKey('checklist'),\n props: { nodeViews: { listItem: (node, view, getPos) => listItemView(editor, node, view, getPos) } },\n }),\n ]\n },\n})\n\n/**\n * A callout \u2014 SPEC \u00A713.3's `tone` on a quote (RIC-19): a quote drawn to stand\n * out, in one of GitHub's alert kinds (`note`, `tip`, `important`, `warning`,\n * `caution`). Its look is `RichText`'s, by `data-tone`; a tone it does not\n * know looks like `note`, and the editor keeps it as written. Add it beside\n * `BlockId`.\n */\nexport const Callout = Extension.create({\n name: 'callout',\n addGlobalAttributes() {\n return [\n {\n types: ['blockquote'],\n attributes: {\n tone: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute('data-tone'),\n // As `RichText` draws it: the tone as written, and the look it is drawn in.\n renderHTML: (attributes: Record<string, unknown>) =>\n typeof attributes.tone === 'string' ? { 'data-tone': attributes.tone, 'data-callout': calloutLook(attributes.tone) } : {},\n },\n },\n },\n ]\n },\n})\n", "/**\n * Where a reference in a block document sits, and so how it draws \u2014 SPEC \u00A713.3,\n * \"A reference's card\" (C22, C24): its chip in a sentence, its row alone on its\n * line, and its card in the row's place when its writer chose one.\n *\n * The rule is the protocol's (`documentLineDrawOf` in `@estiva-app/protocol`),\n * read here off the editor's own tree so it can be asked on every keystroke\n * without writing the document out. `linkPlaces.test.ts` runs the same\n * documents through both and holds them to one answer.\n *\n * - **Alone on its line**: a top-level paragraph, or a list item's, whose line\n * (up to a hard break) holds this reference and nothing but spaces besides.\n * A heading, a quote, a callout and a table cell are sentences, and so is\n * anything inside a block this rule does not name.\n * - **A marker around it** (bold, italic, code\u2026) makes it a sentence.\n * - **A person or a Folder** alone on its line stays a chip.\n * - **Its card** is `embed` `detailed`; anything else (none, `compact`, a value\n * this version does not know) draws the row.\n *\n * `LinkPlaces` puts each reference's place on a node decoration, which\n * `ReferenceNode`'s view reads and hands to the app's view as `place`.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-on-words-counts-toward-the-card.md\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-lone-links-chip-menu-offers-row-or-card.md\n */\nimport { Extension } from '@tiptap/core'\nimport type { Node as PmNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport { thingKindOf } from './KindIcon'\nimport type { LinkedKind } from './linked'\n\n/** How a reference draws: its chip, its row, or its card in the row's place. */\nexport type LinkPlace = 'chip' | 'row' | 'card'\n\n/** The blocks a line may sit inside and still be alone: a list and its items. */\nconst CONTAINERS = new Set(['bulletList', 'orderedList', 'listItem'])\n\nconst BECH32 = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'\n\n/** The 5-bit words of a bech32 string's data part, checksum dropped, or null. */\nfunction bech32Words(text: string): number[] | null {\n const at = text.lastIndexOf('1')\n if (at < 1 || text.length - at < 7) return null\n const words: number[] = []\n for (const char of text.slice(at + 1, -6)) {\n const word = BECH32.indexOf(char)\n if (word < 0) return null\n words.push(word)\n }\n return words\n}\n\n/** An `naddr`'s kind (TLV type 3), or null when it does not hold one. */\nfunction naddrKind(naddr: string): number | null {\n const words = bech32Words(naddr)\n if (!words) return null\n const bytes: number[] = []\n let acc = 0\n let bits = 0\n for (const word of words) {\n acc = (acc << 5) | word\n bits += 5\n while (bits >= 8) {\n bits -= 8\n bytes.push((acc >> bits) & 0xff)\n }\n }\n for (let i = 0; i + 1 < bytes.length; ) {\n const type = bytes[i]\n const length = bytes[i + 1]\n if (type === 3 && length === 4 && i + 6 <= bytes.length) return ((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i + 4] << 8) | bytes[i + 5]) >>> 0\n i += 2 + length\n }\n return null\n}\n\n/** A Folder's kind. */\nconst FOLDER = 39000\n\n/** A document's kind: it draws a page, as `linkedFrom` draws it. */\nconst PAGE = 30842\n\n/**\n * What a `nostr:` reference names, by the icon it draws, read off its address\n * alone: a message (`nevent`, `note`), a file by its kind (`naddr`, a document\n * a page), or undefined for what has no kind icon (a person, anything else).\n */\nexport function linkedKindOfReference(uri: string): LinkedKind | undefined {\n const bare = uri.toLowerCase().replace(/^nostr:/, '')\n if (bare.startsWith('nevent1') || bare.startsWith('note1')) return 'message'\n if (!bare.startsWith('naddr1')) return undefined\n const kind = naddrKind(bare)\n if (kind === null) return undefined\n return kind === PAGE ? 'page' : thingKindOf(kind)\n}\n\n/**\n * Whether what `uri` names stays a chip alone on its line: a person (`npub`,\n * `nprofile`) or a Folder (an `naddr` of kind 39000).\n */\nexport function staysChip(uri: string): boolean {\n const bare = uri.toLowerCase().replace(/^nostr:/, '')\n if (bare.startsWith('npub1') || bare.startsWith('nprofile1')) return true\n return bare.startsWith('naddr1') && naddrKind(bare) === FOLDER\n}\n\n/** Whether the textblock holding `pos` keeps the line rule: a paragraph at the top, or a list item's. */\nfunction keepsLineRule(doc: PmNode, pos: number): boolean {\n const $pos = doc.resolve(pos)\n if ($pos.parent.type.name !== 'paragraph' && $pos.parent.type.name !== 'listItem') return false\n for (let depth = 1; depth < $pos.depth; depth++) if (!CONTAINERS.has($pos.node(depth).type.name)) return false\n return true\n}\n\n/** Whether the reference at `index` of `block` is alone on its line: only spaces beside it, up to a hard break either side. */\nfunction aloneOnLine(block: PmNode, index: number): boolean {\n for (const step of [-1, 1]) {\n for (let i = index + step; i >= 0 && i < block.childCount; i += step) {\n const child = block.child(i)\n if (child.type.name === 'hardBreak') break\n if (!child.isText || (child.text ?? '').trim() !== '') return false\n }\n }\n return true\n}\n\n/** How the reference node at `pos` draws. Anything that is not a reference with a `uri` draws as a chip. */\nexport function linkPlaceAt(doc: PmNode, pos: number): LinkPlace {\n const node = doc.nodeAt(pos)\n if (!node || node.type.name !== 'reference') return 'chip'\n const uri = String(node.attrs.uri ?? '')\n // A URL chip whose URL is not resolved yet names nothing: it reads as the URL.\n if (!uri || staysChip(uri)) return 'chip'\n if (Array.isArray(node.attrs.marks) && node.attrs.marks.length > 0) return 'chip'\n if (!keepsLineRule(doc, pos)) return 'chip'\n const $pos = doc.resolve(pos)\n if (!aloneOnLine($pos.parent, $pos.index())) return 'chip'\n return node.attrs.embed === 'detailed' ? 'card' : 'row'\n}\n\n/** Every reference that does not draw as its chip, with its place. */\nexport function linkPlaces(doc: PmNode): { pos: number; size: number; place: Exclude<LinkPlace, 'chip'> }[] {\n const out: { pos: number; size: number; place: Exclude<LinkPlace, 'chip'> }[] = []\n doc.descendants((node, pos) => {\n if (node.type.name !== 'reference') return true\n const place = linkPlaceAt(doc, pos)\n if (place !== 'chip') out.push({ pos, size: node.nodeSize, place })\n return false\n })\n return out\n}\n\n/** The place a node view's decorations give it; `chip` without one. */\nexport function placeOf(decorations: readonly Decoration[] | undefined): LinkPlace {\n for (const decoration of decorations ?? []) {\n const place = (decoration.spec as { linkPlace?: LinkPlace }).linkPlace\n if (place) return place\n }\n return 'chip'\n}\n\nconst key = new PluginKey<DecorationSet>('linkPlaces')\n\n/**\n * Marks each reference that draws as its row or its card, for `ReferenceNode`'s\n * view. Without it every reference is a chip, as in a message's box.\n */\nexport const LinkPlaces = Extension.create({\n name: 'linkPlaces',\n addProseMirrorPlugins() {\n const decorate = (doc: PmNode) =>\n DecorationSet.create(\n doc,\n linkPlaces(doc).map(({ pos, size, place }) => Decoration.node(pos, pos + size, { 'data-link-place': place }, { linkPlace: place })),\n )\n return [\n new Plugin<DecorationSet>({\n key,\n state: {\n init: (_, state) => decorate(state.doc),\n apply: (tr, set) => (tr.docChanged ? decorate(tr.doc) : set),\n },\n props: { decorations: (state) => key.getState(state) },\n }),\n ]\n },\n})\n", "/**\n * What a link in a document offers its writer: Open, and \u2014 alone on its line \u2014\n * Show as Row or Card (SPEC \u00A713.3, \"A reference's card\"). Card puts its card in\n * the row's place (`embed` `detailed`); Row puts the row back (no `embed`).\n * Nothing writes `compact`. A chip in a sentence, and a person or a Folder alone\n * on its line (which stay chips), offer Open only (`linkPlaceAt`).\n *\n * **Where it opens**: a click on a link while editing opens the menu instead\n * of following it, and a lone-line link just put in \u2014 pasted, picked with `[`,\n * or a pasted URL becoming its chip (`LinkChips`) \u2014 opens it by itself, so the\n * card can be chosen at once. That menu takes no focus: the person is still\n * writing, and typing on closes it with no card. Enter on a selected link opens\n * it from the keyboard.\n *\n * **Keys while it is open**, handed over by the editor as the `/` menu's are:\n * \u2193 and \u2191 move through the rows (nothing is highlighted until they do, so\n * Enter after a paste still starts a new line), Enter chooses the highlighted\n * row, Escape closes it. Any edit or caret move closes it.\n *\n * Open does what a click on the chip does when reading: the app's own chip\n * gets the click, so it opens where the app opens it. A chip with nothing to\n * click opens its URL in a new tab; one with neither \u2014 a person, a link still\n * loading or not available \u2014 offers no Open, and a menu left with nothing in\n * it does not open.\n *\n * Two parts: the extension `ReferenceMenu` holds which chip the menu is open\n * on, and `ReferenceMenuView` draws it beside `EditorContent`. Pair them with\n * `ReferenceNode` and `LinkPlaces`.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-lone-links-chip-menu-offers-row-or-card.md\n */\nimport { useCallback, useEffect, useReducer } from 'react'\nimport { Extension, type Editor } from '@tiptap/core'\nimport { useEditorState } from '@tiptap/react'\nimport { NodeSelection, Plugin, PluginKey, TextSelection, type EditorState, type Transaction } from '@tiptap/pm/state'\nimport { ReplaceStep } from '@tiptap/pm/transform'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { IconCheck, IconExternalLink } from '@tabler/icons-react'\nimport { CHIPS_MADE } from './LinkChips'\nimport { linkPlaceAt } from './LinkPlaces'\nimport { MenuItem, MenuSection, MenuSeparator } from './Menu'\nimport { Popover } from './Popover'\nimport { setReferenceCardAt } from './ReferenceCards'\n\ninterface MenuState {\n /** The chip's position. */\n pos: number\n /** The highlighted row of `rowsOf`, or -1 for none. */\n active: number\n}\n\nconst key = new PluginKey<MenuState | null>('referenceMenu')\n\n/** How a lone-line link can show. */\ntype ShowAs = 'row' | 'card'\n\nconst SHOW_AS: { as: ShowAs; label: string }[] = [\n { as: 'row', label: 'Row' },\n { as: 'card', label: 'Card' },\n]\n\n/** A row of the menu: Open, or a way to show the link. */\ntype Row = 'open' | ShowAs\n\n/** The chip's own control to click, or null. */\nfunction chipTarget(view: EditorView, pos: number): HTMLElement | null {\n const dom = view.nodeDOM(pos)\n return dom instanceof HTMLElement ? dom.querySelector<HTMLElement>('a[href], button') : null\n}\n\n/** An http(s) URL chip's URL, or ''. */\nfunction webHref(view: EditorView, pos: number): string {\n const href = view.state.doc.nodeAt(pos)?.attrs.href\n return typeof href === 'string' && /^https?:\\/\\//i.test(href) ? href : ''\n}\n\n/**\n * The menu's rows: Open when there is something to open \u2014 the link's own\n * control as the app drew it, or its URL \u2014 and Row and Card when it is alone\n * on its line and is neither a person nor a Folder (`linkPlaceAt`). A person,\n * and a link still loading or not available, draw nothing to click: no Open\n * (Katerina, 30 Oct). The view asks again as the app's drawing changes.\n */\nfunction rowsOf(view: EditorView, pos: number): Row[] {\n const open: Row[] = chipTarget(view, pos) || webHref(view, pos) ? ['open'] : []\n return linkPlaceAt(view.state.doc, pos) === 'chip' ? open : [...open, ...SHOW_AS.map((show) => show.as)]\n}\n\n/** A chip node, or null. */\nfunction chipAt(state: EditorState, pos: number) {\n const node = state.doc.nodeAt(pos)\n return node && node.type.name === 'reference' ? node : null\n}\n\n/**\n * The chip this transaction just put right before the caret \u2014 a paste, a `[`\n * pick (which adds a space after it), or a URL becoming its chip \u2014 or null.\n * An undo, and a document loaded over the editor, put nothing in.\n */\nfunction justPlaced(tr: Transaction, state: EditorState): number | null {\n if (!tr.docChanged || tr.getMeta('history$') || tr.getMeta('preventUpdate')) return null\n // A whole document set over the editor \u2014 someone else's edit loaded \u2014 is not something the person put in.\n const whole = tr.steps.some((step) => step instanceof ReplaceStep && step.from === 0 && step.to === tr.before.content.size)\n if (whole && tr.getMeta('uiEvent') !== 'paste') return null\n // A URL becoming its chip opens the menu only when it was pasted, with the caret still right after it.\n const made = tr.getMeta(CHIPS_MADE) as { pasted: boolean } | undefined\n if (made && !made.pasted) return null\n const { selection } = state\n if (!selection.empty) return null\n let at = selection.from\n let before = selection.$from.nodeBefore\n if (!made && before?.isText && before.text === ' ') {\n at -= 1\n before = state.doc.resolve(at).nodeBefore\n }\n if (!before || before.type.name !== 'reference' || !before.attrs.uri) return null\n const pos = at - before.nodeSize\n const old = tr.mapping.invert().map(pos)\n const was = tr.before.nodeAt(old)\n // The same chip as before the step \u2014 a key pressed after it, a card set on it \u2014 is not new. One put in just before\n // an identical chip pushes that chip along, so it no longer maps onto `pos` (code review).\n if (was && was.type.name === 'reference' && was.attrs.uri === before.attrs.uri && tr.mapping.map(old, 1) === pos) return null\n // Only a link alone on its line has a card to choose; in a sentence the menu would offer Open alone.\n if (linkPlaceAt(state.doc, pos) === 'chip') return null\n return pos\n}\n\nfunction dispatchMenu(view: EditorView, next: MenuState | null): void {\n view.dispatch(view.state.tr.setMeta(key, next))\n}\n\n// True while Open hands the click to the chip, so the chip's own click is not taken for a click that opens the menu.\nlet passing = false\n\n/** Opens what the chip at `pos` names, as a click on it does when reading. */\nfunction openChip(view: EditorView, pos: number): void {\n const target = chipTarget(view, pos)\n if (target) {\n passing = true\n try {\n target.click()\n } finally {\n passing = false\n }\n return\n }\n const href = webHref(view, pos)\n if (href) window.open(href, '_blank', 'noopener,noreferrer')\n}\n\n/** Runs `row` of the menu open on the chip at `pos`, and closes it. */\nfunction choose(editor: Editor, pos: number, row: Row | undefined): void {\n dispatchMenu(editor.view, null)\n if (row === 'open') openChip(editor.view, pos)\n else if (row) setReferenceCardAt(editor, pos, row === 'card' ? 'detailed' : 'none')\n}\n\n/** Whether the menu is open, for an editor's own Escape: while it is, Escape closes it rather than leaving. */\nexport function isReferenceMenuOpen(state: EditorState): boolean {\n return !!key.getState(state)\n}\n\n/**\n * A click on the chip at `pos`, from its node view: while editing, with the\n * menu installed, it opens the menu, and the caller stops the click there.\n * Returns false when the click should go on to the chip.\n */\nexport function referenceMenuClick(editor: Editor, pos: number): boolean {\n if (passing || editor.isDestroyed || !editor.isEditable || key.getState(editor.state) === undefined) return false\n // A chip with nothing to open and no card to choose has no menu: the click goes on to it.\n if (!chipAt(editor.state, pos) || rowsOf(editor.view, pos).length === 0) return false\n editor.view.dispatch(caretAfter(editor.state, pos).setMeta(key, { pos, active: -1 }))\n return true\n}\n\n/**\n * The caret right after the chip, as a paste leaves it: a selected chip would\n * bring up the selection toolbar beside the menu, and typing would replace it.\n */\nfunction caretAfter(state: EditorState, pos: number): Transaction {\n const node = state.doc.nodeAt(pos)\n return state.tr.setSelection(TextSelection.create(state.doc, pos + (node?.nodeSize ?? 1)))\n}\n\n/** Which chip the menu is open on: see the module comment. */\nexport const ReferenceMenu = Extension.create({\n name: 'referenceMenu',\n // Before the editor's own keys, so Enter on a highlighted row is the row's, not a new line.\n priority: 1000,\n addProseMirrorPlugins() {\n const editor = this.editor\n return [\n new Plugin<MenuState | null>({\n key,\n state: {\n init: () => null,\n apply: (tr, value, before, after) => {\n const meta = tr.getMeta(key) as MenuState | null | undefined\n if (meta !== undefined) return meta\n const placed = justPlaced(tr, after)\n if (placed !== null) return { pos: placed, active: -1 }\n if (!value) return null\n const pos = tr.mapping.map(value.pos)\n if (!chipAt(after, pos)) return null\n // What another plugin appends \u2014 an id, a trailing line \u2014 is not the person typing on, and nor is a URL\n // elsewhere becoming its chip when its answer comes back (code review).\n if (tr.docChanged && !tr.getMeta('appendedTransaction') && tr.getMeta(CHIPS_MADE) === undefined) return null\n const onChip = after.selection instanceof NodeSelection && after.selection.from === pos\n if (tr.selectionSet && !after.selection.eq(before.selection) && !onChip) return null\n return pos === value.pos ? value : { ...value, pos }\n },\n },\n props: {\n handleDOMEvents: {\n // Focus gone, the keys no longer reach the menu, and a card chosen now would miss the save on leaving (code review).\n blur: (view) => {\n if (key.getState(view.state)) dispatchMenu(view, null)\n return false\n },\n },\n handleKeyDown: (view, event) => {\n // With a modifier, a key is the editor's: Shift+\u2193 extends the selection, Mod+Enter is not a pick.\n if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return false\n const open = key.getState(view.state)\n if (!open) {\n // Enter on a selected chip: the menu, from the keyboard, its first row highlighted.\n const { selection } = view.state\n if (event.key !== 'Enter' || !view.editable || !(selection instanceof NodeSelection) || selection.node.type.name !== 'reference') return false\n if (rowsOf(view, selection.from).length === 0) return false\n view.dispatch(caretAfter(view.state, selection.from).setMeta(key, { pos: selection.from, active: 0 }))\n return true\n }\n const rows = rowsOf(view, open.pos)\n if (event.key === 'Escape') {\n dispatchMenu(view, null)\n return true\n }\n if (rows.length === 0) return false\n if (event.key === 'ArrowDown') {\n dispatchMenu(view, { ...open, active: (open.active + 1) % rows.length })\n return true\n }\n if (event.key === 'ArrowUp') {\n dispatchMenu(view, { ...open, active: open.active <= 0 ? rows.length - 1 : open.active - 1 })\n return true\n }\n if (event.key === 'Enter' && open.active >= 0) {\n choose(editor, open.pos, rows[open.active])\n return true\n }\n return false\n },\n },\n }),\n ]\n },\n})\n\n/** What the panel draws: the link the menu is open on, and how it shows. */\ninterface Shown {\n pos: number\n active: number\n shownAs: ShowAs\n}\n\nexport interface ReferenceMenuViewProps {\n editor: Editor | null\n}\n\n/** The menu `ReferenceMenu` holds, hung under its chip. Render it always, beside `EditorContent`. */\nexport function ReferenceMenuView({ editor }: ReferenceMenuViewProps) {\n const shown = useEditorState({\n editor,\n selector: ({ editor: ed }): Shown | null => {\n if (!ed || ed.isDestroyed) return null\n const open = key.getState(ed.state)\n if (!open) return null\n if (!chipAt(ed.state, open.pos)) return null\n // `compact` and a value this version does not know draw the row (\u00A713.3), so they read as Row here.\n return { pos: open.pos, active: open.active, shownAs: linkPlaceAt(ed.state.doc, open.pos) === 'card' ? 'card' : 'row' }\n },\n })\n // A press anywhere in the panel keeps focus in the text, as a row's does: the editor saves and ends its menus when it loses focus.\n const keepFocus = useCallback((list: HTMLDivElement | null) => {\n const panel = list?.closest('[role=\"dialog\"]')\n if (!panel) return\n const keep = (event: Event) => event.preventDefault()\n panel.addEventListener('mousedown', keep)\n return () => panel.removeEventListener('mousedown', keep)\n }, [])\n\n const live = shown && editor && !editor.isDestroyed ? editor : null\n const dom = live && shown ? live.view.nodeDOM(shown.pos) : null\n const anchor = dom instanceof HTMLElement ? dom : null\n // Whether there is something to open is the app's drawing, which can arrive after the menu (right after a `[` pick)\n // or change under it (a link that loads): the rows are asked again when it does.\n const [, redraw] = useReducer((count: number) => count + 1, 0)\n useEffect(() => {\n if (!anchor || typeof MutationObserver === 'undefined') return\n const observer = new MutationObserver(redraw)\n observer.observe(anchor, { childList: true, subtree: true, attributes: true, attributeFilter: ['href'] })\n return () => observer.disconnect()\n }, [anchor])\n const rows = live && shown ? rowsOf(live.view, shown.pos) : []\n const opens = rows[0] === 'open'\n const showAs = rows.includes('card')\n const run = (row: Row) => {\n if (editor && shown) choose(editor, shown.pos, row)\n }\n\n return (\n // finalFocus={false}: focus never left the text.\n <Popover\n anchor={anchor}\n open={!!shown && !!anchor && rows.length > 0}\n onOpenChange={(next) => {\n if (!next && editor && !editor.isDestroyed && key.getState(editor.state)) dispatchMenu(editor.view, null)\n }}\n side=\"bottom\"\n align=\"left\"\n ariaLabel=\"Link\"\n finalFocus={false}\n >\n {shown && (\n <div ref={keepFocus} role=\"menu\" aria-label=\"Link\" className=\"flex flex-col gap-0.5\">\n {/* Only when there is something to open: the chip's own control, or its URL (code review). */}\n {opens && (\n <MenuItem\n role=\"menuitem\"\n tabIndex={-1}\n label=\"Open\"\n leading={<IconExternalLink size={16} />}\n selected={shown.active === 0}\n onMouseDown={(event) => {\n event.preventDefault()\n run('open')\n }}\n />\n )}\n {showAs && (\n <>\n {opens && <MenuSeparator />}\n <div role=\"group\" aria-label=\"Show as\">\n <MenuSection label=\"Show as\">\n {SHOW_AS.map(({ as, label }, i) => (\n <MenuItem\n key={as}\n role=\"menuitemradio\"\n aria-checked={shown.shownAs === as}\n tabIndex={-1}\n label={label}\n selected={shown.active === i + (opens ? 1 : 0)}\n trailing={shown.shownAs === as ? <IconCheck size={16} aria-hidden /> : undefined}\n onMouseDown={(event) => {\n event.preventDefault()\n run(as)\n }}\n />\n ))}\n </MenuSection>\n </div>\n </>\n )}\n </div>\n )}\n </Popover>\n )\n}\n", "/**\n * An app URL in a document reads as the chip of what it names \u2014 SPEC \u00A713.3,\n * \"A reference's card\", and \u00A77.7.\n *\n * The URL stays the URL: the chip is the `reference` node with `href` set (a\n * URL chip, `ReferenceNode`), which a document writes back as the URL it was,\n * plain text with no card and a `link` mark with one. Never a `nostr:`\n * reference in its place: the URL is how a person addresses the object.\n *\n * What a URL names is the app's to say \u2014 its manifests and its relay \u2014 so the\n * app hands this extension two functions: `referenceOf`, what it has resolved\n * so far, and `ask`, to look up the URLs it has not. A URL that names nothing,\n * or whose answer has not come back, stays text; when `ask` settles the\n * document is looked at again.\n *\n * The URL being typed stays text while the caret is in it or at its end, so a\n * half-typed address never turns into a chip under the person's fingers. A\n * pasted URL is whole, so it is asked about and made a chip at once, the caret\n * still at its end \u2014 where `ReferenceMenu` opens its menu.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-is-stored-as-the-url-a-person-wrote.md\n */\nimport { Extension, type Editor } from '@tiptap/core'\nimport { closeHistory } from '@tiptap/pm/history'\nimport type { Node as PmNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, type EditorState, type Selection, type Transaction } from '@tiptap/pm/state'\n\nexport interface LinkChipsOptions {\n /**\n * The `nostr:` reference an app URL names, from what the app has resolved\n * (\u00A77.7) \u2014 protocol's `referenceOfLink(url, resolveLink)`. Undefined while it\n * names nothing, or its answer has not come back.\n */\n referenceOf: ((url: string) => string | undefined) | null\n /** Look up what these URLs name. When it settles, the document is looked at again. */\n ask: ((urls: string[]) => Promise<unknown> | void) | null\n /**\n * How many URLs one editor asks about in its life, the first ones; the rest\n * stay text. An app's answer can cost a relay query, and a document pasted\n * full of links must not spend the writer's quota. Default 24.\n */\n limit: number\n}\n\ninterface LinkChipsState {\n options: LinkChipsOptions\n /** The last few pastes, mapped through every edit since. */\n pasted: PastedRange[]\n}\n\nconst key = new PluginKey<LinkChipsState>('linkChips')\n\n/** The meta on the transaction that made chips: `{ pasted }`. */\nexport const CHIPS_MADE = 'linkChipsMade'\n\n/** How many pastes are remembered; one is what the person just did. */\nconst PASTES_KEPT = 8\n\n/**\n * A link on words in marker text (skipped), or a bare URL \u2014 the grammar of\n * protocol's `urlRunsIn`, which a reader turns into chips by, so what an editor\n * makes a chip is what a reader would.\n */\nconst LINK_OR_URL = /(\\[[^[\\]\\n]+\\]\\((?:https?:\\/\\/|mailto:)[^\\s)]+\\))|(https?:\\/\\/[^\\s<>\"'`]+)/g\nconst TRAILING = new Set(['.', ',', ';', ':', '!', '?', ')', ']'])\n\n/** Each URL and where it sits; `end` is where its run ends before trailing punctuation is trimmed, which typing may yet continue. */\nfunction urlRuns(text: string): { url: string; from: number; to: number; end: number }[] {\n if (!text.includes('://')) return []\n const out: { url: string; from: number; to: number; end: number }[] = []\n for (const m of text.matchAll(LINK_OR_URL)) {\n if (m[1]) continue\n const start = m.index\n if (text.slice(Math.max(0, start - 2), start) === '](' || text[start - 1] === '[') continue\n let end = m[0].length\n while (end > 0 && TRAILING.has(m[0][end - 1])) end--\n out.push({ url: m[0].slice(0, end), from: start, to: start + end, end: start + m[0].length })\n }\n return out\n}\n\ninterface Found {\n /** Text URLs that name something: made chips. */\n chips: { from: number; to: number; url: string; uri: string; marks: string[]; pasted: boolean }[]\n /** URL chips whose URL is answered now: given their reference. */\n fills: { pos: number; uri: string }[]\n /** Every URL still waiting for an answer, or naming nothing. */\n open: string[]\n}\n\n/** Where something was pasted: a URL wholly inside one was not typed, so the caret at its end does not hold it as text. */\nexport interface PastedRange {\n from: number\n to: number\n}\n\n/**\n * What to change in a document, and what to ask. `selection` null treats no\n * URL as being typed; a URL inside one of `pasted` is never being typed.\n */\nexport function findLinkChips(doc: PmNode, selection: Selection | null, referenceOf: LinkChipsOptions['referenceOf'], pasted: readonly PastedRange[] = []): Found {\n const found: Found = { chips: [], fills: [], open: [] }\n const open = new Set<string>()\n doc.descendants((node, pos) => {\n // A fence is literal (\u00A713.1): its URLs are text.\n if (node.type.spec.code) return false\n if (node.type.name === 'reference') {\n const href = typeof node.attrs.href === 'string' ? node.attrs.href : ''\n if (href && !node.attrs.uri) {\n const uri = referenceOf?.(href)\n if (uri) found.fills.push({ pos, uri })\n else open.add(href)\n }\n return false\n }\n if (!node.isText || !node.text) return true\n // A URL in code is literal.\n if (node.marks.some((m) => m.type.spec.code || m.type.name === 'code')) return false\n // A link on words is the link's. A link whose text is its own URL \u2014 an editor's autolink, or its paste rule \u2014 is\n // that URL, as a document reads one (protocol's `inlineToEditor`): its chip, with the link mark left behind.\n const link = node.marks.find((m) => m.type.name === 'link')\n if (link && !(link.attrs.href === node.text && /^https?:\\/\\//.test(node.text))) return false\n const runs = link ? [{ url: node.text, from: 0, to: node.text.length, end: node.text.length }] : urlRuns(node.text)\n for (const run of runs) {\n const from = pos + run.from\n const to = pos + run.to\n // Being typed or selected: the caret inside it or at its end (`https://a.` is still being typed), or a\n // selection over any of it. A caret before it is not.\n // A pasted URL is whole: it becomes its chip with the caret still at its end, so its menu can open at once.\n const wasPasted = pasted.some((range) => range.from <= from && pos + run.end <= range.to)\n const typing = selection && selection.to > from && selection.from <= pos + run.end\n if (typing && !(selection.empty && wasPasted)) continue\n const uri = referenceOf?.(run.url)\n if (uri) found.chips.push({ from, to, url: run.url, uri, marks: node.marks.filter((m) => m !== link).map((m) => m.type.name), pasted: wasPasted })\n else open.add(run.url)\n }\n return false\n })\n found.open = [...open]\n return found\n}\n\nfunction apply(state: EditorState, found: Found): Transaction | null {\n if (!found.chips.length && !found.fills.length) return null\n const type = state.schema.nodes.reference\n if (!type) return null\n const tr = state.tr\n // A fill keeps the node's size, so the chips' positions still hold; the chips go last first.\n for (const { pos, uri } of found.fills) {\n const node = tr.doc.nodeAt(pos)\n if (node) tr.setNodeMarkup(pos, undefined, { ...node.attrs, uri })\n }\n for (const chip of [...found.chips].reverse()) {\n tr.replaceWith(chip.from, chip.to, type.create({ uri: chip.uri, href: chip.url, marks: chip.marks }))\n }\n // Whether a pasted URL became its chip: `ReferenceMenu` opens on that one, never on a URL typed by hand.\n const pasted = found.chips.some((chip) => chip.pasted)\n tr.setMeta(CHIPS_MADE, { pasted })\n // A pasted URL's chip is its own undo step, so Ctrl+Z gives the URL back rather than taking the paste away (OPT-19,\n // as Peek's pasted link did). Any other chip is not a step of the person's: undo takes back what they typed.\n return pasted ? closeHistory(tr) : tr.setMeta('addToHistory', false)\n}\n\n/**\n * Look at the document again \u2014 after the app learned what more URLs name some\n * other way. Dispatches only when there is a chip to make: an empty\n * transaction would wake every other plugin (a trailing paragraph appears).\n */\nexport function refreshLinkChips(editor: Editor): void {\n if (editor.isDestroyed) return\n const chips = key.getState(editor.state)\n if (!chips) return\n const tr = apply(editor.state, findLinkChips(editor.state.doc, editor.state.selection, chips.options.referenceOf, chips.pasted))\n if (tr) editor.view.dispatch(tr)\n}\n\n/**\n * Turns the app URLs in a document into URL chips. Pair it with `ReferenceNode`;\n * `LinkPlaces` then draws a lone one as its row or its card, and\n * `ReferenceMenu` lets its writer choose.\n */\nexport const LinkChips = Extension.create<LinkChipsOptions>({\n name: 'linkChips',\n addOptions() {\n return { referenceOf: null, ask: null, limit: 24 }\n },\n addProseMirrorPlugins() {\n const options = this.options\n const editor = this.editor\n return [\n new Plugin<LinkChipsState>({\n key,\n // The options, where `refreshLinkChips` can read them from the state alone, and where the last pastes landed.\n state: {\n init: () => ({ options, pasted: [] }),\n apply: (tr, value, before, after) => {\n if (!tr.docChanged) return value\n // A paste edited inside is being typed again: forgotten, so each keystroke in it is not an ask (security review).\n const pasted = value.pasted\n .map((range) => ({ from: tr.mapping.map(range.from, 1), to: tr.mapping.map(range.to, -1), size: range.to - range.from }))\n .filter((range) => range.from < range.to && range.to - range.from === range.size)\n .map(({ from, to }) => ({ from, to }))\n if (tr.getMeta('uiEvent') === 'paste') {\n const from = tr.mapping.map(before.selection.from, -1)\n if (from < after.selection.to) pasted.push({ from, to: after.selection.to })\n }\n return { options, pasted: pasted.slice(-PASTES_KEPT) }\n },\n },\n appendTransaction: (trs, _old, state) => {\n if (!trs.some((tr) => tr.docChanged || tr.selectionSet)) return null\n return apply(state, findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted))\n },\n view: (view) => {\n // Each URL is asked once; one whose ask failed is forgotten, so a later look asks again.\n const asked = new Set<string>()\n // The URL being typed is not asked about: each prefix of it would spend one of `limit`, and a query.\n const look = (state: EditorState) => {\n if (!options.ask) return\n const { open } = findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted)\n // The limit counts the URLs the document still holds unanswered: a message box lives across many messages,\n // and one that counted every URL it was ever asked would stop making chips after a day's links (OPT-19).\n const waiting = new Set(open)\n for (const url of asked) if (!waiting.has(url)) asked.delete(url)\n const fresh = open.filter((url) => !asked.has(url)).slice(0, Math.max(0, options.limit - asked.size))\n if (!fresh.length) return\n for (const url of fresh) asked.add(url)\n const forget = () => {\n for (const url of fresh) asked.delete(url)\n }\n let answer: Promise<unknown> | void\n try {\n answer = options.ask(fresh)\n } catch {\n forget()\n return\n }\n void Promise.resolve(answer).then(() => refreshLinkChips(editor), forget)\n }\n look(view.state)\n // Once the view is up, so a dispatch lands: what the app already knows turns into chips on open.\n queueMicrotask(() => {\n try {\n refreshLinkChips(editor)\n } catch {\n // Unmounted before it ran.\n }\n })\n return {\n update: (next, prev) => {\n // A caret leaving a URL finishes it, so a move is looked at as an edit is.\n if (next.state.doc !== prev.doc || !next.state.selection.eq(prev.selection)) look(next.state)\n },\n }\n },\n }),\n ]\n },\n})\n", "/**\n * The card a block document's writer chose for a reference \u2014 SPEC \u00A713.3, \"A\n * reference's card\": `embed` on the `reference` node (`ReferenceNode`), so the\n * card moves and goes with its chip. `ReferenceMenu` writes it (Show as Row or\n * Card) and `LinkPlaces` draws it in the row's place.\n *\n * The extension that placed a slot after each line for the app's card, and its\n * hook, were deprecated by `LinkPlaces` and are gone (Katerina's widget review,\n * 30 Oct): no app used them. What stays reads and writes the choice.\n */\nimport type { Editor } from '@tiptap/core'\nimport type { Node as PmNode } from '@tiptap/pm/model'\nimport { NodeSelection, type EditorState } from '@tiptap/pm/state'\n\n/** A layout a writer can choose; `none` is no card. */\nexport type ReferenceCardLayout = 'none' | 'compact' | 'detailed'\n\n/** One card to draw: the reference's `nostr:` URI and how much to show. */\nexport interface ReferenceCard {\n uri: string\n layout: Exclude<ReferenceCardLayout, 'none'>\n}\n\ninterface Placement {\n key: string\n /** The end of the textblock's content. */\n pos: number\n cards: ReferenceCard[]\n}\n\n/** `embed` as a node holds it: an unknown string draws as compact (\u00A713.3), anything else is none. */\nfunction layoutOf(raw: unknown): ReferenceCard['layout'] | undefined {\n if (typeof raw !== 'string' || raw === '' || raw === 'none') return undefined\n return raw === 'detailed' ? 'detailed' : 'compact'\n}\n\n/** Every line that asks for a card, in document order. */\nexport function referenceCardPlacements(doc: PmNode): Placement[] {\n const out: Placement[] = []\n const seen = new Map<string, number>()\n doc.descendants((node, pos, parent) => {\n if (!node.isTextblock) return true\n const cards: ReferenceCard[] = []\n node.forEach((child) => {\n if (child.type.name !== 'reference') return\n const layout = layoutOf(child.attrs.embed)\n // A URL chip whose URL is not resolved yet (`LinkChips`) has nothing to draw a card of, yet.\n if (layout && child.attrs.uri) cards.push({ uri: String(child.attrs.uri), layout })\n })\n if (cards.length) {\n // The textblock's own id, or its list item's or cell's: the nearest one.\n const id = node.attrs.blockId ?? parent?.attrs.blockId\n const base = id ? `b:${String(id)}` : `p:${pos}`\n const n = seen.get(base) ?? 0\n seen.set(base, n + 1)\n out.push({ key: n ? `${base}:${n}` : base, pos: pos + node.nodeSize - 1, cards })\n }\n return false\n })\n return out\n}\n\n/**\n * The chip the person has selected, with what it names and its card \u2014 or null.\n *\n * Selected as a node (a click, where a click on the chip does not follow its\n * link), or inside a selected range that holds that one chip and nothing but\n * spaces besides (Shift+arrow over it, or a drag across it): an app whose chip\n * is a link has no other way to select it.\n */\nexport function referenceAtSelection(state: EditorState): { pos: number; uri: string; layout: ReferenceCardLayout } | null {\n const { selection } = state\n let found: { pos: number; node: PmNode } | null = null\n if (selection instanceof NodeSelection) {\n if (selection.node.type.name === 'reference') found = { pos: selection.from, node: selection.node }\n } else if (!selection.empty) {\n let only = true\n state.doc.nodesBetween(selection.from, selection.to, (node, pos) => {\n if (node.type.name === 'reference') {\n if (found) only = false\n found = { pos, node }\n return false\n }\n if (node.isText) {\n const from = Math.max(selection.from, pos) - pos\n const to = Math.min(selection.to, pos + node.nodeSize) - pos\n if ((node.text ?? '').slice(from, to).trim() !== '') only = false\n }\n return true\n })\n if (!only) found = null\n }\n if (!found) return null\n const { pos, node } = found as { pos: number; node: PmNode }\n // A URL chip that names nothing yet has no card to choose.\n if (!node.attrs.uri) return null\n return { pos, uri: String(node.attrs.uri ?? ''), layout: layoutOf(node.attrs.embed) ?? 'none' }\n}\n\n/** Sets the card of the selected chip. `none` removes it. The selection stays as it was. */\nexport function setReferenceCard(editor: Editor, layout: ReferenceCardLayout): boolean {\n const at = referenceAtSelection(editor.state)\n return at ? setReferenceCardAt(editor, at.pos, layout) : false\n}\n\n/** Sets the card of the chip at `pos` \u2014 one that names something. `none` removes it. The selection stays as it was. */\nexport function setReferenceCardAt(editor: Editor, pos: number, layout: ReferenceCardLayout): boolean {\n const node = editor.state.doc.nodeAt(pos)\n if (!node || node.type.name !== 'reference' || !node.attrs.uri) return false\n const wasNode = editor.state.selection instanceof NodeSelection && editor.state.selection.from === pos\n // Same size, so a range maps onto itself; a node selection is made again, since the node is replaced.\n const tr = editor.state.tr.setNodeMarkup(pos, undefined, { ...node.attrs, embed: layout === 'none' ? null : layout })\n if (wasNode) tr.setSelection(NodeSelection.create(tr.doc, pos))\n editor.view.dispatch(tr)\n return true\n}\n", "// @estiva-escape(component-has-a-page, component-has-a-story): draws nothing of its own \u2014 it opens a SuggestionMenu from a Tiptap suggestion plugin, and SuggestionMenu's page and stories show it (UIG-31)\nimport { forwardRef, useRef, useImperativeHandle } from 'react'\nimport { ReactRenderer } from '@tiptap/react'\nimport { exitSuggestion, type SuggestionKeyDownProps, type SuggestionOptions, type SuggestionProps } from '@tiptap/suggestion'\nimport { SuggestionMenu, type SuggestionMenuHandle, type SuggestionMenuRow, type SuggestionMenuSection } from './SuggestionMenu'\n\n/*\n * Is a type-ahead list open? \u2014 Peek's counter (`mention.tsx`), moved here with\n * the lists it counts (UIG-31).\n *\n * A counter rather than a boolean: two suggestion plugins can overlap for a\n * moment while one hands over to the other (`/` choosing \"Mention\" types `@`).\n * An editor asks before it acts on Enter or Escape, so a key that chose a row\n * does not also send the message or cancel the edit.\n *\n * A list counts while it shows rows, not while its trigger listens: since a\n * space stopped closing one (f586437a), \"meet @ 5pm\" leaves `@` listening\n * behind a hidden list to the end of the line, and that Enter must still send.\n *\n * And only while its editor has focus (71a4577b): a list left by a click ends,\n * or it would stay counted and swallow Escape in the box clicked into.\n */\nlet openCount = 0\nlet lastClose = 0\n\n/**\n * Open, or closed less than 100ms ago \u2014 what an Enter handler asks. Choosing a\n * row with Enter closes the list, and that same Enter must not also send.\n */\nexport function isSuggestionActive(): boolean {\n return openCount > 0 || Date.now() - lastClose < 100\n}\n\n/**\n * Open *now*, with no grace period \u2014 what an Escape handler asks. The first\n * Escape closes the list, the second is somebody's deliberate press.\n */\nexport function isSuggestionOpen(): boolean {\n return openCount > 0\n}\n\n/** How a list looks and what fills it \u2014 everything but the editor's own wiring. */\nexport interface SuggestionPopupOptions<T> {\n /** Names the list \u2014 \"Commands\", \"People\". */\n ariaLabel: string\n /** The box's width, e.g. `w-[300px]`. */\n width: string\n /** The cap before the rows scroll, e.g. `max-h-[400px]`. */\n maxHeight: string\n /** The plugin's items, and the typed query, \u2192 the sections to draw. One unlabeled section by default. */\n sections?: (items: T[], query: string) => readonly SuggestionMenuSection<T>[]\n itemKey: (item: T) => string\n row: (item: T) => SuggestionMenuRow\n /**\n * With `refresh`: called with a listener while the list is open; the app\n * calls it when its data has changed (a search landing), and the open list is\n * drawn again for the same query. Returns the unsubscribe, run when the list\n * closes however it closes.\n */\n subscribe?: (listener: () => void) => () => void\n /** The items for a query, as the plugin's `items` answers \u2014 asked again when `subscribe` fires. */\n refresh?: (query: string) => T[]\n}\n\ntype Props<T> = SuggestionProps<T> & { options: SuggestionPopupOptions<T> }\n\n// `forwardRef`, so Tiptap's `ReactRenderer` hands its `ref` through whichever\n// way it detects a component that takes one.\nconst Popup = forwardRef<SuggestionMenuHandle, Props<unknown>>(function Popup({ options, ...props }, handle) {\n const menu = useRef<SuggestionMenuHandle>(null)\n useImperativeHandle(handle, () => ({ onKeyDown: (event) => menu.current?.onKeyDown(event) ?? false }))\n const sections = options.sections ? options.sections(props.items, props.query) : [{ items: props.items }]\n return (\n <SuggestionMenu\n handle={menu}\n rect={props.clientRect ?? null}\n editorElement={props.editor.view.dom}\n ariaLabel={options.ariaLabel}\n width={options.width}\n maxHeight={options.maxHeight}\n sections={sections}\n itemKey={options.itemKey}\n row={options.row}\n onSelect={(item) => props.command(item)}\n />\n )\n})\n\n/**\n * The `render` of a Tiptap suggestion plugin, drawn as a `SuggestionMenu` \u2014\n * the popup controller Peek wrote four times (`mention.tsx`, `slashCommands.tsx`),\n * once.\n *\n * Suggestion({ editor, char: '/', items, command,\n * render: suggestionPopup({ ariaLabel: 'Commands', width: 'w-[300px]',\n * maxHeight: 'max-h-[400px]', itemKey, row, sections }) })\n *\n * It mounts the list when the query starts and removes it when it ends: the\n * plugin owns the list's life. Escape closes it and is used up; \u2191, \u2193 and Enter\n * go to the list; every other key stays the editor's. The list portals itself\n * (the package `Popover`), so the mount point is only a mount point.\n */\nexport function suggestionPopup<T>(options: SuggestionPopupOptions<T>): NonNullable<SuggestionOptions<T>['render']> {\n return () => {\n let component: ReactRenderer<SuggestionMenuHandle, Props<T>> | null = null\n let container: HTMLDivElement | null = null\n let last: SuggestionProps<T> | null = null\n let unsubscribe: (() => void) | undefined\n let counted = false\n let unlisten: (() => void) | undefined\n const count = (shown: boolean) => {\n if (shown === counted) return\n counted = shown\n openCount = shown ? openCount + 1 : Math.max(0, openCount - 1)\n }\n // The plugin's state outlives a blur \u2014 no transaction runs \u2014 so leaving the\n // box ends the query here, as Escape does: coming back finds no list, and\n // Enter sends (Miky, 2026-10-06). Leaving the window is not leaving the box,\n // and a press in the list's own panel never takes focus (SuggestionMenu).\n const listen = (props: SuggestionProps<T>) => {\n const { view } = props.editor\n const dom = view.dom\n const onBlur = () => {\n // A window that loses focus leaves its active element where it was.\n if (dom.contains(document.activeElement) || !last) return\n const from = last.range.from\n // Not a pick: no grace for the other box's Enter.\n count(false)\n for (const plugin of view.state.plugins) {\n const state = plugin.getState(view.state) as { active?: boolean; range?: { from: number } } | undefined\n if (state?.active && state.range?.from === from && plugin.spec.key) exitSuggestion(view, plugin.spec.key)\n }\n }\n dom.addEventListener('blur', onBlur)\n unlisten = () => dom.removeEventListener('blur', onBlur)\n }\n const exit = () => {\n unsubscribe?.()\n unsubscribe = undefined\n unlisten?.()\n unlisten = undefined\n last = null\n // The grace is for the Enter that picked a row and closed the list, not\n // for a keystroke that only left it with no rows.\n if (counted) lastClose = Date.now()\n count(false)\n if (!component) return\n component.destroy()\n container?.remove()\n component = null\n container = null\n }\n return {\n onStart: (props) => {\n count(props.items.length > 0)\n component = new ReactRenderer<SuggestionMenuHandle, Props<T>>(Popup as never, { props: { ...props, options }, editor: props.editor })\n container = document.createElement('div')\n document.body.appendChild(container)\n container.appendChild(component.element)\n last = props\n listen(props)\n const { subscribe, refresh } = options\n if (subscribe && refresh) {\n // The plugin asks for items only when the query changes; an answer\n // landing later draws the open list again with the same props.\n unsubscribe = subscribe(() => {\n if (!last || !component) return\n last = { ...last, items: refresh(last.query) }\n count(last.items.length > 0)\n component.updateProps({ ...last, options })\n })\n }\n },\n onUpdate: (props) => {\n last = props\n count(props.items.length > 0)\n component?.updateProps({ ...props, options })\n },\n onKeyDown: ({ event }: SuggestionKeyDownProps) => {\n if (event.key === 'Escape') {\n exit()\n return true\n }\n return component?.ref?.onKeyDown(event) ?? false\n },\n onExit: exit,\n }\n }\n}\n", "// @estiva-escape(component-has-a-page, component-has-a-story): CommentBox's own frame, not offered to apps \u2014 CommentBox's page and stories show it (Katerina, 21 Oct: one box)\nimport { useCallback, useEffect, useState, type ReactNode } from 'react'\nimport { Extension } from '@tiptap/core'\nimport { EditorContent, type Editor } from '@tiptap/react'\nimport { IconArrowUp } from '@tabler/icons-react'\nimport { IconButton } from './IconButton'\nimport { Toolbar } from './Toolbar'\nimport { cn } from './cn'\nimport { richTextClassName } from './RichText'\nimport { ScrollArea } from './ScrollArea'\nimport { BOX_HINT_CLASSES, EDITOR_SELECTION_CLASSES, WRITING_BOX_CLASSES, WRITING_RING_CLASSES } from './looks'\nimport { SelectionToolbar, type SelectionToolbarProps } from './SelectionToolbar'\nimport { isSuggestionActive } from './suggestionPopup'\n\n/**\n * The frame `CommentBox` writes in, from Katerina's Leaf prototype (9\n * October): the text, scrolling in a `ScrollArea` past half the window, the\n * bar down its left while it is marked, what is attached, and a footer. The\n * send box and the edit box are this one frame with different footers, so a\n * change to the box is made once (Katerina, 21 Oct: the scrollbar had to be\n * fixed in two copies). It was `ComposeBox`, a part of its own until 0.85.0;\n * no app used it, and two box names invited the wrong pick.\n */\n\n/** The classes the box's editor wears: rich text with no outline. It never scrolls itself; the box does, in a `ScrollArea`. */\nexport const COMPOSE_EDITOR_CLASSES = richTextClassName('default', cn('outline-none w-full bg-transparent min-h-[20px] [&>p+p]:-mt-1', EDITOR_SELECTION_CLASSES))\n\n/**\n * A long draft stops at half the window and scrolls inside the box, so its\n * first line can be reached (PEE-59). The package's `ScrollArea` scrolls it,\n * not the browser: its bar, and one that shows while there is more (Katerina,\n * 21 Oct: the browser's bar, and none at all in some browsers).\n *\n * The region reaches into the box's right padding (the box's `p-3`) and its\n * content gives it back, so the text ends where it did and the bar sits 3px\n * from the box's edge, as every other box's bar does (Katerina, 21 Oct: the gap\n * on the right; measured 15px before, 3px after).\n */\nexport const COMPOSE_SCROLL_CLASSES = { area: '-mr-3', viewport: 'max-h-[50vh]', content: 'pr-3' }\n\ntype ComposeKeysStorage = { send: (() => boolean) | null }\n\n/**\n * Enter sends; Shift+Enter is a new line \u2014 in a list a new item (or out of the\n * list, on an empty one), in a quote a new line (or out of it, on an empty one).\n * Peek's keys, as its ComposeBox has them. Enter while a `/`, `@` or `[` list is\n * open picks a row instead. `ComposeBox` says what sending does.\n */\nexport const ComposeKeys = Extension.create<Record<string, never>, ComposeKeysStorage>({\n name: 'composeKeys',\n addStorage() {\n return { send: null }\n },\n addKeyboardShortcuts() {\n return {\n Enter: () => {\n if (isSuggestionActive()) return false\n this.storage.send?.()\n return true\n },\n 'Shift-Enter': ({ editor }) => {\n const { $from } = editor.state.selection\n for (let d = $from.depth; d > 0; d--) {\n const node = $from.node(d)\n if (node.type.name === 'listItem') {\n return node.textContent.length === 0 ? editor.commands.liftListItem('listItem') : editor.commands.splitListItem('listItem')\n }\n if (node.type.name === 'blockquote') {\n if ($from.parent.textContent.length === 0) return editor.commands.lift('paragraph')\n break\n }\n }\n return editor.commands.splitBlock()\n },\n }\n },\n})\n\n/** Nothing written: no text, no chip and no picture \u2014 empty lines, spaces, lists or quotes only. */\nexport function isEmptyDoc(editor: Editor): boolean {\n const doc = editor.state.doc\n if (doc.textContent.trim().length > 0) return false\n let empty = true\n doc.descendants((node) => {\n // A text node is a leaf, so an atom too: only spaces are left of it here.\n if (node.isAtom && !node.isText && node.type.name !== 'hardBreak') empty = false\n })\n return empty\n}\n\nexport interface BoxFrameProps {\n /** The box's editor, with `ComposeKeys` in its extensions and `COMPOSE_EDITOR_CLASSES` on it. `null` while it loads. */\n editor: Editor | null\n /** The bar down the text's left: an urgent mention or a highlight, as Peek draws it. */\n marked?: boolean\n /** The selection strip over the text, with these buttons. Absent, no strip (the edit box). */\n selection?: Pick<SelectionToolbarProps, 'marks' | 'link' | 'actions'>\n /** Said while the text is empty: words, and a `Kbd` where a key helps. */\n placeholder?: ReactNode\n empty?: boolean\n /** What is attached, under the text: `AttachmentCard pending`s. */\n attachments?: ReactNode\n /** The row under it all: the tools and Send, or the keys and Cancel/Save. */\n footer: ReactNode\n /** Signal's focus ring. Off for the edit box, whose edge only darkens on focus, as in Ship. Default on. */\n ring?: boolean\n /** On the box itself. */\n className?: string\n}\n\n/** The one frame both boxes draw: the bordered box, its text in a `ScrollArea`, what is attached, the footer. */\nexport function BoxFrame({ editor, marked = false, selection, placeholder, empty = false, attachments, footer, ring = true, className }: BoxFrameProps) {\n return (\n // Focused, the edge darkens (the send box in Signal takes the accent and its glow instead). In Leaf, the edge every\n // field takes, in the send box and the edit box alike (Katerina, 31 October); never the accent on Peek's edit box (1 November).\n <div className={cn(WRITING_BOX_CLASSES, ring && WRITING_RING_CLASSES, 'focus-within:border-border-strong leaf:focus-within:border-border-focus transition-colors', className)}>\n <div data-composer-editor data-marked={marked || undefined} className={cn('relative min-h-[20px] transition-all', marked && 'border-l-4 border-border-strong pl-2')}>\n <ScrollArea className={COMPOSE_SCROLL_CLASSES.area} viewportClassName={COMPOSE_SCROLL_CLASSES.viewport} contentClassName={COMPOSE_SCROLL_CLASSES.content}>\n <EditorContent editor={editor} />\n </ScrollArea>\n {selection && <SelectionToolbar editor={editor} {...selection} />}\n {empty && placeholder != null && (\n <div className=\"pointer-events-none absolute inset-0 flex flex-wrap items-center gap-1 text-body-2 text-text-muted\">{placeholder}</div>\n )}\n </div>\n {attachments && <div className=\"flex flex-wrap gap-2\">{attachments}</div>}\n {footer}\n </div>\n )\n}\n\nexport interface SendBoxProps {\n /** The box's editor. `null` while it loads. */\n editor: Editor | null\n /**\n * Send what is written. The box empties afterwards \u2014 unless this returns\n * `false`: nothing was sent, and the words stay.\n */\n onSend: (editor: Editor) => void | boolean\n /** Said in the empty box: words, and a `Kbd` where a key helps (\"type / for commands\"). */\n placeholder: ReactNode\n /** The tools under the text, left: `ToolbarButton`s (attach, highlight). One Tab stop. */\n tools?: ReactNode\n /** What is attached, under the text: `AttachmentCard pending`s. */\n attachments?: ReactNode\n /** Something to send even with no words \u2014 a file ready. */\n ready?: boolean\n /** Sending waits \u2014 a file still uploading. */\n holding?: boolean\n /** The bar down the text's left: an urgent mention or a highlight, as Peek draws it. */\n marked?: boolean\n /** The selection strip's buttons: its marks, Link, and the app's own (`actions`). */\n selection?: Pick<SelectionToolbarProps, 'marks' | 'link' | 'actions'>\n className?: string\n}\n\n/**\n * The send box: the frame with the selection strip over the text, the tools\n * and Send under it. Enter sends (`ComposeKeys`), and so does the button.\n */\nexport function SendBox({ editor, onSend, placeholder, tools, attachments, ready = false, holding = false, marked = false, selection, className }: SendBoxProps) {\n const [empty, setEmpty] = useState(true)\n const canSend = (!empty || ready) && !holding\n\n const send = useCallback((): boolean => {\n if (!editor || holding || (isEmptyDoc(editor) && !ready)) return true\n if (onSend(editor) === false) return true\n editor.commands.clearContent(true)\n editor.commands.focus()\n return true\n }, [editor, holding, ready, onSend])\n\n // Enter, through `ComposeKeys`, sends the way the button does.\n useEffect(() => {\n if (!editor) return\n const storage = (editor.storage as unknown as { composeKeys?: ComposeKeysStorage }).composeKeys\n if (!storage) return\n storage.send = send\n return () => {\n storage.send = null\n }\n }, [editor, send])\n\n useEffect(() => {\n if (!editor) return\n const read = () => setEmpty(isEmptyDoc(editor))\n read()\n editor.on('update', read)\n return () => {\n editor.off('update', read)\n }\n }, [editor])\n\n return (\n <div className={cn('relative', className)}>\n <BoxFrame\n editor={editor}\n marked={marked}\n selection={selection ?? {}}\n placeholder={placeholder}\n empty={empty}\n attachments={attachments}\n footer={\n // The tools are one strip \u2014 one Tab stop, arrows along it; Send, the answer rather than a tool, keeps its own.\n <div className=\"flex items-center justify-between\">\n {tools ? (\n <Toolbar aria-label=\"Compose tools\" surface={false} className=\"flex items-center gap-1\">\n {tools}\n </Toolbar>\n ) : (\n <span />\n )}\n <div className=\"flex items-center gap-2.5\">\n <span className={BOX_HINT_CLASSES}>Enter to send \u00B7 Shift+Enter new line</span>\n {/* Focus stays in the text: the press sends on its way down. A keyboard press is the click (`detail` 0), so a click never sends twice. */}\n <IconButton\n variant=\"primary\"\n onMouseDown={(e) => {\n e.preventDefault()\n send()\n }}\n onClick={(e) => {\n if (e.detail === 0) send()\n }}\n disabled={!canSend}\n aria-label=\"Send\"\n tooltip=\"Send\"\n tooltipShortcut=\"Enter\"\n glow={canSend}\n >\n <IconArrowUp size={16} stroke={1.5} />\n </IconButton>\n </div>\n </div>\n }\n />\n </div>\n )\n}\n", "/**\n * Looks two or more parts share, written once (UIG-25).\n *\n * A look typed again by hand draws the same today and drifts the day one of\n * them changes: nothing fails, one screen just looks slightly off. So a look\n * more than one part wears lives here, and each part takes it from here. The\n * lint that finds a copied look reads a class list wherever it is written; a\n * constant of classes ends in `_CLASSES`, so it is read as one.\n *\n * Only looks \u2014 colour, text, border, corner, shadow. Where a part sits and how\n * much room it takes stay in the part.\n */\n\n/**\n * A field's box: TextInput and Textarea. The hairline strengthens on hover \u2014 of the box, or of anywhere in the `Field` around it, label included, so the field is one thing under the pointer (Katerina, 28 September) \u2014 and not while switched off: a label passes its hover to its box, switched off or not (FIELD_DISABLED_CLASSES holds it back). Focus outranks it, so a focused field keeps its colour under the pointer.\n */\nexport const FIELD_BOX_CLASSES = 'bg-bg-field border border-border-field shadow-field hover:border-border-strong group-hover/field:border-border-strong focus:border-border-focus group-hover/field:focus:border-border-focus rounded-lg'\n\n/** What a field's words look like, typed or waiting: TextInput, Textarea and Select. */\nexport const FIELD_TEXT_CLASSES = 'text-text-primary placeholder:text-text-muted'\n\n/** A field that cannot be used: TextInput, Textarea and Select. */\nexport const FIELD_DISABLED_CLASSES = 'disabled:pointer-events-none disabled:bg-bg-disabled disabled:text-text-disabled disabled:border-border-field group-hover/field:disabled:border-border-field'\n\n/** The ring a focused field wears in Signal: TextInput and Textarea. */\nexport const FIELD_FOCUS_RING_CLASSES = 'signal:transition-shadow signal:focus:shadow-focus-ring'\n\n/** A field's two sizes, its padding and its words: TextInput, Textarea (default only) and Select. The small one is the small Select's trigger. */\nexport const FIELD_SIZE_CLASSES = {\n default: 'px-3 py-2 text-input-value',\n small: 'h-6 min-h-6 px-2 text-caption',\n} as const\n\n/** The box around an input that sits inside it, before its focus look: SearchInput and ChipInput. */\nexport const FIELD_SHELL_CLASSES = 'bg-bg-field border border-border-field shadow-field hover:border-border-strong group-hover/field:border-border-strong rounded-lg transition-colors'\n\n/** That box focused, while what is typed in it has the focus: the focus border, held under the pointer, and Signal's ring. ChipInput and DocumentField. */\nexport const FIELD_SHELL_FOCUS_CLASSES = 'focus-within:border-border-focus focus-within:hover:border-border-focus group-hover/field:focus-within:border-border-focus signal:transition-shadow signal:focus-within:shadow-focus-ring'\n\n/** A panel that floats over the page: Menu's panel and Tooltip. */\nexport const FLOATING_SURFACE_CLASSES = 'rounded-lg border border-border-default bg-bg-elevated shadow-lg'\n\n/** A count beside a label, in the muted colour: NavItem's number and SectionHeader's `count`. */\nexport const COUNT_TEXT_CLASSES = 'font-mono text-caption tabular-nums text-text-muted'\n\n/** A chip's words: Chip's label and Reaction's count. */\nexport const CHIP_TEXT_CLASSES = 'text-chip signal:font-mono signal:text-small signal:font-semibold signal:tabular-nums'\n\n/**\n * The time of something a person said: one line, and in Signal the mono micro-type with even digits, as Peek's\n * conversation draws a message's time (its MetaText). Only there: words a person wrote, and the latest conversation\n * (Katerina, 29 Oct); \"Updated\" and other times keep the text's own type.\n */\nexport const TIME_CLASSES = 'whitespace-nowrap signal:font-mono signal:text-small signal:tracking-wide signal:tabular-nums'\n\n/** Small secondary words that turn mono under signal: Kbd's key, CommandPalette's footer and MembersPill's count. */\nexport const MONO_CAPTION_CLASSES = 'text-caption text-text-secondary signal:font-mono signal:text-small'\n\n/** Words typed straight into an input with no box of its own: SearchInput and ChipInput. */\nexport const BARE_INPUT_CLASSES = 'bg-transparent text-text-primary placeholder:text-text-muted outline-none'\n\n/** A sidebar row's shape and its words at rest, brightening under the pointer: NavItem, and SectionHeader's `row` (a folder among rows). */\n// 8px corners, a MenuItem row's (Katerina, 2 October).\nexport const SIDEBAR_ROW_CLASSES = 'rounded-lg transition-colors'\nexport const SIDEBAR_ROW_TEXT_CLASSES = 'text-text-secondary hover:text-text-primary'\n\n/** A quiet icon control: secondary, brightening on a hover fill \u2014 IconButton's `muted`. */\nexport const MUTED_CONTROL_CLASSES = 'text-text-secondary hover:bg-bg-hover hover:text-text-primary'\n\n/** A control that opens a menu: a hover fill, held while its menu is up \u2014 PersonTrigger's row, and a ContainerHeader title with a menu. */\nexport const MENU_TRIGGER_CLASSES = 'cursor-pointer rounded-md transition-colors hover:bg-bg-hover data-[popup-open]:bg-bg-hover'\n\n/**\n * A column that folds sideways, as Peek's rail did (Katerina, 31 October: one fold in every app): 300ms, none under\n * prefers-reduced-motion. Folded, it fades and is then hidden, so nothing in it can be seen once it has gone; with\n * the `transition-[\u2026]` naming `opacity` and `visibility`. AppShell's navigation, and ListColumn closing with it.\n */\nexport const FOLD_MOTION_CLASSES = 'duration-300 ease-in-out motion-reduce:transition-none'\nexport const FOLDED_CLASSES = 'invisible opacity-0'\nexport const UNFOLDED_CLASSES = 'visible opacity-100'\n\n/**\n * A panel that slides open and shut on Base UI's Collapsible: Base UI measures\n * it and writes its height to a variable, `auto` again once the slide ends, and\n * the panel is 0 high on its opening and closing frames. None under\n * prefers-reduced-motion. CollapsibleSection's rows, and the rows under a NavItem.\n */\nexport const COLLAPSIBLE_PANEL_CLASSES = 'h-[var(--collapsible-panel-height)] overflow-hidden transition-[height] duration-150 ease-out motion-reduce:transition-none data-[starting-style]:h-0 data-[ending-style]:h-0'\n\n/**\n * The box a message or a comment is written in: Peek's writing box (its\n * `looks.ts`, Katerina 24 September), moved with the comment box. Inset, a hairline,\n * 12px in, 16px between the text and the row under it; the focus ring in Signal.\n */\n// A field's fill and edge, as every field has (Katerina, 31 October: the comment box is a field, and every field has its fill).\nexport const WRITING_BOX_CLASSES = 'relative bg-bg-field border border-border-field rounded-lg p-3 flex flex-col gap-4'\n\n/**\n * Selected words in an editor: the selected thing's fill, the colour the selection strip's kept selection paints\n * while its link field has the focus (`KeptSelection`), so the words look the same selected and kept. Peek's\n * composer rule (PEE-19), moved into every editor: the comment box, the document editor and InlineText.\n */\nexport const EDITOR_SELECTION_CLASSES = 'selection:bg-bg-selected'\n\n/** The keys under the send box, in words: \"Enter to send \u00B7 Shift+Enter new line\". One line, cut when the room runs out; no key caps. The edit box writes none (Katerina, 1 November). */\nexport const BOX_HINT_CLASSES = 'min-w-0 truncate select-none text-caption text-text-muted signal:font-mono signal:text-menu signal:font-normal signal:tracking-wider'\n\n/** Signal's focus ring (the glow) on the send box, as on every field. The edit box has no glow and no accent edge (Katerina, 31 October, 1 November). */\nexport const WRITING_RING_CLASSES = 'signal:transition-shadow signal:focus-within:border-border-focus signal:focus-within:shadow-focus-ring'\n\n/** The 36px tile a file's type sits in: AttachmentCard's, and a link's kind in LinkRow, LinkCard and PartCard (Katerina, 29 Oct). */\nexport const TYPE_TILE_CLASSES = 'size-9 rounded-md bg-bg-active flex items-center justify-center shrink-0 text-text-secondary'\n\n\n/** The bar down a quoted part's left edge: PartCard's blocks, and (proposal) a card's latest conversation. */\nexport const QUOTE_BAR_CLASSES = 'border-l-2 border-border-default pl-3'\n\n/**\n * A link in text: the link icon before its words, in the link's colour and at the text's size, and one underline\n * under the icon and the words together, as Slack draws one, so it never reads as a chip (Katerina, 29 Oct: \"icon\n * before but also underlined\", \"I want the icon to be underlined as well like Slack does\"). A chip of an Estiva thing\n * starts with its kind's icon instead and wears none of this.\n *\n * The browser's underline (`text-decoration`) skips an icon, so the line is the link's own background instead: 1px of\n * its colour along the bottom of each line it runs over. Tabler's `link` is drawn as a mask on `::before`, so it takes\n * the link's colour and nothing is added to what is saved or copied. `Link`'s `text` look is this, and so are the\n * editors' links (`LINK_CLASS`).\n */\n/** The line a link in text draws under everything in it, icon included: its own 1px background, since text-decoration skips an icon. */\nexport const LINK_UNDERLINE_CLASSES = 'no-underline bg-[linear-gradient(currentColor,currentColor)] bg-[length:100%_1px] bg-bottom bg-no-repeat'\n\nexport const WEB_LINK_CLASSES = `${LINK_UNDERLINE_CLASSES} before:content-[''] before:inline-block before:size-[1em] before:mr-0.5 before:align-[-0.125em] before:bg-current before:[mask:url(data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2024%2024%27%20fill%3D%27none%27%20stroke%3D%27black%27%20stroke-width%3D%271.75%27%20stroke-linecap%3D%27round%27%20stroke-linejoin%3D%27round%27%3E%3Cpath%20d%3D%27M9%2015l6%20-6%27%2F%3E%3Cpath%20d%3D%27M11%206l.463%20-.536a5%205%200%200%201%207.071%207.072l-.534%20.464%27%2F%3E%3Cpath%20d%3D%27M13%2018l-.397%20.534a5.068%205.068%200%200%201%20-7.127%200a4.972%204.972%200%200%201%200%20-7.071l.524%20-.463%27%2F%3E%3C%2Fsvg%3E)_center/contain_no-repeat]`\n", "import type { ComponentType, MouseEvent, ReactNode } from 'react'\nimport { Extension, type Editor } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport Mention, { type MentionOptions } from '@tiptap/extension-mention'\nimport Suggestion from '@tiptap/suggestion'\nimport { NodeViewWrapper, ReactNodeViewRenderer, type ReactNodeViewProps } from '@tiptap/react'\nimport { Avatar } from './Avatar'\nimport type { ReferenceViewProps } from './BlockNodes'\nimport { EnterHint } from './Menu'\nimport { inlineChipClassName } from './InlineChip'\nimport { WithTooltip } from './Tooltip'\nimport type { SuggestionMenuRow } from './SuggestionMenu'\nimport { suggestionPopup, type SuggestionPopupOptions } from './suggestionPopup'\n\n/*\n * The four composer triggers every Estiva app shares \u2014 `@`, `!@`, `[` and `/`\n * (CON-26, Miky 2026-10-02). Peek built them first and they move here unchanged\n * (CON-27); an app passes in only its own data: its people, the things `[` can\n * reference, and the `/` rows it can perform beside the shared Format section.\n *\n * **What a pick writes is not here.** The text a chip becomes in the body and\n * the tags it earns are `@estiva-app/conversation`'s (`mentionText`,\n * `messageReference`, `urgentTagsFor`), so a client without React writes the\n * same bytes. A chip here carries what that needs: a person's `pubkey`, a\n * reference's `uri`.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/composer-triggers-are-one-shared-kit.md\n */\n\n// \u2500\u2500\u2500 @ and !@ \u2500\u2500\u2500\n\n/** A person `@` and `!@` offer. */\nexport interface MentionPerson {\n /** The app's own key for the person \u2014 the row's key and the chip's `id`. */\n id: string\n name: string\n /** The second line of the row: a role, a team. */\n description?: string\n /** Their Nostr key, when they have one \u2014 what the body is written with (SPEC \u00A713.1). */\n pubkey?: string | null\n /** The face at the row's start. Default: the package `Avatar` for the name. */\n avatar?: ReactNode\n /** An agent: its face is a robot, as Avatar's `bot`. */\n bot?: boolean\n}\n\n/** How many people the list shows. */\nexport const PEOPLE_LIMIT = 6\n\n/** The people whose name holds the query, the first {@link PEOPLE_LIMIT} of them. */\nexport function filterPeople(people: readonly MentionPerson[], query: string): MentionPerson[] {\n const q = query.toLowerCase()\n return people.filter((person) => q === '' || person.name.toLowerCase().includes(q)).slice(0, PEOPLE_LIMIT)\n}\n\n/**\n * The people list `@` and `!@` open: the face, the name, the second line, and\n * the Enter hint while highlighted \u2014 `MenuItem` at its tall size.\n */\nexport function peopleMenu(urgent: boolean): SuggestionPopupOptions<MentionPerson> {\n const section = urgent ? 'Urgent mention' : 'People'\n return {\n ariaLabel: section,\n // The people and the reference lists are the same box: 658px, capped at 360.\n width: 'w-[658px]',\n maxHeight: 'max-h-[360px]',\n sections: (people) => [{ label: section, items: people, className: 'px-3 py-1' }],\n itemKey: (person) => person.id,\n row: (person) => ({\n label: person.name,\n description: person.description,\n leading: person.avatar ?? <Avatar size={32} alt={person.name} bot={person.bot} />,\n hint: <EnterHint />,\n size: 'tall',\n }),\n }\n}\n\nexport interface PersonMentionOptions {\n /** Everyone the list can offer, asked each time the query changes. */\n people: () => readonly MentionPerson[]\n}\n\ntype Doc = { descendants: (cb: (node: { type: { name: string }; attrs: Record<string, unknown> }) => boolean | void) => void }\n\nfunction optionsOf<T>(editor: Editor, name: string): T | undefined {\n return editor.extensionManager.extensions.find((one) => one.name === name)?.options as T | undefined\n}\n\n/**\n * A list keeps listening across spaces, so a name or a title can be more than\n * one word (f586437a, Miky 2026-10-06). It stops at a new line, Escape, a pick\n * or the cursor leaving \u2014 Suggestion's own \u2014 and once the query holds `stop`:\n * `]` for `[`, so \"see [the notes] above\" ends as text. While nothing matches,\n * the list is hidden rather than closed, and comes back if the words match again.\n * A space straight after the key is prose (\"meet @ 5pm\", \"- [ ] task\"), not a\n * query: every two-word name holds a space.\n */\nconst listening = (stop: string) => ({\n allowSpaces: true,\n shouldShow: ({ query }: { query: string }) => !/^\\s/.test(query) && !query.includes(stop),\n})\n\n/** `@`'s list and pick, or `!@`'s, for the node `name` \u2014 the extension's own, so a renamed one still finds its people. */\nfunction personSuggestion(urgent: boolean, name: string) {\n return {\n ...(urgent ? { char: '!@' } : {}),\n // A second `@` starts another mention; the first one has ended.\n ...listening('@'),\n items: ({ query, editor }: { query: string; editor: Editor }) => filterPeople(optionsOf<PersonMentionOptions>(editor, name)?.people() ?? [], query),\n render: suggestionPopup(peopleMenu(urgent)),\n command: ({ editor, range, props: person }: { editor: Editor; range: { from: number; to: number }; props: MentionPerson }) => {\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n { type: name, attrs: { id: person.id, label: person.name, pubkey: person.pubkey ?? null } },\n { type: 'text', text: ' ' },\n ])\n .run()\n },\n }\n}\n\n/*\n What a chip keeps through HTML \u2014 a copy and paste, inside an editor or\n between two. The chip's own `renderHTML` writes each as a `data-*` attribute\n and these read them back. Until CON-27 none was written, so a pasted chip\n came back with every value null and was sent as `@null`. What is read is\n checked: a crafted `data-pubkey` that is not a key, or a `data-uri` that is\n not a `nostr:` reference, is dropped rather than written into the body.\n*/\nconst HEX_KEY = /^[0-9a-f]{64}$/\nconst NOSTR_URI = /^nostr:[a-z0-9]+$/i\nconst fromData = (name: string, valid?: RegExp) => ({\n parseHTML: (element: HTMLElement) => {\n const value = element.getAttribute(`data-${name}`)\n return value !== null && (!valid || valid.test(value)) ? value : null\n },\n // The node's own `renderHTML` writes it.\n renderHTML: () => ({}),\n})\n\nconst personAttributes = () => ({\n id: { default: null, ...fromData('id') },\n label: { default: null, ...fromData('label') },\n /**\n * The person's Nostr key, when they have one \u2014 SPEC \u00A713.1. `id` is the app's\n * own and means nothing to another app; this is what the body is written\n * with, so a mention survives a rename.\n */\n pubkey: { default: null, ...fromData('pubkey', HEX_KEY) },\n})\n\n/** The `data-*` a person chip is written with, so a paste reads it back. */\nfunction personData(attrs: Record<string, unknown>): Record<string, string> {\n return {\n 'data-id': String(attrs.id ?? ''),\n 'data-label': String(attrs.label ?? ''),\n ...(typeof attrs.pubkey === 'string' && attrs.pubkey ? { 'data-pubkey': attrs.pubkey } : {}),\n }\n}\n\n/**\n * `@` \u2014 a person, as a chip that writes their key (SPEC \u00A713.1).\n *\n * PersonMention.configure({ people: () => directory })\n *\n * Its `pubkey` and `label` are what `mentionText` takes.\n */\nexport const PersonMention = Mention.extend<MentionOptions<MentionPerson, MentionPerson> & PersonMentionOptions>({\n name: 'mention',\n addOptions() {\n return { ...this.parent!(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(false, this.name) }\n },\n addAttributes: personAttributes,\n renderHTML({ node }) {\n // No node view, so this spec is what the editor draws: the one chip.\n return ['span', { 'data-mention': 'true', ...personData(node.attrs), class: inlineChipClassName('person', 'cursor-default') }, `@${node.attrs.label}`]\n },\n parseHTML() {\n return [{ tag: 'span[data-mention]' }]\n },\n})\n\n/**\n * `!@` \u2014 a person, urgently: the same chip in the urgent tone. Its text is an\n * ordinary mention; the urgency travels as a tag (`urgentTagsFor`), so hand the\n * write {@link urgentPubkeys}.\n */\nexport const UrgentPersonMention = Mention.extend<MentionOptions<MentionPerson, MentionPerson> & PersonMentionOptions>({\n name: 'urgentMention',\n addOptions() {\n return { ...this.parent!(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(true, this.name) }\n },\n addAttributes: personAttributes,\n renderHTML({ node }) {\n return [\n 'span',\n { 'data-urgent-mention': 'true', ...personData(node.attrs), class: inlineChipClassName('urgent', 'cursor-default') },\n `@${node.attrs.label}`,\n ]\n },\n parseHTML() {\n return [{ tag: 'span[data-urgent-mention]' }]\n },\n})\n\n/**\n * The keys the document's urgent mentions name \u2014 what the write turns into\n * `[\"urgent\", <pubkey>]` tags. A chip with no key has no tag to carry; its text\n * is the old `!@Name`.\n */\nexport function urgentPubkeys(editor: { state: { doc: Doc } }): string[] | undefined {\n const urgent: string[] = []\n editor.state.doc.descendants((node) => {\n if (node.type.name === 'urgentMention' && typeof node.attrs.pubkey === 'string' && node.attrs.pubkey) urgent.push(node.attrs.pubkey)\n })\n return urgent.length > 0 ? urgent : undefined\n}\n\nexport interface PersonReferenceOptions {\n /** Everyone `@` can offer, asked each time the query changes. */\n people: () => readonly MentionPerson[]\n /** The `nostr:npub\u2026` a person is written as; `null` for someone without one, who is not offered. */\n uriOf: (person: MentionPerson) => string | null\n /** The node a pick inserts. Default `reference`, `ReferenceNode`'s. */\n nodeName: string\n}\n\n/**\n * `@` in a document \u2014 a person, written as a reference to them: a\n * `ReferenceNode` whose `uri` is their `nostr:npub\u2026` (SPEC \u00A713.1, \u00A713.3). Not\n * {@link PersonMention}'s chip, which is a message's: a document names people\n * the way it names anything else, and a save that newly names someone is what\n * adds them (`@estiva-app/conversation`'s `mentionAddsFor`, which reads only\n * that uri).\n *\n * PersonReference.configure({ people: () => directory, uriOf: (person) => npubUri(person.pubkey) })\n *\n * The chip carries no name: the app's `ReferenceNode` view resolves the uri,\n * so a rename shows everywhere the person is named.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-mention-in-a-files-text-adds-the-person-with-no-unread.md\n */\nexport const PersonReference = Extension.create<PersonReferenceOptions>({\n name: 'personReference',\n addOptions() {\n return { people: () => [], uriOf: () => null, nodeName: 'reference' }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n Suggestion<MentionPerson>({\n editor: this.editor,\n char: '@',\n pluginKey: new PluginKey('personReference'),\n ...listening('@'),\n // As `[`'s: only where the chip may go.\n allow: ({ state, range }) => {\n const type = state.schema.nodes[options.nodeName]\n return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type)\n },\n items: ({ query }) =>\n filterPeople(\n options.people().filter((person) => options.uriOf(person) !== null),\n query,\n ),\n render: suggestionPopup(peopleMenu(false)),\n command: ({ editor, range, props: person }) => {\n const uri = options.uriOf(person)\n if (!uri) return\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n { type: options.nodeName, attrs: { uri } },\n { type: 'text', text: ' ' },\n ])\n .run()\n },\n }),\n ]\n },\n})\n\n// \u2500\u2500\u2500 [ \u2500\u2500\u2500\n\n/** Something `[` offers: a reference drawn as who said it and how it opens. */\nexport interface CaptionedItem {\n /** The referenced thing's id \u2014 the row's key and the chip's `id`. */\n id: string\n /** Who, as the list shows them. */\n label: string\n /** The opening words, marks stripped: the caption the row and the chip wear. */\n snippet: string\n /** `nostr:\u2026`, exactly as the body will carry it (`messageReference`). */\n uri: string\n /** What the query is matched against beside `label`. Default: `snippet`. */\n search?: string\n /** The row's second line, e.g. where the thing sits. The chip does not wear it. */\n description?: string\n /**\n * What the thing is about, in a line of plain text \u2014 a file's summary. When\n * set, it is the row's second line and `description` moves up after the\n * label, muted; absent, the row is as before. The chip does not wear it, and\n * the query is not matched against it.\n */\n summary?: string\n /**\n * This row's own 16px icon, in place of the list's `icon`: what the thing is,\n * when the list holds several kinds \u2014 a topic, a project, a message\n * (Katerina, 7 October). Absent, the list's icon.\n */\n icon?: ReactNode\n}\n\n/** One labelled group of `[`'s rows, in the order the list draws them. */\nexport interface ReferenceSection {\n label: string\n items: readonly CaptionedItem[]\n}\n\n/** How many references the list shows. */\nexport const REFERENCE_LIMIT = 6\n\n/**\n * The references whose label or text holds the query \u2014 the last\n * {@link REFERENCE_LIMIT}, in the order given: a thread is unbounded, and a\n * list that grew with it would be a hundred rows of prose.\n */\nexport function filterReferences(items: readonly CaptionedItem[], query: string): CaptionedItem[] {\n const q = query.toLowerCase()\n const shown = q ? items.filter((item) => (item.search ?? item.snippet).toLowerCase().includes(q) || item.label.toLowerCase().includes(q)) : [...items]\n return shown.slice(-REFERENCE_LIMIT)\n}\n\nconst captionOf = (label: string, snippet: string) => (snippet ? `${label}: ${snippet}` : label)\n\nexport interface CaptionedReferenceOptions {\n /** Drawn before the caption: a 14px icon. */\n icon: ReactNode\n /**\n * The chip's 14px icon from what it points at \u2014 its `uri` \u2014 when chips name\n * several kinds of thing; `undefined` from it, or no `iconFor`, draws `icon`.\n * The same answer the list's row gave (Katerina, 7 October).\n */\n iconFor?: (uri: string | null) => ReactNode | undefined\n /**\n * Draws the chip as the box's other links are drawn \u2014 the app's `referenceView`,\n * the kit's `LinkChip` \u2014 told it is being edited, so it shows no preview and a\n * click on it stays in the draft. Absent, or for a chip with no `uri`, the\n * caption with `icon`.\n */\n view?: ComponentType<ReferenceViewProps> | null\n}\n\n/** A click on a link inside a chip being written: the draft is not left for it (Katerina, 30 Oct). */\nfunction stayInDraft(event: MouseEvent) {\n if (event.target instanceof Element && event.target.closest('a[href]')) event.preventDefault()\n}\n\n/**\n * A reference mid-sentence, drawn as `label: snippet` and written as its `uri`\n * verbatim (SPEC \u00A713.1). The caption is the snapshot it was picked with \u2014 a\n * caption, never parsed. Inserted by {@link ReferenceTrigger}, a paste or a\n * draft; it opens no list of its own. With `view` it draws as the app draws\n * any other link in the box, so a `[` pick and a pasted link look alike.\n */\nexport const CaptionedReference = Mention.extend<MentionOptions & CaptionedReferenceOptions>({\n name: 'captionedReference',\n group: 'inline',\n inline: true,\n atom: true,\n addOptions() {\n return { ...this.parent!(), HTMLAttributes: {}, icon: null, iconFor: undefined, view: null, suggestion: { char: '\\0', items: () => [] } }\n },\n addAttributes() {\n return {\n id: { default: null, ...fromData('id') },\n label: { default: null, ...fromData('label') },\n snippet: { default: '', parseHTML: (element: HTMLElement) => element.getAttribute('data-snippet') ?? '', renderHTML: () => ({}) },\n uri: { default: null, ...fromData('uri', NOSTR_URI) },\n }\n },\n renderHTML({ node }) {\n return [\n 'span',\n { [`data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`]: 'true', 'data-id': String(node.attrs.id ?? ''), 'data-label': String(node.attrs.label ?? ''), 'data-snippet': String(node.attrs.snippet ?? ''), ...(node.attrs.uri ? { 'data-uri': String(node.attrs.uri) } : {}), class: inlineChipClassName('neutral', 'cursor-default') },\n captionOf(node.attrs.label, node.attrs.snippet),\n ]\n },\n parseHTML() {\n return [{ tag: `span[data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}]` }]\n },\n addNodeView() {\n const { icon, iconFor, view: View } = this.options\n return ReactNodeViewRenderer(\n ({ node }: ReactNodeViewProps) =>\n View && node.attrs.uri ? (\n <NodeViewWrapper as=\"span\" onClickCapture={stayInDraft}>\n <View uri={String(node.attrs.uri)} place=\"chip\" editing />\n </NodeViewWrapper>\n ) : (\n // The caption is cut at 24ch, so the whole of it is on hover, in the package's tooltip (UIG-14) \u2014 as Peek's sent chip has it.\n <NodeViewWrapper as=\"span\">\n <WithTooltip inline label={captionOf(node.attrs.label, node.attrs.snippet)}>\n <span className={inlineChipClassName('neutral', 'max-w-[24ch] cursor-default')}>\n <span className=\"flex items-center justify-center w-4 h-4 shrink-0 text-text-secondary\">{iconFor?.(node.attrs.uri ?? null) ?? icon}</span>\n <span className=\"truncate\">{captionOf(node.attrs.label, node.attrs.snippet)}</span>\n </span>\n </WithTooltip>\n </NodeViewWrapper>\n ),\n { as: 'span' },\n )\n },\n})\n\nexport interface ReferenceMenuOptions {\n /** Names the list, e.g. what can be referenced. */\n ariaLabel: string\n /** The section's heading. */\n sectionLabel: string\n /** At each row's start: a 16px icon \u2014 unless the row brings its own (`CaptionedItem.icon`), or `iconFor` answers. */\n icon: ReactNode\n /**\n * A row's 16px icon from what it points at \u2014 its `uri` \u2014 when the list holds\n * several kinds of thing; `undefined` from it draws `icon`. Give the chip the\n * same answer at 14px (`CaptionedReference`'s `iconFor`), so a pick keeps it.\n */\n iconFor?: (uri: string) => ReactNode | undefined\n}\n\n/** A row as the list holds it: which section it is drawn under, when the list has several. */\ntype ListedItem = CaptionedItem & { section?: string }\n\n/**\n * The list `[` opens: `label: snippet` rows, the same box as the people list.\n * One section headed `sectionLabel`, or \u2014 when the rows say which section they\n * are in \u2014 a heading for each, in the order the rows arrive.\n */\nexport function referenceMenu({ ariaLabel, sectionLabel, icon, iconFor }: ReferenceMenuOptions): SuggestionPopupOptions<CaptionedItem> {\n return {\n ariaLabel,\n width: 'w-[658px]',\n maxHeight: 'max-h-[360px]',\n sections: (items: ListedItem[]) => {\n const groups: { label: string; items: CaptionedItem[]; className: string }[] = []\n for (const item of items) {\n const label = item.section ?? sectionLabel\n const last = groups[groups.length - 1]\n if (last?.label === label) last.items.push(item)\n else groups.push({ label, items: [item], className: 'px-2' })\n }\n return groups\n },\n itemKey: (item) => `reference-${item.id}`,\n row: (item) => ({\n leading: item.icon ?? iconFor?.(item.uri) ?? icon,\n label: captionOf(item.label, item.snippet),\n // A summary is the second line, and where the thing sits moves up beside the label (SUM-7's story).\n ...(item.summary ? { description: item.summary, aside: item.description } : { description: item.description }),\n hint: <EnterHint />,\n }),\n }\n}\n\nexport interface ReferenceTriggerOptions extends ReferenceMenuOptions {\n /** Everything `[` can offer, asked each time the query changes. Narrowed by {@link filterReferences}. */\n items: () => readonly CaptionedItem[]\n /**\n * In place of `items`: the sections to draw for what was typed, already\n * narrowed and ordered by the app. Empty sections are not drawn.\n */\n sections?: (query: string) => readonly ReferenceSection[]\n /**\n * Called with a listener while the list is open; the app calls it when what\n * `sections` would answer has changed \u2014 a search landing \u2014 and the open list\n * is drawn again for the same query. Returns the unsubscribe.\n */\n subscribe?: (listener: () => void) => () => void\n /** The node a pick inserts. Default `captionedReference`. */\n nodeName: string\n}\n\nconst listed = (options: ReferenceTriggerOptions, query: string): ListedItem[] =>\n options.sections\n ? options.sections(query).flatMap((section) => section.items.map((item) => ({ ...item, section: section.label })))\n : filterReferences(options.items(), query)\n\n/**\n * `[` \u2014 reference something, inserted as a {@link CaptionedReference} chip.\n *\n * Its own extension rather than the chip's suggestion, so the chip's text (its\n * `renderText`) does not change with the key that summons the list.\n */\nexport const ReferenceTrigger = Extension.create<ReferenceTriggerOptions>({\n name: 'referenceTrigger',\n addOptions() {\n return { items: () => [], nodeName: 'captionedReference', ariaLabel: 'References', sectionLabel: 'References', icon: null }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n Suggestion<CaptionedItem>({\n editor: this.editor,\n char: '[',\n pluginKey: new PluginKey('referenceTrigger'),\n ...listening(']'),\n // As a mention's: only where the chip may go.\n allow: ({ state, range }) => {\n const type = state.schema.nodes[options.nodeName]\n return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type)\n },\n items: ({ query }) => listed(options, query),\n render: suggestionPopup({ ...referenceMenu(options), subscribe: options.subscribe, refresh: (query) => listed(options, query) }),\n command: ({ editor, range, props: item }) => {\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n { type: options.nodeName, attrs: { id: item.id, label: item.label, snippet: item.snippet, uri: item.uri } },\n { type: 'text', text: ' ' },\n ])\n .run()\n },\n }),\n ]\n },\n})\n\n// \u2500\u2500\u2500 / \u2500\u2500\u2500\n\n/** A row of the `/` list, and what choosing it does. */\nexport interface SlashCommand {\n key: string\n row: SuggestionMenuRow\n /** Matched beside the row's label: an id, a trigger, a description. */\n keywords?: readonly string[]\n /** Runs once the `/query` that summoned the list has been removed. */\n run: (editor: Editor) => void\n /**\n * The extensions (by name) the row needs: an editor without one of them is\n * not offered the row, so no row makes something the editor cannot hold.\n */\n needs?: readonly string[]\n}\n\n/** Whether an editor has every extension a row needs. */\nconst offers = (editor: Editor, command: SlashCommand) =>\n !command.needs || command.needs.every((name) => editor.extensionManager.extensions.some((extension) => extension.name === name))\n\nexport interface SlashSection {\n label: string\n commands: readonly SlashCommand[]\n}\n\nexport type FormatId = 'paragraph' | 'heading' | 'subheading' | 'quote' | 'bulletList' | 'orderedList' | 'code' | 'checklist' | 'note' | 'warning'\n\nexport interface FormatDef {\n id: FormatId\n label: string\n /** What you type to get it \u2014 the input rule the extension registers. Blank when there is none. */\n trigger?: string\n /** The trigger when the format makes a block instead \u2014 Code's fence. Blank when it is the same. */\n blockTrigger?: string\n}\n\n/**\n * The formats `/` offers, in order. The hint is what you would type, not a key\n * chord. Bold, italic and underline are absent: they act on text already\n * written, so they are the selection toolbar's.\n */\nexport const FORMATS: readonly FormatDef[] = [\n { id: 'paragraph', label: 'Text' },\n { id: 'heading', label: 'Heading', trigger: '#' },\n { id: 'subheading', label: 'Subheading', trigger: '##' },\n { id: 'quote', label: 'Quote', trigger: '>' },\n { id: 'code', label: 'Code', trigger: '`', blockTrigger: '```' },\n { id: 'bulletList', label: 'Bulleted list', trigger: '-' },\n { id: 'orderedList', label: 'Numbered list', trigger: '1.' },\n]\n\n/**\n * What only a document holds \u2014 a checklist item and a callout (RIC-19) \u2014 so\n * only a block editor's `/` offers them (`formatSection('block')`): a\n * message's text has no spelling for either. They need the `Checklist` and\n * `Callout` extensions. Note and Warning are the two callouts offered (Miky,\n * 2026-10-13); the other tones are read and kept, not offered.\n */\nexport const DOCUMENT_FORMATS: readonly FormatDef[] = [\n { id: 'checklist', label: 'Checklist', trigger: '[]' },\n { id: 'note', label: 'Note' },\n { id: 'warning', label: 'Warning' },\n]\n\n/** Code as a mark inside the line, or as a block of its own. */\nexport type CodeFormat = 'inline' | 'block'\n\n/**\n * Apply one format to the current block. `set*` wherever Tiptap has one:\n * choosing Heading should make a heading, not turn one off. `false` means\n * nothing changed, not that anything failed.\n */\nexport function applyFormat(editor: Editor, id: FormatId, code: CodeFormat = 'inline'): boolean {\n /*\n The node's own command, called by name: StarterKit's extensions declare\n them, and this package builds without StarterKit. Its own command, rather\n than the core one it wraps, because a list's runs with the app's options\n (`keepMarks`, `itemTypeName`). An editor without that node changes nothing.\n A chain per call: a chain holds the state it was made from, and a quote\n first takes its line out of a list.\n */\n const run = (command: string, ...args: unknown[]): boolean => {\n const chain = editor.chain().focus()\n const named = (chain as unknown as Record<string, ((...a: unknown[]) => { run: () => boolean }) | undefined>)[command]\n return named ? named(...args).run() : false\n }\n /*\n A list item's first line cannot be wrapped where it is, so Quote, Note and\n Warning did nothing in a bulleted line once the `/` was gone (LFB-3). The\n line leaves its list first, as Heading's and Code's already do \u2014 only in\n an editor that has a quote to make. Whether it left one.\n */\n const leaveList = (): boolean => {\n if (!editor.schema.nodes.blockquote) return false\n let left = false\n while (editor.isActive('listItem') && run('liftListItem', 'listItem')) left = true\n return left\n }\n switch (id) {\n case 'paragraph':\n return run('setParagraph')\n case 'heading':\n return run('setHeading', { level: 1 })\n case 'subheading':\n return run('setHeading', { level: 2 })\n case 'quote':\n // A list inside a quote: the line, out of its list, is already quoted, and toggling would unquote it.\n if (leaveList() && editor.isActive('blockquote')) return true\n return run('toggleBlockquote')\n case 'bulletList':\n return run('toggleBulletList')\n case 'orderedList':\n return run('toggleOrderedList')\n case 'code':\n return run(code === 'block' ? 'toggleCodeBlock' : 'toggleCode')\n case 'checklist': {\n // In a list, that item becomes one; elsewhere, the line becomes a list of one.\n if (!editor.isActive('listItem') && !run('toggleBulletList')) return false\n // An item already a checklist item keeps its tick.\n if (typeof editor.getAttributes('listItem').checked === 'boolean') return true\n return editor.chain().updateAttributes('listItem', { checked: false }).run()\n }\n case 'note':\n case 'warning': {\n leaveList()\n if (!editor.isActive('blockquote') && !run('toggleBlockquote')) return false\n return editor.chain().updateAttributes('blockquote', { tone: id }).run()\n }\n default:\n return false\n }\n}\n\n/** Words a row is also found by, beyond its id. */\nconst KEYWORDS: Partial<Record<FormatId, string[]>> = {\n checklist: ['todo', 'task'],\n note: ['callout'],\n warning: ['callout'],\n}\n\n/** The extension a row's block needs: without it the row would make a plain bullet or a plain quote (Katerina, review of #170). */\nconst NEEDS: Partial<Record<FormatId, string[]>> = {\n checklist: ['checklist'],\n note: ['callout'],\n warning: ['callout'],\n}\n\n/**\n * The Format section every app's `/` opens with. A block editor's also offers\n * a checklist and the callouts \u2014 only where the editor has the `Checklist` and\n * `Callout` extensions (`SlashCommand.needs`).\n */\nexport function formatSection(code: CodeFormat = 'inline'): SlashSection {\n return {\n label: 'Format',\n commands: (code === 'block' ? [...FORMATS, ...DOCUMENT_FORMATS] : FORMATS).map((format) => ({\n key: `format-${format.id}`,\n row: { label: format.label, shortcut: (code === 'block' && format.blockTrigger) || format.trigger },\n keywords: [format.id, ...(KEYWORDS[format.id] ?? [])],\n ...(NEEDS[format.id] ? { needs: NEEDS[format.id] } : {}),\n run: (editor) => {\n applyFormat(editor, format.id, code)\n },\n })),\n }\n}\n\n/** A row that types another trigger, so its own list opens \u2014 `@` from `/`. */\nexport function typeTrigger(input: string): SlashCommand['run'] {\n // Deferred a frame: the delete of the `/query` has to land first, or the\n // trigger's plugin sees the character arrive inside a range still being removed.\n return (editor) => {\n requestAnimationFrame(() => editor.commands.insertContent(input))\n }\n}\n\nfunction matches(command: SlashCommand, q: string): boolean {\n return [command.row.label, ...(command.keywords ?? [])].some((text) => text.toLowerCase().includes(q))\n}\n\n/** The sections narrowed to a query \u2014 the text typed after the `/`. Empty sections stay. */\nexport function filterSlashSections(sections: readonly SlashSection[], query: string): SlashSection[] {\n const q = query.toLowerCase()\n return sections.map((section) => ({ ...section, commands: q ? section.commands.filter((command) => matches(command, q)) : section.commands }))\n}\n\nexport interface SlashCommandsOptions {\n /** The sections, in order: {@link formatSection} first, then the app's own. */\n sections: readonly SlashSection[]\n}\n\ntype SlashRow = SlashCommand & { section: number }\n\n/**\n * `/` \u2014 format the line or insert something, at the caret, mid-sentence too.\n * A `/` inside a word (`and/or`, a path) opens nothing: the plugin wants a\n * space or the line's start before it.\n */\nexport const SlashCommands = Extension.create<SlashCommandsOptions>({\n name: 'slashCommands',\n addOptions() {\n return { sections: [formatSection()] }\n },\n addProseMirrorPlugins() {\n const sections = this.options.sections\n return [\n Suggestion<SlashRow>({\n editor: this.editor,\n char: '/',\n startOfLine: false,\n pluginKey: new PluginKey('slashCommands'),\n items: ({ query, editor }) =>\n filterSlashSections(sections, query).flatMap((section, at) =>\n section.commands.filter((command) => offers(editor, command)).map((command) => ({ ...command, section: at })),\n ),\n command: ({ editor, range, props }) => {\n editor.chain().focus().deleteRange(range).run()\n props.run(editor)\n },\n render: suggestionPopup<SlashRow>({\n ariaLabel: 'Commands',\n width: 'w-[300px]',\n maxHeight: 'max-h-[400px]',\n sections: (rows) => sections.map((section, at) => ({ label: section.label, items: rows.filter((row) => row.section === at) })),\n itemKey: (row) => row.key,\n row: (row) => row.row,\n }),\n }),\n ]\n },\n})\n", "import { Extension, type Mark } from '@tiptap/core'\nimport { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport StarterKit from '@tiptap/starter-kit'\nimport { WEB_LINK_CLASSES } from './looks'\n\n/*\n * Links in the kit's editors: a URL pasted over words, the link mark that holds\n * it, and a bare address drawn as a link. `CommentBox` and `DocumentEditor`\n * share the paste and the mark's end, so a link on words is made the same way\n * wherever it is written.\n */\n\n/** A link a message can carry on words, `[words](url)`: no `)` and no space in it (conversation's `composerText`). */\nconst LINK_ON_WORDS_TARGET = /^https?:\\/\\/[^\\s)]+$/\n\n/**\n * A URL pasted over words links them, as in Peek, when the message can carry\n * them as a link on words: plain words on one line, no chip, no line break, no\n * bracket, no code. Otherwise the words stay and the URL goes in after them,\n * so neither is lost. Ahead of StarterKit's own link-on-paste.\n */\nexport const PasteOverWords = Extension.create({\n name: 'commentBoxPasteOverWords',\n priority: 1001,\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('commentBoxPasteOverWords'),\n props: {\n handlePaste: (view, event) => {\n // A URL copied with the end of its sentence names what it names without it, as LinkChips reads one.\n const url = (event.clipboardData?.getData('text/plain').trim() ?? '').replace(/[.,;:!?]+$/, '')\n const { state } = view\n const { schema } = state\n if (state.selection.empty || !schema.marks.link || !/^https?:\\/\\/\\S+$/.test(url)) return false\n // Select-all spans the document itself: read it as the text it holds.\n const { $from, $to, from, to } = TextSelection.between(state.selection.$from, state.selection.$to)\n let plain = $from.sameParent($to) && $from.parent.isTextblock && !$from.parent.type.spec.code\n state.doc.nodesBetween(from, to, (node) => {\n // A quote or a list around the line holds it, and is not in the words: look inside.\n if (!node.isInline) return true\n if (!node.isText || node.marks.some((m) => m.type.spec.code || m.type.name === 'code')) plain = false\n return false\n })\n if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\\]\\n]/.test(state.doc.textBetween(from, to))) {\n // The caret goes after the link: left selected, the words open the selection strip's Link field,\n // which takes focus and the next Enter, so a box needed two to send (COMM-8).\n const tr = state.tr.addMark(from, to, schema.marks.link.create({ href: url }))\n view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to)).removeStoredMark(schema.marks.link))\n return true\n }\n const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, '', '\uFFFC')\n const inserted = before && !/\\s/.test(before) ? ` ${url}` : url\n const tr = state.tr.insertText(inserted, to)\n view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to + inserted.length)).scrollIntoView())\n return true\n },\n },\n }),\n ]\n },\n})\n\n/** StarterKit with a link that ends where its words end: what is typed after linked words is not linked (Peek's `inclusive: false`). */\nexport const BoxKit = StarterKit.extend({\n addExtensions() {\n return (this.parent?.() ?? []).map((extension) => (extension.name === 'link' ? extension.extend({ inclusive: () => false }) : extension))\n },\n})\n\n/**\n * {@link BoxKit} for a document: the same link, which also keeps `extra` \u2014\n * every key a saved link carries that this version does not know \u2014 so a save\n * writes it back. ProseMirror drops an attribute its schema does not name, and\n * the key with it. Protocol's `toEditorDocument(doc, { links: true })` fills it.\n */\nexport const DocumentKit = StarterKit.extend({\n addExtensions() {\n return (this.parent?.() ?? []).map((extension) =>\n extension.name === 'link'\n ? (extension as Mark).extend({\n inclusive: () => false,\n addAttributes() {\n return { ...this.parent?.(), extra: { default: null, rendered: false, parseHTML: () => null } }\n },\n })\n : extension,\n )\n },\n})\n\n/*\n * A bare address looks like a link while you write it, and a click opens it, as\n * a link in a read page does (Katerina, 30 September: the always-editable\n * description had made its links unclickable). Ship's `LinkDecoration`, moved\n * into the kit with the document editor.\n *\n * A decoration, not a mark: the address is saved as the text it is, byte for\n * byte. The patterns are `RichText`'s, so the editor marks what the reader links.\n */\nconst LINK_SPLIT = /\\[[^[\\]\\n]+\\]\\((?:https?:\\/\\/|mailto:)[^\\s)]+\\)|https?:\\/\\/[^\\s]+/g\n/** Punctuation after a bare address ends the sentence, not the address. */\nconst TRAILING = /[.,;:!?)\\]]+$/\n/** A link's look in an editor: the package `Link variant=\"text\"`, spelled out for a mark's element and a decoration's range, with the link icon and its underline as in `RichText`. */\nexport const LINK_CLASS = `text-info-default cursor-pointer ${WEB_LINK_CLASSES}`\n\n/** What a click may open: an address a reader may follow (SPEC \u00A713.1), never `javascript:` and the like. */\nconst OPENABLE = /^(https?:\\/\\/|mailto:)/i\n\n/** How a link mark is drawn in a document: the link look, a mark {@link BareLinks} recognises, and a new tab that cannot reach this one. */\nexport const LINK_MARK_ATTRIBUTES = { class: LINK_CLASS, 'data-link-mark': '', target: '_blank', rel: 'noopener noreferrer nofollow' }\n/** `[words](url)` names its address in the brackets; a bare address is its own. */\nconst LINK_TARGET = /\\]\\(([^\\s)]+)\\)$/\n\nexport const BareLinks = Extension.create({\n name: 'bareLinks',\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('bareLinks'),\n props: {\n // The one way a click opens an address: a bare one's decoration, or, while editing, a link on words (read only,\n // the link is a plain anchor and opens itself). Only its own attributes are read \u2014 never a chip's \u2014 and only an\n // address a reader may follow opens, always without handing the new tab this window.\n handleClick: (view, _pos, event) => {\n if (event.button !== 0) return false\n const target = event.target as HTMLElement | null\n const bare = target?.closest?.('[data-bare-link]')?.getAttribute('data-bare-link')\n const onWords = view.editable ? target?.closest?.('a[data-link-mark]')?.getAttribute('href') : null\n const href = bare ?? onWords\n if (!href || !OPENABLE.test(href)) return false\n window.open(href, '_blank', 'noopener,noreferrer')\n return true\n },\n decorations: ({ doc }) => {\n const found: Decoration[] = []\n doc.descendants((node, pos) => {\n if (!node.isText || !node.text) return\n // A code run is literal, so an address quoted as an example is not a link; one already linked is the mark's.\n if (node.marks.some((mark) => mark.type.name === 'code' || mark.type.name === 'link')) return\n for (const match of node.text.matchAll(LINK_SPLIT)) {\n if (match.index === undefined) continue\n const text = match[0].startsWith('[') ? match[0] : match[0].replace(TRAILING, '')\n const href = text.startsWith('[') ? (LINK_TARGET.exec(text)?.[1] ?? '') : text\n found.push(Decoration.inline(pos + match.index, pos + match.index + text.length, { class: LINK_CLASS, ...(href ? { 'data-bare-link': href } : {}) }))\n }\n })\n return found.length ? DecorationSet.create(doc, found) : null\n },\n },\n }),\n ]\n },\n})\n", "import { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\n/** As much of a `DataTransfer` as the paste reads. */\nexport interface ClipboardSource {\n files?: ArrayLike<File> | null\n getData(format: string): string\n}\n\n/** MIME type \u2192 the extension a pasted picture is named with. */\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/gif': 'gif',\n 'image/webp': 'webp',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'image/svg+xml': 'svg',\n}\n\n/** Names a browser invents for a clipboard picture. A made-up one is better. */\nconst GENERIC_STEMS = new Set(['image', 'blob', 'unknown', 'untitled', 'screenshot'])\n\n/*\n An unlisted type keeps its own subtype rather than becoming `png`, so a\n picture the app does not accept is refused by the app's own message instead\n of arriving disguised as one it does.\n*/\nfunction extensionFor(contentType: string): string {\n const type = contentType.toLowerCase()\n return IMAGE_EXTENSIONS[type] ?? type.split('/')[1]?.split('+')[0] ?? 'png'\n}\n\n/** `'Screenshot 2026-09-07 14-32-05.png'`: sortable, and readable on a file card. */\nexport function pastedImageName(contentType: string, at: Date = new Date(), index = 0): string {\n const pad = (n: number) => String(n).padStart(2, '0')\n const stamp =\n `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ` +\n `${pad(at.getHours())}-${pad(at.getMinutes())}-${pad(at.getSeconds())}`\n const nth = index > 0 ? ` (${index + 1})` : ''\n return `Screenshot ${stamp}${nth}.${extensionFor(contentType)}`\n}\n\n/** A real filename is kept; `image.png`, `blob` and '' are not names. */\nfunction hasUsableName(name: string): boolean {\n const dot = name.lastIndexOf('.')\n if (dot <= 0 || dot === name.length - 1) return false\n return !GENERIC_STEMS.has(name.slice(0, dot).toLowerCase())\n}\n\n/**\n * The pictures on the clipboard, named \u2014 `[]` when there is nothing to attach.\n *\n * **Text wins.** A copy from a spreadsheet or a document puts a rendered\n * picture of the selection beside the text; attaching the picture instead of\n * pasting the text is wrong every time. So a clipboard holding text is left to\n * the editor, and a screenshot, which holds none, lands here. Pictures only:\n * any other file comes through the app's own file picker.\n */\nexport function pastedImages(source: ClipboardSource | null | undefined, at: Date = new Date()): File[] {\n if (!source) return []\n if (source.getData('text/plain').trim() !== '') return []\n const images = Array.from(source.files ?? []).filter((f) => f.type.toLowerCase().startsWith('image/'))\n let generated = 0\n return images.map((file) =>\n hasUsableName(file.name)\n ? file\n : new File([file], pastedImageName(file.type, at, generated++), { type: file.type, lastModified: file.lastModified }),\n )\n}\n\nexport interface PastedImagesOptions {\n /**\n * The pictures a paste carried, named. Return `true` when the app took them\n * (an upload started), `false` to let the editor paste as it would have \u2014\n * for a box that cannot upload right now.\n */\n onImages: (files: File[]) => boolean\n}\n\n/**\n * Pasting a picture attaches it: a screenshot pasted into the editor reaches\n * the app as named files, the way the app's own file picker would hand them.\n * Text on the clipboard wins (see {@link pastedImages}).\n */\nexport const PastedImages = Extension.create<PastedImagesOptions>({\n name: 'pastedImages',\n addOptions() {\n return { onImages: () => false }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n new Plugin({\n key: new PluginKey('pastedImages'),\n props: {\n handlePaste: (_view, event) => {\n const files = pastedImages(event.clipboardData)\n return files.length > 0 && options.onImages(files)\n },\n },\n }),\n ]\n },\n})\n", "import { useCallback, useEffect, useImperativeHandle, useRef, useState, type Ref } from 'react'\nimport { Extension, Node } from '@tiptap/core'\nimport { history, redo, undo } from '@tiptap/pm/history'\nimport { EditorContent, useEditor } from '@tiptap/react'\nimport { cn } from './cn'\nimport { EDITOR_SELECTION_CLASSES } from './looks'\n\n/**\n * A line of plain text on a page that you edit where it stands, as in a\n * document: a title, a summary. Ship's title editor (Katerina, 29 September,\n * findings E1 and E2), moved here for the summary (Miky, 16 October: \"it feels\n * like a document, not a form\") so every app's header edits the same way.\n *\n * - **No box**, on hover or on click, and nothing moves: the text is the\n * editor, in its own size and colour. The text cursor is the only sign.\n * - **The caret goes where you click**, and nothing is selected.\n * - **Enter saves and moves on** \u2014 `onEnter` says where: the title to the\n * summary, the summary to the description.\n * - **Escape stops editing and keeps the text**, saving it, as leaving does.\n * Nothing is thrown away; Ctrl+Z undoes.\n * - **An unchanged value is not a write.** Leaving it empty brings the saved\n * one back, unless `clearable`: then empty is saved, as nothing.\n * - **A refused save keeps your text where it is**, and the app says why\n * beside it; a change made elsewhere does not overwrite it until you have\n * saved, changed or emptied it.\n *\n * One paragraph and no marks, so pasted line breaks become spaces and it wraps\n * like text, which a one-line `<input>` cannot. A Tiptap editor rather than a\n * raw `contenteditable`, so it is the same kind of surface as the description\n * under it.\n */\nexport interface InlineTextProps {\n /** The saved text. A new value is loaded when you are not in the field and hold nothing unsaved. */\n value: string\n /** What it is for, muted, while it is empty: \"Untitled\", \"Add a summary\". */\n placeholder: string\n /** The accessible name: \"Title\", \"Summary\". */\n label: string\n /** Save it: resolve `true` when saved; `false` keeps your text in place. */\n onCommit: (value: string) => Promise<boolean> | boolean\n /** The text as it is being written, on focus and every change; `null` when you leave. For a count. */\n onText?: (text: string | null) => void\n /** Enter, after the save has started: where the caret goes next. */\n onEnter?: () => void\n /**\n * `title`: the page's heading. `heading`: a document's title, at the largest heading size (Leaf's file page).\n * `summary`: the line under either, quieter.\n */\n variant?: 'title' | 'heading' | 'summary'\n /** Empty is a value (a summary). Otherwise leaving it empty brings the saved one back (a title). */\n clearable?: boolean\n /** Text only, the same size and place: nobody can change it, or the editor is not ready. */\n readOnly?: boolean\n /** Placement only. */\n className?: string\n ref?: Ref<InlineTextHandle>\n}\n\ntype CaretAt = 'start' | 'end'\n\nexport interface InlineTextHandle {\n /** Put the caret in it, at the start or the end. */\n focus: (at?: CaretAt) => void\n}\n\n/** Size and tone, per variant: the same for the text at rest and while it is written. */\nconst VARIANT = {\n title: 'text-h2 text-text-primary',\n // A document's title: Leaf set text-h1 on InlineText from outside, which the gate refuses (Katerina, 29 Oct: \"I choose A\").\n heading: 'text-h1 text-text-primary',\n summary: 'text-body-1 text-text-secondary',\n} as const\n\n/** The room around the text: the caret has a little space at the edges, and the text still lines up with what is above and below it. */\nconst ROOM = '-mx-2 px-2 py-1'\n\n// The whole schema: one paragraph of text. Written with the core, so the\n// package's peers stay what they were.\nconst OneLine = Node.create({ name: 'doc', topNode: true, content: 'paragraph' })\nconst Paragraph = Node.create({\n name: 'paragraph',\n content: 'text*',\n parseHTML: () => [{ tag: 'p' }],\n renderHTML: () => ['p', 0],\n})\nconst Text = Node.create({ name: 'text' })\nconst Undo = Extension.create({\n name: 'inlineTextUndo',\n addProseMirrorPlugins: () => [history()],\n addKeyboardShortcuts() {\n const run = (command: typeof undo) => () => command(this.editor.state, this.editor.view.dispatch)\n return { 'Mod-z': run(undo), 'Shift-Mod-z': run(redo), 'Mod-y': run(redo) }\n },\n})\n\nconst doc = (text: string) => ({ type: 'doc', content: [{ type: 'paragraph', content: text ? [{ type: 'text', text }] : [] }] })\n\n/** One line: every run of white space, line breaks included, is one space. */\nconst oneLine = (text: string) => text.replace(/\\s+/g, ' ').trim()\n\nexport function InlineText({ value, placeholder, label, onCommit, onText, onEnter, variant = 'title', clearable = false, readOnly = false, className, ref }: InlineTextProps) {\n const saved = useRef(value)\n // The placeholder follows the text as it is typed or deleted, not the saved value.\n const [empty, setEmpty] = useState(!value)\n // Read at key time: the editor's handlers are built once, and a prop they\n // closed over would be the first render's.\n const latest = useRef({ onEnter, onText, onCommit, clearable, value })\n latest.current = { onEnter, onText, onCommit, clearable, value }\n // The text being saved right now: Enter moves on, and the leave that follows\n // must not send the same save a second time while the first is in flight.\n const pending = useRef<string | null>(null)\n\n const save = useCallback(async (text: string) => {\n const next = oneLine(text)\n if (next === saved.current || next === pending.current) return\n if (!next && !latest.current.clearable) return\n pending.current = next\n try {\n if (await latest.current.onCommit(next)) saved.current = next\n } finally {\n if (pending.current === next) pending.current = null\n }\n }, [])\n\n const editor = useEditor({\n extensions: [OneLine, Paragraph, Text, Undo],\n content: doc(value),\n editable: !readOnly,\n editorProps: {\n attributes: {\n 'aria-label': label,\n role: 'textbox',\n 'aria-multiline': 'false',\n 'aria-placeholder': placeholder,\n ...(readOnly ? { 'aria-readonly': 'true' } : {}),\n class: cn('outline-none', EDITOR_SELECTION_CLASSES),\n },\n handleKeyDown: (view, event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void save(view.state.doc.textContent)\n latest.current.onEnter?.()\n return true\n }\n if (event.key === 'Escape') {\n view.dom.blur()\n return true\n }\n return false\n },\n // A paste is its plain text on this one line, whatever it was copied from.\n handlePaste: (view, event) => {\n const text = event.clipboardData?.getData('text/plain')\n if (text == null) return false\n view.dispatch(view.state.tr.insertText(text.replace(/\\s+/g, ' ')))\n return true\n },\n },\n onFocus: ({ editor: e }) => latest.current.onText?.(e.getText()),\n onUpdate: ({ editor: e }) => {\n setEmpty(e.isEmpty)\n latest.current.onText?.(e.getText())\n },\n onBlur: ({ editor: e }) => {\n latest.current.onText?.(null)\n // Left empty where empty is not a value: the saved text comes back, so\n // the page never shows the placeholder while everyone else sees the text.\n if (e.isEmpty && saved.current && !latest.current.clearable) {\n e.commands.setContent(doc(saved.current), { emitUpdate: false })\n setEmpty(false)\n return\n }\n // Left unchanged while someone else changed it: their text comes in now,\n // as it would have had you not been in it.\n const { value: current } = latest.current\n if (oneLine(e.getText()) === saved.current && current !== saved.current && pending.current === null) {\n e.commands.setContent(doc(current), { emitUpdate: false })\n saved.current = current\n setEmpty(!current)\n return\n }\n void save(e.getText())\n },\n }, [readOnly])\n\n // A change made elsewhere is loaded while you are not in the field and hold\n // nothing unsaved; your own save coming back is left alone.\n useEffect(() => {\n if (!editor || editor.isDestroyed || value === saved.current || editor.isFocused) return\n if (oneLine(editor.getText()) !== saved.current) return\n editor.commands.setContent(doc(value), { emitUpdate: false })\n saved.current = value\n setEmpty(!value)\n }, [editor, value])\n\n useImperativeHandle(ref, () => ({\n focus: (at = 'start') => editor?.commands.focus(at),\n }), [editor])\n\n return (\n <div className={cn('relative', VARIANT[variant], className)}>\n <EditorContent editor={editor} className={cn(ROOM, !readOnly && 'cursor-text')} />\n {/* Empty \u2014 never saved, or just deleted \u2014 shows what it is for, muted,\n and is not part of the text. Drawn over the editor, where the text starts. */}\n {empty && !readOnly && (\n <span aria-hidden className=\"pointer-events-none absolute left-0 top-1 text-text-muted\">{placeholder}</span>\n )}\n </div>\n )\n}\n", "import type { Editor } from '@tiptap/react'\nimport { Extension } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\n/**\n * Comments on a selection, drawn where they are, from Katerina's Leaf prototype\n * (9 October), with a run, whole blocks and changed words added for LEAF-7.\n *\n * A comment's place is the one SPEC \u00A713.6 gives it: a run of blocks, and the\n * words where the selection starts and where it ends as a quote. Words inside\n * one block are quoted whole; a selection across blocks quotes its start in\n * the first block and its end in the last; a selection of whole blocks quotes\n * nothing and is about the blocks. Nothing is written into the document: the\n * highlight is a decoration, so a save never carries it.\n *\n * Three places a comment can be in, as `@estiva-app/protocol`'s\n * `resolveCommentAnchor` reads them:\n * - **resolved** \u2014 its words are found (drawn on them), or it quotes none\n * (drawn on its whole blocks);\n * - **reworded** \u2014 its blocks are there and its words are not: nothing is\n * drawn, and the comment stands beside its first block;\n * - **detached** \u2014 none of its blocks is left.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-comment-remembers-where-its-selection-starts-and-ends.md\n */\n\n/** The words a comment quotes: \u00A713.6's `quote` tag. */\nexport interface CommentQuote {\n /** The selection's words in one block, or its first words when it runs across blocks. */\n start: string\n /** Its last words, in the run's last block. Absent: `start` is the whole selection. */\n end?: string\n /** A few characters before `start`, only when the words repeat in their block. */\n prefix?: string\n /** A few characters after the end, only when the words repeat in their block. */\n suffix?: string\n}\n\n/** One comment's place: the blocks it is anchored to and the words it is about. */\nexport interface CommentAnchor {\n /** The thread's id. Clicks report it; `active` names it. */\n id: string\n /** The run: the \u00A713.3 block ids the comment's `block` tag lists, in order. */\n blocks: readonly string[]\n /** The words, as they were when the comment was written. Absent: the whole blocks. */\n quote?: CommentQuote\n}\n\n/** Where a comment is now, in document positions. */\nexport type CommentPlace =\n /** Drawn: on its words (`words`), or on its whole blocks. */\n | { state: 'resolved'; from: number; to: number; words: boolean }\n /** Its blocks (`from`\u2013`to`) are there, its words are not. Draw nothing; show the quote as the commenter's. */\n | { state: 'reworded'; from: number; to: number }\n /** None of its blocks is left. */\n | { state: 'detached' }\n\ninterface HighlightState {\n anchors: readonly CommentAnchor[]\n active: string | null\n}\n\nconst commentHighlightsKey = new PluginKey<HighlightState>('commentHighlights')\n\n/**\n * The highlight's two looks: every commented selection, and the one being\n * read. A block carries the same classes as words do: its underline reaches\n * every line of its text.\n */\nconst COMMENT_HIGHLIGHT_CLASSES = {\n rest: 'cursor-pointer rounded-sm bg-warning-muted',\n active: 'cursor-pointer rounded-sm bg-warning-muted underline decoration-warning-default decoration-2 underline-offset-4',\n} as const\n\n/** Up to this many characters, a selection in one block is quoted whole (\u00A713.6). */\nconst QUOTE_WHOLE_MAX = 1000\n/** Otherwise about this many at each end, cut at a word. */\nconst QUOTE_END_LENGTH = 150\n/** How much of the text around repeated words is kept to tell them apart. */\nconst QUOTE_CONTEXT_LENGTH = 32\n\n/** A block with an id: where it is, where its parent's content starts, and its index there. */\ninterface Place {\n node: ProseMirrorNode\n pos: number\n parent: number\n index: number\n}\n\n/** Every block carrying an id, by id. */\nfunction placesIn(doc: ProseMirrorNode): Map<string, Place> {\n const places = new Map<string, Place>()\n const walk = (parent: ProseMirrorNode, parentPos: number) => {\n parent.forEach((node, offset, index) => {\n const pos = parentPos + offset\n const id = node.attrs.blockId\n if (typeof id === 'string' && id && !places.has(id)) places.set(id, { node, pos, parent: parentPos, index })\n if (!node.isTextblock && !node.isLeaf) walk(node, pos + 1)\n })\n }\n walk(doc, 0)\n return places\n}\n\n/**\n * A block's text, and the document position where each of its characters\n * starts and ends. It is the text the protocol's `inlineTextOf` reads from the\n * same block on the wire, or a quote written here would not be found there: a\n * chip counts as the text it is on the wire (a URL chip its URL, any other its\n * `nostr:` reference), a line break as `\\n`, and the blocks inside a block (a\n * quote's lines, a list's items, a table's cells) are joined with `\\n`. A list\n * item is its own text: the list inside it is flat on the wire, its items\n * following it in the list.\n */\nfunction textOf(block: Place): { text: string; starts: number[]; ends: number[] } {\n let text = ''\n const starts: number[] = []\n const ends: number[] = []\n const add = (chars: string, start: number, end: number) => {\n for (let i = 0; i < chars.length; i++) (starts.push(start), ends.push(end))\n text += chars\n }\n const walk = (node: ProseMirrorNode, pos: number) => {\n if (node.isTextblock) {\n node.forEach((child, offset) => {\n const at = pos + 1 + offset\n if (child.isText && child.text) {\n for (let i = 0; i < child.text.length; i++) (starts.push(at + i), ends.push(at + i + 1))\n text += child.text\n } else if (child.type.name === 'hardBreak') add('\\n', at, at + child.nodeSize)\n else if (child.isInline && child.isLeaf) add(String(child.attrs.href || child.attrs.uri || ''), at, at + child.nodeSize)\n })\n return\n }\n // A list item's paragraphs are one run on the wire, with nothing between them.\n if (node.type.name === 'listItem') {\n node.forEach((child, offset) => void (LISTS.has(child.type.name) || walk(child, pos + 1 + offset)))\n return\n }\n const children = LISTS.has(node.type.name) ? itemsOf(node, pos) : childrenOf(node, pos)\n children.forEach(({ node: child, pos: at }, index) => {\n // Between two blocks: the boundary, where neither one's text is.\n if (index > 0) add('\\n', at, at)\n walk(child, at)\n })\n }\n walk(block.node, block.pos)\n return { text, starts, ends }\n}\n\n/** The lists whose nested items the wire holds flat, after the item they are in. */\nconst LISTS = new Set(['bulletList', 'orderedList'])\n\nfunction childrenOf(node: ProseMirrorNode, pos: number): { node: ProseMirrorNode; pos: number }[] {\n const out: { node: ProseMirrorNode; pos: number }[] = []\n node.forEach((child, offset) => void out.push({ node: child, pos: pos + 1 + offset }))\n return out\n}\n\n/** A list's items as the wire lists them: each one, then the items of a list inside it. */\nfunction itemsOf(list: ProseMirrorNode, pos: number): { node: ProseMirrorNode; pos: number }[] {\n return childrenOf(list, pos).flatMap((item) => [item, ...childrenOf(item.node, item.pos).flatMap((c) => (LISTS.has(c.node.type.name) ? itemsOf(c.node, c.pos) : []))])\n}\n\n/** Where `words` sits in `text` at or after `from`: the occurrence whose context matches, else the first. */\nfunction find(text: string, words: string, from: number, context: (at: number) => boolean): number {\n let first = -1\n for (let at = text.indexOf(words, from); at !== -1; at = text.indexOf(words, at + 1)) {\n if (first === -1) first = at\n if (context(at)) return at\n }\n return first\n}\n\n/**\n * The run as \u00A713.3 reads it: the parent holding most of its listed blocks, and\n * every block there from the earliest listed one to the latest. Null when none\n * is left.\n */\nfunction runIn(doc: ProseMirrorNode, places: Map<string, Place>, ids: readonly string[]): Place[] | null {\n const present = ids.map((id) => places.get(id)).filter((p): p is Place => !!p)\n if (present.length === 0) return null\n const byParent = new Map<number, Place[]>()\n for (const p of present) byParent.set(p.parent, [...(byParent.get(p.parent) ?? []), p])\n const group = [...byParent.values()].reduce((best, one) => (one.length > best.length ? one : best))\n const low = Math.min(...group.map((p) => p.index))\n const high = Math.max(...group.map((p) => p.index))\n // `parent` is where the parent's content starts: 0 for the document itself.\n const contentStart = group[0].parent\n const parent = contentStart === 0 ? doc : doc.nodeAt(contentStart - 1)\n if (!parent) return group\n const run: Place[] = []\n parent.forEach((node, offset, index) => {\n if (index >= low && index <= high) run.push({ node, pos: contentStart + offset, parent: contentStart, index })\n })\n return run\n}\n\n/** Where a comment is in this document. */\nfunction placeOf(doc: ProseMirrorNode, anchor: CommentAnchor, places = placesIn(doc)): CommentPlace {\n const run = runIn(doc, places, anchor.blocks)\n if (!run) return { state: 'detached' }\n const from = run[0].pos\n const to = run[run.length - 1].pos + run[run.length - 1].node.nodeSize\n const { quote } = anchor\n if (!quote) return { state: 'resolved', from, to, words: false }\n\n const reworded: CommentPlace = { state: 'reworded', from, to }\n const firstId = anchor.blocks[0]\n const lastId = anchor.blocks[anchor.blocks.length - 1]\n const first = run.findIndex((p) => p.node.attrs.blockId === firstId)\n const last = run.findIndex((p) => p.node.attrs.blockId === lastId)\n if (first === -1 || last === -1 || last < first) return reworded\n const a = textOf(run[first])\n const b = first === last ? a : textOf(run[last])\n // Context longer than a writer ever sends is a stranger's, and ignored, as the protocol's `resolveCommentAnchor` does.\n const prefix = quote.prefix && quote.prefix.length <= QUOTE_CONTEXT_LENGTH ? quote.prefix : undefined\n const suffix = quote.suffix && quote.suffix.length <= QUOTE_CONTEXT_LENGTH ? quote.suffix : undefined\n const before = (text: string, i: number) => !prefix || text.slice(Math.max(0, i - prefix.length), i) === prefix\n const after = (text: string, i: number) => !suffix || text.slice(i, i + suffix.length) === suffix\n\n if (quote.end === undefined) {\n const at = find(a.text, quote.start, 0, (i) => before(a.text, i) && after(a.text, i + quote.start.length))\n if (at === -1 || quote.start === '') return reworded\n return { state: 'resolved', from: a.starts[at], to: a.ends[at + quote.start.length - 1], words: true }\n }\n const startAt = find(a.text, quote.start, 0, (i) => before(a.text, i))\n if (startAt === -1 || quote.start === '') return reworded\n const endFrom = first === last ? startAt + quote.start.length : 0\n const endAt = find(b.text, quote.end, endFrom, (i) => after(b.text, i + quote.end!.length))\n if (endAt === -1 || quote.end === '') return reworded\n return { state: 'resolved', from: a.starts[startAt], to: b.ends[endAt + quote.end.length - 1], words: true }\n}\n\ndeclare module '@tiptap/core' {\n interface EditorEvents {\n /** A comment's highlight was clicked: `editor.on('commentSelect', ({ id }) => \u2026)`. */\n commentSelect: { id: string }\n }\n}\n\nexport interface CommentHighlightsOptions {\n /** A highlight was clicked: the thread to show. Or listen for the editor's `commentSelect`. */\n onSelect: ((id: string) => void) | null\n}\n\n/** The extension an editor registers to draw comments where they are. */\nexport const CommentHighlights = Extension.create<CommentHighlightsOptions>({\n name: 'commentHighlights',\n\n addOptions() {\n return { onSelect: null }\n },\n\n addProseMirrorPlugins() {\n const options = this.options\n const editor = this.editor\n return [\n new Plugin<HighlightState>({\n key: commentHighlightsKey,\n state: {\n init: () => ({ anchors: [], active: null }),\n apply(tr, previous) {\n const meta = tr.getMeta(commentHighlightsKey) as HighlightState | undefined\n return meta ?? previous\n },\n },\n props: {\n decorations(state) {\n const { anchors, active } = commentHighlightsKey.getState(state) ?? { anchors: [], active: null }\n const places = placesIn(state.doc)\n const drawn = anchors.flatMap((anchor) => {\n const place = placeOf(state.doc, anchor, places)\n if (place.state !== 'resolved') return []\n const attrs = { class: anchor.id === active ? COMMENT_HIGHLIGHT_CLASSES.active : COMMENT_HIGHLIGHT_CLASSES.rest, 'data-comment-id': anchor.id }\n if (place.words) return [Decoration.inline(place.from, place.to, attrs)]\n // Whole blocks: each block of the run carries the look itself.\n const blocks: Decoration[] = []\n state.doc.nodesBetween(place.from, place.to, (node, pos) => {\n if (pos < place.from || pos + node.nodeSize > place.to) return true\n blocks.push(Decoration.node(pos, pos + node.nodeSize, attrs))\n return false\n })\n return blocks\n })\n return drawn.length ? DecorationSet.create(state.doc, drawn) : null\n },\n handleClick(view, pos) {\n const { anchors } = commentHighlightsKey.getState(view.state) ?? { anchors: [] }\n const places = placesIn(view.state.doc)\n // The narrowest drawn comment under the click: words before the paragraph around them.\n let hit: { id: string; size: number } | null = null\n for (const anchor of anchors) {\n const place = placeOf(view.state.doc, anchor, places)\n if (place.state !== 'resolved' || pos < place.from || pos >= place.to) continue\n const size = place.to - place.from\n if (!hit || size < hit.size) hit = { id: anchor.id, size }\n }\n if (hit) {\n options.onSelect?.(hit.id)\n editor.emit('commentSelect', { id: hit.id })\n }\n return false\n },\n },\n }),\n ]\n },\n})\n\n/** Draw these comments, `active` the one being read. */\nexport function setCommentAnchors(editor: Editor, anchors: readonly CommentAnchor[], active: string | null = null) {\n if (editor.isDestroyed) return\n editor.view.dispatch(editor.state.tr.setMeta(commentHighlightsKey, { anchors, active }))\n}\n\n/** Where a comment is now: on its words or blocks, beside its blocks with its words gone, or detached. */\nexport function commentPlace(editor: Editor, anchor: CommentAnchor): CommentPlace {\n return placeOf(editor.state.doc, anchor)\n}\n\n/**\n * What a comment's card stands beside: its drawn highlight, or \u2014 its words\n * gone \u2014 its first block. Null when it is detached.\n */\nexport function commentElement(editor: Editor, anchor: CommentAnchor): HTMLElement | null {\n const drawn = editor.view.dom.querySelector<HTMLElement>(`[data-comment-id=\"${CSS.escape(anchor.id)}\"]`)\n if (drawn) return drawn\n const place = placeOf(editor.state.doc, anchor)\n if (place.state === 'detached') return null\n const dom = editor.view.nodeDOM(place.from)\n return dom instanceof HTMLElement ? dom : null\n}\n\n/** A quote in one line, as a card says it: its start and end words around an ellipsis. */\nexport function quoteText(quote: CommentQuote): string {\n return quote.end ? `${quote.start} \u2026 ${quote.end}` : quote.start\n}\n\n/** At most `length` characters from the front of `text`, cut back to a word when one is near. */\nfunction headOf(text: string, length: number): string {\n if (text.length <= length) return text\n const cut = text.lastIndexOf(' ', length)\n return text.slice(0, cut > length / 2 ? cut : length)\n}\n\n/** At most `length` characters from the back of `text`, cut forward to a word when one is near. */\nfunction tailOf(text: string, length: number): string {\n if (text.length <= length) return text\n const from = text.length - length\n const cut = text.indexOf(' ', from)\n return text.slice(cut !== -1 && cut < from + length / 2 ? cut + 1 : from)\n}\n\nfunction occurrences(text: string, words: string): number {\n let count = 0\n for (let at = text.indexOf(words); words && at !== -1; at = text.indexOf(words, at + 1)) count++\n return count\n}\n\n/** How many characters of `block`'s text come before document position `pos`. */\nfunction offsetIn(block: { starts: number[] }, pos: number): number {\n const at = block.starts.findIndex((start) => start >= pos)\n return at === -1 ? block.starts.length : at\n}\n\n/** What a comment on the selection would carry: its run, and its words unless it covers whole blocks. */\nexport interface SelectionAnchor {\n blocks: string[]\n quote?: CommentQuote\n}\n\n/**\n * The anchor a comment on the selection carries, as \u00A713.6 writes it: the\n * selected blocks, and the selected words in one block or the words where it\n * starts and ends across several. No quote when whole blocks are selected.\n * Null when nothing is selected or a selected block has no id.\n */\nexport function anchorOfSelection(editor: Editor): SelectionAnchor | null {\n const { doc, selection } = editor.state\n if (selection.empty) return null\n const { $from, $to } = selection\n const places = placesIn(doc)\n // The block with an id at or around `depth`: the lines of a quote or a list\n // item are paragraphs with no id of their own, and belong to it.\n const around = (depth: number): Place | undefined => {\n for (let d = depth; d > 0; d--) {\n const id = $from.node(d).attrs.blockId\n if (typeof id === 'string' && id && places.has(id)) return places.get(id)\n }\n return undefined\n }\n // The blocks the selection runs across: children of the deepest node holding\n // both ends, or \u2014 both ends in one textblock, or in blocks with no ids \u2014 the\n // block with an id around them.\n let run: Place[]\n if ($from.parent === $to.parent && $from.parent.isTextblock) {\n const found = around($from.depth)\n if (!found) return null\n run = [found]\n } else {\n const depth = $from.sharedDepth($to.pos)\n const low = $from.index(depth)\n const high = $to.pos >= $to.end(depth) ? $from.node(depth).childCount - 1 : $to.index(depth)\n run = []\n for (let i = low; i <= high; i++) {\n const id = $from.node(depth).child(i).attrs.blockId\n const place = typeof id === 'string' ? places.get(id) : undefined\n if (!place) {\n const found = around(depth)\n if (!found) return null\n run = [found]\n break\n }\n run.push(place)\n }\n }\n let firstText = textOf(run[0])\n let lastText = run.length === 1 ? firstText : textOf(run[run.length - 1])\n let start = offsetIn(firstText, selection.from)\n let end = offsetIn(lastText, selection.to)\n // A block the selection only touches at its edge holds none of it: it is not\n // in the run. The same rule as the protocol's `selectionAnchorTags`.\n if (run.length > 1 && start >= firstText.text.length) ((run = run.slice(1)), (firstText = textOf(run[0])), (start = 0))\n if (run.length > 1 && end <= 0) ((run = run.slice(0, -1)), (lastText = textOf(run[run.length - 1])), (end = lastText.text.length))\n if (run.length === 1) lastText = firstText\n // Between two blocks, with no character selected: nothing to comment on.\n if (run.length === 1 && firstText.text && start >= end) return null\n // Only a line break, or the edge between two lines of one block: no word to comment on either.\n if (run.length === 1 && firstText.text && !firstText.text.slice(start, end).replace(/\\n/g, '')) return null\n const blocks = run.map((p) => p.node.attrs.blockId as string)\n if (start === 0 && end >= lastText.text.length) return { blocks }\n\n const single = run.length === 1\n const quote: CommentQuote = { start: '' }\n if (single && end - start <= QUOTE_WHOLE_MAX) {\n quote.start = firstText.text.slice(start, end)\n } else {\n const startWords = single ? firstText.text.slice(start, end) : firstText.text.slice(start)\n const endWords = single ? startWords : lastText.text.slice(0, end)\n quote.start = headOf(startWords, QUOTE_END_LENGTH)\n quote.end = tailOf(endWords, QUOTE_END_LENGTH)\n }\n if (!quote.start || quote.end === '') return { blocks }\n const prefix = firstText.text.slice(Math.max(0, start - QUOTE_CONTEXT_LENGTH), start)\n const suffix = lastText.text.slice(end, end + QUOTE_CONTEXT_LENGTH)\n if (prefix && occurrences(firstText.text, quote.start) > 1) quote.prefix = prefix\n if (suffix && occurrences(lastText.text, quote.end ?? quote.start) > 1) quote.suffix = suffix\n return { blocks, quote }\n}\n", "import { Extension, type JSONContent } from '@tiptap/core'\nimport { Slice, type ResolvedPos } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\nexport interface PastedMarkdownOptions {\n /**\n * Plain text read as the blocks it spells, as editor JSON (`{ type: 'doc',\n * content }`), or `undefined` to paste it as text. The app passes its\n * protocol's reader \u2014 for a block document, `@estiva-app/protocol`'s\n * `descriptionTextToBlockDocument` through `toEditorDocument` \u2014 so a paste\n * reads text exactly as the agent's write of the same text does.\n */\n read: (text: string) => JSONContent | undefined\n}\n\n/** Inside a table cell: a pasted table there stays text, never a table in a table. */\nfunction inTableCell($context: ResolvedPos): boolean {\n for (let depth = $context.depth; depth > 0; depth--) {\n const role = $context.node(depth).type.spec.tableRole\n if (role === 'cell' || role === 'header_cell') return true\n }\n return false\n}\n\nconst hasTable = (blocks: JSONContent[]): boolean => blocks.some((block) => block.type === 'table' || hasTable(block.content ?? []))\n\n/**\n * Markdown pasted as plain text lands as what it spells: a heading, a list, a\n * checklist, a quote or callout, a table (LEAF-10; Miky, 2026-10-15). Only a\n * paste with no HTML on the clipboard is read \u2014 a copy from a web page already\n * pastes its own structure \u2014 and a paste that spells nothing but paragraphs\n * pastes exactly as before. Ctrl/Cmd+Shift+V, the plain-text paste, keeps the\n * text as typed, and so does a paste into code.\n *\n * For an editor that saves a block document. A message box leaves it out: a\n * message's text has no table (SPEC \u00A713.2), so a pasted table stays text there.\n */\nexport const PastedMarkdown = Extension.create<PastedMarkdownOptions>({\n name: 'pastedMarkdown',\n addOptions() {\n return { read: () => undefined }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n new Plugin({\n key: new PluginKey('pastedMarkdown'),\n props: {\n // Reached only for a text paste outside code; `plain` is the Shift paste.\n clipboardTextParser: (text, $context, plain, view) => {\n if (plain) return undefined as unknown as Slice\n try {\n const blocks = options.read(text.replace(/\\r\\n?/g, '\\n'))?.content ?? []\n // Paragraphs only: the editor's own paste keeps each line a paragraph, and its paste rules make `**bold**` bold.\n if (blocks.every((block) => block.type === 'paragraph')) return undefined as unknown as Slice\n if (inTableCell($context) && hasTable(blocks)) return undefined as unknown as Slice\n return Slice.maxOpen(view.state.schema.nodeFromJSON({ type: 'doc', content: blocks }).content)\n } catch {\n // A reader that throws, or a block this editor's schema does not\n // hold (a table without TableKit): paste the text.\n return undefined as unknown as Slice\n }\n },\n },\n }),\n ]\n },\n})\n", "/** The editor's code block, coloured by language like RichText's (`@estiva-app/ui/editor`). */\nimport { CodeBlockLowlight } from '@tiptap/extension-code-block-lowlight'\nimport { lowlight } from './codeColours'\n\n/*\n The editor library guesses a language for a block that names none, or names\n one it does not know, and colours it by the guess. RichText never guesses, so\n that block was coloured while written and plain once read. A block is\n coloured only by the language it names, while written and when read\n (Katerina, 9 October: never guess).\n*/\nconst namedOnly = {\n highlight: (language: string, value: string) => lowlight().highlight(language, value),\n highlightAuto: (value: string) => ({ type: 'root' as const, children: [{ type: 'text' as const, value }], data: { language: undefined, relevance: 0 } }),\n listLanguages: () => lowlight().listLanguages(),\n registered: (language: string) => lowlight().registered(language),\n}\n\n/**\n * A code block in the editor, with the colours RichText reads it in (Katerina,\n * 9 October): the same highlight.js languages, the same classes, and the\n * editor's root wears `richTextClassName`, which colours them.\n *\n * It replaces the starter kit's code block: `StarterKit.configure({ codeBlock: false })`,\n * then add `CodeBlockColours`. The block keeps its name, `codeBlock`, and its\n * `language` attribute, so nothing already written changes.\n */\nexport const CodeBlockColours = CodeBlockLowlight.configure({ lowlight: namedOnly })\n", "import { createElement, type ReactNode } from 'react'\nimport { common, createLowlight } from 'lowlight'\n\n/**\n * Colours inside a code block, by language (Katerina, 9 October).\n *\n * highlight.js reads the code and names each word (a keyword, a string, a\n * comment); RichText's class list gives each name its colour from the theme's\n * `syntax-*` tokens. The same instance colours the editor's code block\n * (`CodeBlockColours`), so what is written looks the same as what is read.\n *\n * `common` is highlight.js's 37 everyday languages. A language outside them, or\n * none, leaves the code in one colour.\n *\n * Made the first time code is coloured, not when the package loads: a call at\n * the top of the file is kept by every app's bundler, so an app that never draws\n * code carried highlight.js too (measured: an app importing only `Link` was\n * 55 KB gzipped).\n */\nlet instance: ReturnType<typeof createLowlight> | undefined\nexport function lowlight() {\n return (instance ??= createLowlight(common))\n}\n\ninterface HastNode {\n type: string\n value?: string\n properties?: { className?: string[] }\n children?: HastNode[]\n}\n\nfunction draw(node: HastNode, key: number): ReactNode {\n if (node.type === 'text') return node.value\n return createElement('span', { key, className: node.properties?.className?.join(' ') }, (node.children ?? []).map(draw))\n}\n\n/** The code, its words wrapped in highlight.js's classes; the text as it is when the language is unknown. */\nexport function codeColours(text: string, language?: string): ReactNode {\n if (!language || !lowlight().registered(language)) return text\n return (lowlight().highlight(language, text).children as HastNode[]).map(draw)\n}\n", "import { useMemo, type ReactNode } from 'react'\nimport type { Editor } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { IconCopy, IconTrash } from '@tabler/icons-react'\nimport { BlockHandle, blockAtY, type BlockHandleEditing, type HandleBlock } from './BlockHandle'\nimport { Selection } from '@tiptap/pm/state'\nimport { MenuItem, MenuSub } from './Menu'\nimport { DOCUMENT_FORMATS, FORMATS, applyFormat, type FormatId } from './ComposerTriggers'\n\n/** A row of the block menu's Turn into: what the block becomes. */\nexport interface BlockTurnInto {\n label: string\n /**\n * Turns the block. The handle puts the caret in a block of text first, so a\n * row for one can act at the caret; `pos` is where the block starts, for a\n * list or a quote, whose row acts on the whole block.\n */\n run: (editor: Editor, pos: number) => void\n /** Whether the block already is this \u2014 drawn as the selected row. */\n active?: (node: ProseMirrorNode) => boolean\n}\n\nexport interface EditorBlockHandleProps {\n /** The editor. Not editable, or not there yet, and the handle reads: the caller's rows only. */\n editor: Editor | null\n /**\n * Turn into's rows for a block. By default `turnIntoRows`, the same in every\n * app: a block of text, a list and a quote each get theirs. A list of rows\n * instead is offered for a block of text only; `[]` offers none.\n */\n turnInto?: readonly BlockTurnInto[] | ((node: ProseMirrorNode, editor: Editor) => readonly BlockTurnInto[])\n /** The caller's own rows, after the editing ones. */\n actions?: (block: HandleBlock) => ReactNode\n /** The `EditorContent`. */\n children: ReactNode\n className?: string\n}\n\n/** The editor's top-level blocks, where each starts and what it is. */\nfunction editorBlocks(view: EditorView): HandleBlock[] {\n const out: HandleBlock[] = []\n view.state.doc.forEach((node, pos) => {\n const element = view.nodeDOM(pos)\n if (element instanceof HTMLElement) out.push({ id: (node.attrs.blockId as string | null) || undefined, element, pos })\n })\n return out\n}\n\n/*\n Duplicate and Delete leave the editor focused, as Turn into and a drop do: the\n person is still in the field, so an editor that saves when they leave it saves\n these too \u2014 and one that loads someone else's edit while unfocused does not\n load it over them.\n*/\n\n/** A copy of the block straight after it, the caret in the copy. `BlockId` gives the copy a fresh id; the original keeps its own. */\nexport function duplicateBlock(editor: Editor, pos: number): boolean {\n const node = editor.state.doc.nodeAt(pos)\n if (!node) return false\n editor.view.dispatch(editor.state.tr.insert(pos + node.nodeSize, node).scrollIntoView())\n editor.commands.focus(pos + node.nodeSize + 1)\n return true\n}\n\n/** Removes the block, the caret where it was. The last block of a document becomes an empty paragraph, since a document holds at least one. */\nexport function deleteBlock(editor: Editor, pos: number): boolean {\n const { state } = editor\n const node = state.doc.nodeAt(pos)\n if (!node) return false\n const tr = state.doc.childCount === 1 ? state.tr.replaceWith(pos, pos + node.nodeSize, state.schema.nodes.paragraph.create()) : state.tr.delete(pos, pos + node.nodeSize)\n editor.view.dispatch(tr)\n editor.commands.focus(Math.min(pos + 1, editor.state.doc.content.size))\n return true\n}\n\n/**\n * Moves the block at `from` to `to` (a position between top-level blocks), the\n * caret in it: what a drop in the gutter does, where the editor has no drop of\n * its own. The node moves whole, attributes and all, so it keeps its id, as\n * ProseMirror's drop keeps it.\n */\nexport function moveBlock(editor: Editor, from: number, to: number): boolean {\n const node = editor.state.doc.nodeAt(from)\n if (!node || (to >= from && to <= from + node.nodeSize)) return false\n const tr = editor.state.tr.delete(from, from + node.nodeSize)\n const at = tr.mapping.map(to)\n editor.view.dispatch(tr.insert(at, node).scrollIntoView())\n editor.commands.focus(at + 1)\n return true\n}\n\n/**\n * Starts the browser's own drag of the block, as ProseMirror starts one of a\n * selected node: the block selected, its slice on `view.dragging` with `move`,\n * and its HTML on the transfer. ProseMirror's drop then deletes the selection\n * and inserts the slice with its attributes \u2014 so the block arrives with the\n * id it left with, and every comment anchored to it still finds it.\n */\nexport function startBlockDrag(editor: Editor, pos: number, event: Pick<globalThis.DragEvent, 'dataTransfer'>, image?: Element) {\n editor.commands.setNodeSelection(pos)\n const { view } = editor\n const slice = view.state.selection.content()\n const { dom, text } = view.serializeForClipboard(slice)\n const transfer = event.dataTransfer\n if (transfer) {\n transfer.clearData()\n transfer.setData('text/html', dom.innerHTML)\n transfer.setData('text/plain', text)\n transfer.effectAllowed = 'copyMove'\n if (image) transfer.setDragImage(image, 0, 0)\n }\n view.dragging = { slice, move: true }\n}\n\n/**\n * The drop line a dragged block shows, in the package's accent instead of the\n * editor's default (the text's colour). Give it to the editor's StarterKit:\n * `StarterKit.configure({ dropcursor: blockDropCursor })`.\n */\nexport const blockDropCursor = { color: false, class: 'bg-accent-primary' } as const\n\nconst NOTHING_YET: BlockHandleEditing = { find: () => null, rows: () => null, startDrag: () => {}, drop: () => {}, endDrag: () => {}, onChange: () => () => {} }\n\n/**\n * `BlockHandle` in an editor: drag the handle to move the block, and the menu\n * gains Turn into, Duplicate and Delete before the caller's rows.\n */\nexport function EditorBlockHandle({ editor, turnInto = turnIntoRows, actions, children, className }: EditorBlockHandleProps) {\n const editing = useMemo<BlockHandleEditing>(() => {\n // Before the editor exists there is no block to find \u2014 not the editor's whole element read as one.\n if (!editor) return NOTHING_YET\n // Where the block being dragged starts.\n let dragged: number | undefined\n return {\n find: (y) => blockAtY(editorBlocks(editor.view), y),\n rows: (block) => {\n const pos = block.pos\n // Not editable: the caller's rows only, and no drag.\n if (!editor.isEditable) return null\n const node = pos === undefined ? null : editor.state.doc.nodeAt(pos)\n if (pos === undefined || !node) return null\n const turnRows = typeof turnInto === 'function' ? turnInto(node, editor) : node.isTextblock ? turnInto : []\n return (\n <>\n {turnRows.length > 0 && (\n <MenuSub label=\"Turn into\">\n {turnRows.map((row) => (\n <MenuItem\n key={row.label}\n label={row.label}\n selected={row.active?.(node) ?? false}\n onClick={() => {\n // Inside a block of text, so a row's command at the caret turns this block and no other.\n if (node.isTextblock) editor.chain().focus().setTextSelection(pos + 1).run()\n row.run(editor, pos)\n }}\n />\n ))}\n </MenuSub>\n )}\n <MenuItem label=\"Duplicate\" leading={<IconCopy size={16} stroke={1.5} className=\"text-text-secondary\" />} onClick={() => duplicateBlock(editor, pos)} />\n <MenuItem label=\"Delete\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={() => deleteBlock(editor, pos)} />\n </>\n )\n },\n startDrag: (block, event) => {\n dragged = block.pos\n if (block.pos !== undefined) startBlockDrag(editor, block.pos, event, block.element)\n },\n drop: (target, after) => {\n const node = target.pos === undefined ? null : editor.state.doc.nodeAt(target.pos)\n if (dragged === undefined || target.pos === undefined || !node) return\n moveBlock(editor, dragged, after ? target.pos + node.nodeSize : target.pos)\n },\n // ProseMirror clears `dragging` on its own dragend, which a drag started outside its element never reaches.\n endDrag: () => setTimeout(() => (editor.view.dragging = null), 50),\n onChange: (changed) => {\n editor.on('update', changed)\n return () => {\n editor.off('update', changed)\n }\n },\n }\n }, [editor, turnInto])\n\n return (\n <BlockHandle editing={editing} actions={actions} className={className}>\n {children}\n </BlockHandle>\n )\n}\n\nconst LISTS = ['bulletList', 'orderedList']\nconst isList = (node: ProseMirrorNode) => LISTS.includes(node.type.name)\n\n/** Every item of a list, the ones nested under an item too \u2014 the editor nests what \u00A713.3 keeps flat (MAN-13). */\nfunction listItems(list: ProseMirrorNode, at: number): { node: ProseMirrorNode; pos: number }[] {\n const out: { node: ProseMirrorNode; pos: number }[] = []\n list.descendants((node, pos) => {\n if (node.type.name === 'listItem') out.push({ node, pos: at + 1 + pos })\n })\n return out\n}\n\nconst isChecklistItem = ({ node }: { node: ProseMirrorNode }) => typeof node.attrs.checked === 'boolean'\n/** Whether every item of the list is a checklist item. */\nconst isChecklist = (list: ProseMirrorNode) => listItems(list, 0).every(isChecklistItem)\n/** A list of that type with no checklist item in it \u2014 a list partly ticked is neither, so no row reads as \"nothing changes\". */\nconst isPlainList = (list: ProseMirrorNode, type: string) => list.type.name === type && !listItems(list, 0).some(isChecklistItem)\n\nconst hasExtension = (editor: Editor, name: string) => editor.extensionManager.extensions.some((e) => e.name === name)\n\n/** The caret back in the block, the editor still focused \u2014 as Duplicate and Delete leave it, so a save on leaving saves this too. */\nfunction caretInto(editor: Editor, pos: number) {\n const { state } = editor\n editor.view.dispatch(state.tr.setSelection(Selection.near(state.doc.resolve(Math.min(pos + 1, state.doc.content.size)))))\n editor.commands.focus()\n}\n\nexport type ListKind = 'bulletList' | 'orderedList' | 'checklist' | 'text'\n\n/**\n * Turns the whole list at `pos`, every item, the nested ones too.\n *\n * - **Bulleted, Numbered:** the list's own type changes and its attributes\n * stay, so it keeps its id; every item's tick goes. Not Tiptap's\n * `toggleList`, which makes the list anew \u2014 a fresh id, detaching every\n * comment anchored to it \u2014 and then joins it into a list of that type next\n * to it.\n * - **Checklist:** every item a checklist item, the list's type as it was; an\n * item already one keeps its tick.\n *\n * The kind it already is changes nothing \u2014 no edit, no undo step.\n * - **Text:** each item becomes a paragraph that takes the item's id, as\n * lifting an item out does (MAN-12). The list's own id goes with the list.\n *\n * `false` when there is no list at `pos`.\n */\nexport function turnListInto(editor: Editor, pos: number, kind: ListKind): boolean {\n const { state } = editor\n const list = state.doc.nodeAt(pos)\n if (!list || !isList(list)) return false\n const tr = state.tr\n if (kind === 'text') {\n const blocks: ProseMirrorNode[] = []\n for (const { node: item } of listItems(list, pos)) {\n item.forEach((child, _offset, index) => {\n // Its nested list's items are in `listItems` already.\n if (isList(child)) return\n // The item's first block takes its id; any other gets one of its own from `BlockId`.\n blocks.push(child.type.create({ ...child.attrs, blockId: index === 0 ? item.attrs.blockId : null }, child.content, child.marks))\n })\n }\n tr.replaceWith(pos, pos + list.nodeSize, blocks)\n } else {\n // A checklist stays the list type it is: \u00A713.3 ticks items of either.\n const type = kind === 'checklist' ? list.type : state.schema.nodes[kind]\n // The list and the lists nested in it, one type throughout: \u00A713.3's indented items are their list's type.\n if (list.type !== type) tr.setNodeMarkup(pos, type, list.attrs)\n list.descendants((node, at) => {\n if (isList(node) && node.type !== type) tr.setNodeMarkup(pos + 1 + at, type, node.attrs)\n })\n for (const { node, pos: at } of listItems(list, pos)) {\n const checked = kind === 'checklist' ? (typeof node.attrs.checked === 'boolean' ? node.attrs.checked : false) : null\n if (node.attrs.checked !== checked) tr.setNodeAttribute(at, 'checked', checked)\n }\n }\n // The row it already is changes nothing: no edit to save, no step to undo.\n if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView())\n caretInto(editor, pos)\n return true\n}\n\nexport type QuoteKind = 'quote' | 'note' | 'warning' | 'text'\n\n/**\n * Turns the quote at `pos`: a plain quote, a Note or Warning callout (the\n * tone changes, the id stays), or its text, whose first paragraph takes the\n * quote's id, as lifting it out does (MAN-12). `false` when there is no quote\n * at `pos`.\n */\nexport function turnQuoteInto(editor: Editor, pos: number, kind: QuoteKind): boolean {\n const { state } = editor\n const quote = state.doc.nodeAt(pos)\n if (!quote || quote.type.name !== 'blockquote') return false\n const tr = state.tr\n if (kind === 'text') {\n const blocks: ProseMirrorNode[] = []\n quote.forEach((child) => blocks.push(blocks.length === 0 ? child.type.create({ ...child.attrs, blockId: quote.attrs.blockId }, child.content, child.marks) : child))\n tr.replaceWith(pos, pos + quote.nodeSize, blocks)\n } else {\n const tone = kind === 'quote' ? null : kind\n if ((quote.attrs.tone ?? null) !== tone) tr.setNodeAttribute(pos, 'tone', tone)\n }\n if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView())\n caretInto(editor, pos)\n return true\n}\n\nfunction isFormat(node: ProseMirrorNode, id: FormatId): boolean {\n if (id === 'paragraph') return node.type.name === 'paragraph'\n if (id === 'heading') return node.type.name === 'heading' && node.attrs.level === 1\n if (id === 'subheading') return node.type.name === 'heading' && node.attrs.level === 2\n if (id === 'code') return node.type.name === 'codeBlock'\n return false\n}\n\n/**\n * The block menu's Turn into for one block, the same in every app (Miky,\n * LEAF-11's kickoff, 15 October):\n *\n * - **A block of text** \u2014 a paragraph, a heading, code: the `/` menu's Format\n * rows, code as a block, and Checklist, Note and Warning where the editor\n * has `Checklist` and `Callout`.\n * - **A list:** Bulleted list, Numbered list, Checklist (with `Checklist`), Text.\n * - **A quote:** Quote, Note, Warning (with `Callout`), Text.\n *\n * Anything else \u2014 a table, an attachment \u2014 none. Each keeps the block's text\n * and its id, and so the comments anchored to it.\n */\nexport function turnIntoRows(node: ProseMirrorNode, editor: Editor): readonly BlockTurnInto[] {\n const checklist = hasExtension(editor, 'checklist')\n const callout = hasExtension(editor, 'callout')\n if (node.isTextblock) {\n const document = DOCUMENT_FORMATS.filter((f) => (f.id === 'checklist' ? checklist : callout))\n return [...FORMATS, ...document].map((format) => ({\n label: format.label,\n run: (e) => void applyFormat(e, format.id, 'block'),\n active: (n) => isFormat(n, format.id),\n }))\n }\n if (isList(node)) {\n const rows: BlockTurnInto[] = [\n { label: 'Bulleted list', run: (e, pos) => void turnListInto(e, pos, 'bulletList'), active: (n) => isPlainList(n, 'bulletList') },\n { label: 'Numbered list', run: (e, pos) => void turnListInto(e, pos, 'orderedList'), active: (n) => isPlainList(n, 'orderedList') },\n ]\n if (checklist) rows.push({ label: 'Checklist', run: (e, pos) => void turnListInto(e, pos, 'checklist'), active: isChecklist })\n rows.push({ label: 'Text', run: (e, pos) => void turnListInto(e, pos, 'text') })\n return rows\n }\n if (node.type.name === 'blockquote') {\n const rows: BlockTurnInto[] = [{ label: 'Quote', run: (e, pos) => void turnQuoteInto(e, pos, 'quote'), active: (n) => !n.attrs.tone }]\n if (callout) {\n rows.push({ label: 'Note', run: (e, pos) => void turnQuoteInto(e, pos, 'note'), active: (n) => n.attrs.tone === 'note' })\n rows.push({ label: 'Warning', run: (e, pos) => void turnQuoteInto(e, pos, 'warning'), active: (n) => n.attrs.tone === 'warning' })\n }\n rows.push({ label: 'Text', run: (e, pos) => void turnQuoteInto(e, pos, 'text') })\n return rows\n }\n return []\n}\n", "import { useCallback, useEffect, useRef, useState, type MouseEvent, type ReactNode } from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { TextSelection, type Command } from '@tiptap/pm/state'\nimport { addColumnAfter, addColumnBefore, addRowAfter, addRowBefore, deleteColumn, deleteRow, deleteTable, toggleHeader } from '@tiptap/pm/tables'\nimport { IconCheck, IconColumnInsertLeft, IconColumnInsertRight, IconGripHorizontal, IconGripVertical, IconPlus, IconRowInsertBottom, IconRowInsertTop, IconTableRow, IconTrash } from '@tabler/icons-react'\nimport { cn } from './cn'\nimport { IconButton } from './IconButton'\nimport { FLOATING_SURFACE_CLASSES } from './looks'\nimport { Menu, MenuItem, MenuSeparator } from './Menu'\n\nexport interface EditorTableControlsProps {\n /** The editor, with TableKit (`@tiptap/extension-table`) in its extensions. Not editable, or not there yet: no controls. */\n editor: Editor | null\n /** The `EditorContent`. */\n children: ReactNode\n className?: string\n}\n\n/** The cell the pointer is on, and the table and row it is in. */\ninterface Hovered {\n table: HTMLTableElement\n row: HTMLTableRowElement\n cell: HTMLTableCellElement\n}\n\n/** Where the controls go, measured from the frame: they depend on the document, not on a size of ours. */\ninterface Placed {\n tableBox: { top: number; left: number; width: number; height: number }\n rowBox: { top: number; height: number }\n columnBox: { left: number; width: number }\n}\n\n/*\n Every row runs the table command with the caret in a cell, as the command\n expects \u2014 the hovered cell's, or for a \u2795 bar the last row's or the last\n column's \u2014 and leaves the editor focused there, as the block menu does: the\n person is still in the field, so an editor that saves when they leave it\n saves this too.\n*/\n\n/** Puts the caret in `cell` and runs `command` there. */\nfunction inCell(editor: Editor, cell: HTMLTableCellElement, command: Command): boolean {\n const { view } = editor\n if (!view.dom.contains(cell)) return false\n const at = view.posAtDOM(cell, 0)\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(at))))\n const done = command(view.state, view.dispatch, view)\n editor.commands.focus()\n return done\n}\n\n/** A row of header cells only: the table's header row. */\nfunction isHeaderRow(row: HTMLTableRowElement): boolean {\n return row.cells.length > 0 && Array.from(row.cells).every((c) => c.tagName === 'TH')\n}\n\n/**\n * The cell's row, or the whole table when it is its only one: a table holds at\n * least one row (prosemirror-tables refuses to delete it). Deleting the header\n * row makes the next row the header, so the table still opens with one.\n */\nexport function deleteTableRow(editor: Editor, cell: HTMLTableCellElement): boolean {\n const row = cell.closest('tr')\n const table = cell.closest('table')\n if (!row || !table || table.rows.length <= 1) return inCell(editor, cell, deleteTable)\n const header = isHeaderRow(row)\n return inCell(editor, cell, header ? (state, dispatch, view) => deleteRow(state, dispatch) && (!view || toggleHeader('row')(view.state, view.dispatch)) : deleteRow)\n}\n\n/**\n * The table's first row becomes its header row, or an ordinary row again:\n * whichever cell of the table `cell` is. A table with no header row has no\n * text spelling, so the agent keeps it as written (SPEC \u00A713.3, \"No spelling\").\n */\nexport function toggleTableHeaderRow(editor: Editor, cell: HTMLTableCellElement): boolean {\n return inCell(editor, cell, toggleHeader('row'))\n}\n\n/** The same for a column: the last one deletes the table. */\nexport function deleteTableColumn(editor: Editor, cell: HTMLTableCellElement): boolean {\n const row = cell.closest('tr')\n return inCell(editor, cell, row && row.cells.length > 1 ? deleteColumn : deleteTable)\n}\n\n/** A row after the last one: the \u2795 under the table. */\nexport function appendTableRow(editor: Editor, table: HTMLTableElement): boolean {\n const last = table.rows[table.rows.length - 1]?.cells[0]\n return !!last && inCell(editor, last, addRowAfter)\n}\n\n/** A column after the last one: the \u2795 right of the table. */\nexport function appendTableColumn(editor: Editor, table: HTMLTableElement): boolean {\n const first = table.rows[0]\n const last = first?.cells[first.cells.length - 1]\n return !!last && inCell(editor, last, addColumnAfter)\n}\n\nfunction place(frame: HTMLElement, { table, row, cell }: Hovered): Placed {\n const at = frame.getBoundingClientRect()\n const t = table.getBoundingClientRect()\n const r = row.getBoundingClientRect()\n const c = cell.getBoundingClientRect()\n return {\n tableBox: { top: t.top - at.top, left: t.left - at.left, width: t.width, height: t.height },\n rowBox: { top: r.top - at.top, height: r.height },\n columnBox: { left: c.left - at.left, width: c.width },\n }\n}\n\nconst ICON = { size: 16, stroke: 1.5, className: 'text-text-secondary' } as const\n\n/**\n * A \u2795 press keeps the focus where it is, as the selection toolbar's buttons do:\n * the person never left the field, so an editor that saves when they leave it\n * does not save half-way, and History gets one line for the edit, not one per\n * press. (A handle's menu takes the focus, as every menu does.)\n */\nconst keepFocus = (e: MouseEvent) => e.preventDefault()\n\n/** What a handle and a \u2795 bar sit in: the elevated surface's border and fill, opaque over the table's lines, with no shadow at this size. */\nconst HANDLE_BOX = cn(FLOATING_SURFACE_CLASSES, 'shadow-none')\n\n/**\n * A table's own controls in an editor, as in Notion: point at a cell and a\n * handle sits on its row's left edge and on its column's top edge; press one\n * for Insert above and below (left and right), Delete, and Delete table. The\n * first row's menu also turns the header row on and off (Header row, ticked\n * while it is on); with it off, the first row is an ordinary row. On\n * the last row a \u2795 bar under the table adds a row, and on the last column one\n * right of it adds a column. Tab in\n * the last cell adds a row too \u2014 that is TableKit's own.\n *\n * Deleting a table's only row or only column deletes the table, which cannot\n * be left with none.\n *\n * Built on the editor library's own table commands; the controls are ours.\n * Wrap the `EditorContent` in it, inside an `EditorBlockHandle` if there is\n * one: the block handle stays the table's, in the gutter.\n */\nexport function EditorTableControls({ editor, children, className }: EditorTableControlsProps) {\n const frame = useRef<HTMLDivElement>(null)\n // The cell pointed at and where its controls go, as one: the boxes mean nothing without their elements.\n const [hovered, setHovered] = useState<(Hovered & Placed) | null>(null)\n // A menu that is up keeps its row and column, wherever the pointer goes.\n const [menu, setMenu] = useState<'row' | 'column' | null>(null)\n const editable = !!editor && editor.isEditable\n\n const follow = useCallback(\n (target: EventTarget | null) => {\n if (!editor || !frame.current || !(target instanceof Element)) return\n // On a control of ours: keep what it was drawn for.\n if (target.closest('[data-table-control]')) return\n const cell = target.closest<HTMLTableCellElement>('td, th')\n const row = cell?.closest('tr')\n const table = row?.closest('table')\n if (!cell || !row || !table || !editor.view.dom.contains(table)) {\n setHovered(null)\n return\n }\n // Measured on every move, the same cell too: a panel resized or a cell's text wrapping moves the edges under a still pointer.\n const next = { table, row, cell, ...place(frame.current, { table, row, cell }) }\n setHovered((was) => (was && was.cell === cell && JSON.stringify([was.tableBox, was.rowBox, was.columnBox]) === JSON.stringify([next.tableBox, next.rowBox, next.columnBox]) ? was : next))\n },\n [editor],\n )\n\n /*\n Any change to the document moves everything under the controls, so they go\n until the pointer moves again: a row added or deleted here, and someone\n else's edit loaded into the field \u2014 which an app does without an `update`\n (`emitUpdate: false`), and which redraws the cells the controls point at.\n */\n useEffect(() => {\n if (!editor) return\n const changed = ({ transaction }: { transaction: { docChanged: boolean } }) => {\n if (transaction.docChanged && !menu) setHovered(null)\n }\n editor.on('transaction', changed)\n return () => {\n editor.off('transaction', changed)\n }\n }, [editor, menu])\n\n const shown = editable ? hovered : null\n const run = (act: () => boolean) => () => {\n if (editor) act()\n setMenu(null)\n setHovered(null)\n }\n\n return (\n <div\n ref={frame}\n className={cn('relative', className)}\n onMouseMove={(e) => {\n if (!menu) follow(e.target)\n }}\n onMouseLeave={() => {\n if (!menu) setHovered(null)\n }}\n >\n {children}\n {shown && editor && (\n <>\n {/* The row's handle, centred on the table's left edge: the box is ours, so the table's line does not show through it. */}\n <div data-table-control className={cn(HANDLE_BOX, 'absolute -translate-x-1/2 -translate-y-1/2')} style={{ left: shown.tableBox.left, top: shown.rowBox.top + shown.rowBox.height / 2 }}>\n <Menu\n open={menu === 'row'}\n onOpenChange={(open) => setMenu(open ? 'row' : null)}\n trigger={\n <IconButton aria-label=\"Row menu\" tooltip=\"Row\" className=\"h-6 w-4 p-0\">\n <IconGripVertical size={16} stroke={1.5} />\n </IconButton>\n }\n >\n {/* The header row is switched where it lives: on the first row's menu, ticked while that row is the header. */}\n {shown.row.rowIndex === 0 && (\n <>\n <MenuItem\n label=\"Header row\"\n leading={<IconTableRow {...ICON} />}\n trailing={isHeaderRow(shown.row) ? <IconCheck {...ICON} aria-hidden /> : undefined}\n onClick={run(() => toggleTableHeaderRow(editor, shown.cell))}\n />\n <MenuSeparator />\n </>\n )}\n {/* Nothing goes above a header row: it is the table's first row, and a header anywhere else is no header (RichText, the agent's text). */}\n {!isHeaderRow(shown.row) && <MenuItem label=\"Insert above\" leading={<IconRowInsertTop {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addRowBefore))} />}\n <MenuItem label=\"Insert below\" leading={<IconRowInsertBottom {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addRowAfter))} />\n <MenuSeparator />\n <MenuItem label=\"Delete\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => deleteTableRow(editor, shown.cell))} />\n <MenuItem label=\"Delete table\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => inCell(editor, shown.cell, deleteTable))} />\n </Menu>\n </div>\n {/* The column's handle, centred on the table's top edge. */}\n <div data-table-control className={cn(HANDLE_BOX, 'absolute -translate-x-1/2 -translate-y-1/2')} style={{ left: shown.columnBox.left + shown.columnBox.width / 2, top: shown.tableBox.top }}>\n <Menu\n open={menu === 'column'}\n onOpenChange={(open) => setMenu(open ? 'column' : null)}\n trigger={\n <IconButton aria-label=\"Column menu\" tooltip=\"Column\" className=\"h-4 w-6 p-0\">\n <IconGripHorizontal size={16} stroke={1.5} />\n </IconButton>\n }\n >\n <MenuItem label=\"Insert left\" leading={<IconColumnInsertLeft {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addColumnBefore))} />\n <MenuItem label=\"Insert right\" leading={<IconColumnInsertRight {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addColumnAfter))} />\n <MenuSeparator />\n <MenuItem label=\"Delete\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => deleteTableColumn(editor, shown.cell))} />\n <MenuItem label=\"Delete table\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => inCell(editor, shown.cell, deleteTable))} />\n </Menu>\n </div>\n {/*\n The \u2795 bars, flush with the table so the pointer reaches them from a\n cell without leaving it \u2014 the row's from the last row, the column's\n from the last column. Anywhere else the one under the table would\n lie over the top of the next block for nothing.\n */}\n {shown.row === shown.table.rows[shown.table.rows.length - 1] && (\n <div data-table-control className={cn(HANDLE_BOX, 'absolute flex h-4')} style={{ left: shown.tableBox.left, top: shown.tableBox.top + shown.tableBox.height, width: shown.tableBox.width }}>\n <IconButton aria-label=\"Add row\" tooltip=\"Add row\" className=\"h-full w-full p-0\" onMouseDown={keepFocus} onClick={run(() => appendTableRow(editor, shown.table))}>\n <IconPlus size={12} stroke={1.5} />\n </IconButton>\n </div>\n )}\n {shown.cell === shown.row.cells[shown.row.cells.length - 1] && (\n <div data-table-control className={cn(HANDLE_BOX, 'absolute flex w-4')} style={{ left: shown.tableBox.left + shown.tableBox.width, top: shown.tableBox.top, height: shown.tableBox.height }}>\n <IconButton aria-label=\"Add column\" tooltip=\"Add column\" className=\"h-full w-full p-0\" onMouseDown={keepFocus} onClick={run(() => appendTableColumn(editor, shown.table))}>\n <IconPlus size={12} stroke={1.5} />\n </IconButton>\n </div>\n )}\n </>\n )}\n </div>\n )\n}\n", "import { useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'\n// @estiva-escape(estiva/no-hand-rolled-behaviour): \"Your version\" is drawn into the text, in the slot ProseMirror's decoration places at its block's end; nothing floats, so no Base UI part has it.\nimport { createPortal } from 'react-dom'\nimport type { AnyExtension } from '@tiptap/core'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { EditorContent, useEditor, useEditorState, type Editor, type JSONContent } from '@tiptap/react'\nimport { TableKit } from '@tiptap/extension-table'\nimport { IconCheck, IconCopy, IconMessagePlus } from '@tabler/icons-react'\nimport { ASKED_BLOCK_CLASSES, AskedBlocks, blockAt, setAskedBlocks, type AskedSlot } from './AskedBlocks'\nimport type { HandleBlock } from './BlockHandle'\nimport { AttachmentNode, BlockId, Callout, Checklist, ReferenceNode, UnknownBlock, isChecklistTick, type AttachmentViewProps, type ReferenceViewProps } from './BlockNodes'\nimport { Button } from './Button'\nimport { Card } from './Card'\nimport { cn } from './cn'\nimport { CodeBlockColours } from './CodeBlockColours'\nimport { CommentHighlights, anchorOfSelection, type SelectionAnchor } from './CommentHighlights'\nimport { PersonReference, ReferenceTrigger, SlashCommands, formatSection, typeTrigger, type MentionPerson, type ReferenceSection, type SlashCommand, type SlashSection } from './ComposerTriggers'\nimport { EditorBlockHandle, blockDropCursor } from './EditorBlockHandle'\nimport { EditorTableControls } from './EditorTableControls'\nimport { FieldLine } from './Field'\nimport { FilePicker } from './FilePicker'\nimport { LinkChips, type LinkChipsOptions } from './LinkChips'\nimport { BareLinks, DocumentKit, LINK_MARK_ATTRIBUTES, PasteOverWords } from './links'\nimport { PastedImages } from './PastedImages'\nimport { PastedMarkdown } from './PastedMarkdown'\nimport { LinkPlaces } from './LinkPlaces'\nimport { EDITOR_SELECTION_CLASSES } from './looks'\nimport { ReferenceMenu, ReferenceMenuView, isReferenceMenuOpen } from './ReferenceMenu'\nimport { richTextClassName } from './RichText'\nimport { SectionLabel } from './SectionLabel'\nimport { KeptSelection, SelectionToolbar } from './SelectionToolbar'\nimport { isSuggestionOpen } from './suggestionPopup'\n\n/**\n * How the app's saved text and the editor's document turn into each other. The\n * package speaks only the editor's document; the translation is\n * `@estiva-app/protocol`'s, which the package does not depend on (the record\n * below):\n *\n * { read: (value, format) => toEditorDocument(documentForEditing(value, format), { links: true }),\n * write: (doc) => publishableFromEditor(doc) }\n */\nexport interface DocumentCodec {\n /** The saved text, in its format, as the editor's document. */\n read: (value: string, format: string) => JSONContent\n /** The editor's document as the text to save, and the format it is in. */\n write: (doc: JSONContent) => { value: string; contentFormat?: string }\n}\n\n/**\n * Where text typed when the sign-in ends is kept through the passkey trip, and\n * put back, unsaved, after it. The app's own store, by key.\n */\nexport interface HeldTyping {\n /** What is held for `key` from the last ending, or `undefined`. */\n text: (key: string) => string | undefined\n /** Forget what is held for `key`: it was saved. */\n release: (key: string) => void\n /** While the editor is open, let an ending read its unsaved text. Returns what stops that, as the editor closes. */\n register: (key: string, read: () => string | undefined) => () => void\n /** Whether the sign-in has ended: nothing is saved then, and the text is held instead. */\n ended: () => boolean\n}\n\n/** What `[` lists, and how. Without it `[` is a bracket. */\nexport interface DocumentReferences {\n /** The sections for what was typed after `[`, already narrowed and in the app's order. */\n sections: (query: string) => readonly ReferenceSection[]\n /** Called with a listener while the list is open; call it when `sections` would answer differently (a search landed). */\n subscribe?: (listener: () => void) => () => void\n /** Names the list. */\n ariaLabel: string\n /** The heading of rows that bring no section of their own. */\n sectionLabel: string\n /** A row's 16px icon, unless the row brings its own. Default none. */\n icon?: ReactNode\n}\n\n/** Whom `@` offers. Without it `@` is an at sign. */\nexport interface DocumentMentions {\n /** Everyone `@` can offer, asked as the query changes. */\n people: () => readonly MentionPerson[]\n /** The `nostr:npub\u2026` a person is written as; `null` for someone without one, who is not offered. */\n uriOf: (person: MentionPerson) => string | null\n}\n\nexport interface DocumentEditorProps {\n /** The saved text. A new value while the editor is open is somebody else's save, or your own coming back. */\n value: string\n /** The format `value` is in, handed to `codec.read`. */\n format: string\n codec: DocumentCodec\n /**\n * Save. Called when you leave, never while typing, with the text, its format,\n * and the saved text this edit started from \u2014 so the app can tell whom the\n * save names anew. Answer whether it was saved, or, when someone changed a\n * block you changed too, what asks ({@link DocumentAsks}).\n */\n onCommit: (value: string, contentFormat: string | undefined, editedFrom: string) => Promise<boolean | DocumentAsks> | boolean | DocumentAsks\n /**\n * Your saves are merged with someone else's (the app merges them by blocks):\n * a newer save arriving while you are in the editor waits with no line, and\n * leaving saves yours merged onto it. Without it, the line with Load it.\n */\n merges?: boolean\n /** The editor's accessible name. */\n label: string\n /** Muted words over an empty editor. */\n placeholder?: ReactNode\n /** For reading: nothing is typed or saved; chips open, and comments on a selection work when on. */\n readOnly?: boolean\n /** Who saved the text last, when it was not you: named in \"\u2026 saved a newer version\". */\n changedBy?: { name: string } | null\n /**\n * A save refused after the editor closed, with nothing left on screen to say it. Closed while blocks ask, it is\n * handed the text with your version of each, in the saved format, for the app to keep.\n */\n onLeftUnsaved?: (unsaved?: string) => void\n /** Where text typed when the sign-in ends is held, under `holdKey`. */\n hold?: HeldTyping\n holdKey?: string\n /** `[` and `/` \u2192 File. */\n references?: DocumentReferences\n /** `@` and `/` \u2192 Mention. */\n mentions?: DocumentMentions\n /** A pasted app URL drawn as the chip of what it names (`LinkChips`). */\n linkChips?: LinkChipsOptions\n /** `/` \u2192 Upload, and a pasted picture: upload one file and answer the attachment's attributes (its `imeta` fields). */\n upload?: (file: File) => Promise<Record<string, unknown>>\n /** Plain text pasted as the blocks it spells: the app's reader of markdown, as the editor's document. */\n readMarkdown?: (text: string) => JSONContent | undefined\n /** `/` \u2192 Table. Default on. */\n table?: boolean\n /** Comment on what is selected: the selection strip's Comment, and the comment highlights. Without it, neither. */\n onCommentOnSelection?: (anchor: SelectionAnchor) => void\n /** The app's rows in a block's handle menu, after the editing ones: Copy link, Comment. */\n blockRows?: (block: HandleBlock) => ReactNode\n /**\n * Draws a link: the app's own, which resolves what it names \u2014 its chip, its\n * row or its card in the row's place, as `place` says (\u00A713.3).\n */\n referenceView?: ComponentType<ReferenceViewProps>\n /** Draws a placed file: the app's own card. */\n attachmentView?: ComponentType<AttachmentViewProps>\n /** Around everything the editor draws: the app's providers, which may read the editor. */\n wrap?: (children: ReactNode, editor: Editor | null) => ReactNode\n /** The editor, once it is there, and `null` as it goes. */\n onEditor?: (editor: Editor | null) => void\n /** More of the app's own extensions. */\n extensions?: readonly AnyExtension[]\n}\n\n/**\n * A save refused because someone changed a block you changed too, merged as far\n * as it goes. Nothing of yours is saved until every block that asks is chosen.\n */\nexport interface DocumentAsks {\n /** The text to hold now, unsaved: theirs, with every change of yours that did not clash in it, and their words in each block that asks. */\n value: string\n /** Their saved text, which `value` follows: the next save's `editedFrom`. */\n theirs: string\n /** Your text as you saved it: \"Your version\" of each block is read from it. */\n mine: string\n /** The ids of the blocks that ask: changed by both, or changed by one and deleted by the other. */\n blocks: readonly string[]\n /** The text changed since this page was opened, and the app could not merge it: said above the text. */\n sinceOpened?: boolean\n}\n\nconst isAsks = (answer: boolean | DocumentAsks): answer is DocumentAsks => typeof answer === 'object' && answer !== null\n\n/** The node of the block with this id in a document of the editor's, or `null` when it holds none. */\nfunction blockOf(doc: JSONContent, id: string): JSONContent | null {\n if (doc.attrs?.blockId === id) return doc\n for (const child of doc.content ?? []) {\n const found = blockOf(child, id)\n if (found) return found\n }\n return null\n}\n\n/** The words of a block of the editor's document, as \"Your version\" shows them: a line per block inside it (a list's items). */\nconst wordsOf = (node: JSONContent): string => {\n const children = node.content ?? []\n const inline = children.every((child) => child.text !== undefined || !child.content)\n return (node.text ?? '') + children.map(wordsOf).join(inline ? '' : '\\n')\n}\n\n/** A document with each of these blocks as `from` has it, or taken out where `from` has none: your text with your version of each block that asks. */\nfunction withBlocksFrom(doc: JSONContent, ids: readonly string[], from: JSONContent): JSONContent {\n if (!doc.content) return doc\n return {\n ...doc,\n content: doc.content.flatMap((child) => {\n const id = child.attrs?.blockId as string | undefined\n if (id && ids.includes(id)) return blockOf(from, id) ?? []\n return [withBlocksFrom(child, ids, from)]\n }),\n }\n}\n\n/** The top-level blocks `to` has changed, added or taken out since `from`. */\nfunction blocksChanged(from: JSONContent, to: JSONContent): string[] {\n if (from === to) return []\n const before = new Map((from.content ?? []).map((child) => [child.attrs?.blockId as string | undefined, JSON.stringify(child)]))\n const after = new Set<string>()\n const changed: string[] = []\n for (const child of to.content ?? []) {\n const id = child.attrs?.blockId as string | undefined\n if (!id) continue\n after.add(id)\n if (before.get(id) !== JSON.stringify(child)) changed.push(id)\n }\n for (const id of before.keys()) if (id && !after.has(id)) changed.push(id)\n return changed\n}\n\n/**\n * The merge with these blocks as you typed them since the save went: changed in place, taken out where you took them\n * out, and a new one after the nearest block before it in your text that the merge still holds.\n */\nfunction withTypedSince(merged: JSONContent, typedNow: JSONContent, ids: readonly string[]): JSONContent {\n if (ids.length === 0) return merged\n const yours = typedNow.content ?? []\n const content = (merged.content ?? []).flatMap((child) => {\n const id = child.attrs?.blockId as string | undefined\n return id && ids.includes(id) ? (yours.find((block) => block.attrs?.blockId === id) ?? []) : [child]\n })\n yours.forEach((block, i) => {\n const id = block.attrs?.blockId as string | undefined\n if (!id || !ids.includes(id) || content.some((child) => child.attrs?.blockId === id)) return\n let at = 0\n for (let j = i - 1; j >= 0 && at === 0; j--) {\n const before = yours[j].attrs?.blockId as string | undefined\n at = content.findIndex((child) => child.attrs?.blockId === before) + 1\n }\n content.splice(at, 0, block)\n })\n return { ...merged, content }\n}\n\n/** Whose version of a block that asks is chosen. */\ntype Side = 'mine' | 'theirs'\n\n/** What the editor holds while blocks ask. */\ninterface Asking {\n blocks: readonly string[]\n mine: JSONContent\n theirs: JSONContent\n sinceOpened: boolean\n}\n\n/**\n * Your version, beside the block you both changed. Use mine puts yours in its place; Copy puts yours on the clipboard\n * and keeps it here, so you can paste it and still choose; Dismiss keeps theirs. None of them takes focus from the text.\n */\nfunction YourVersion({ words, onUseMine, onDismiss }: { words: string; onUseMine: () => void; onDismiss: () => void }) {\n const [copied, setCopied] = useState(false)\n const keep = (event: { preventDefault: () => void }) => event.preventDefault()\n return (\n <Card fill=\"inset\" className=\"flex flex-col gap-2 p-3\" data-your-version=\"\">\n <SectionLabel>Your version</SectionLabel>\n <p className=\"whitespace-pre-wrap text-body-2 text-text-primary\">{words}</p>\n <div className=\"flex flex-wrap items-center gap-1\">\n <Button variant=\"outlined\" size=\"small\" onMouseDown={keep} onClick={onUseMine}>\n Use mine\n </Button>\n <Button\n variant=\"muted\"\n size=\"small\"\n leadingIcon={copied ? <IconCheck size={14} stroke={1.5} /> : <IconCopy size={14} stroke={1.5} />}\n onMouseDown={keep}\n onClick={() => {\n void navigator.clipboard?.writeText(words).catch(() => undefined)\n setCopied(true)\n }}\n >\n {copied ? 'Copied' : 'Copy'}\n </Button>\n <Button variant=\"muted\" size=\"small\" onMouseDown={keep} onClick={onDismiss}>\n Dismiss\n </Button>\n </div>\n </Card>\n )\n}\n\n/** The editor's own document held for this place when the sign-in ended, block ids and all; `null` when none. */\nfunction heldDocument(hold: HeldTyping | undefined, key: string | undefined): JSONContent | null {\n const text = hold && key ? hold.text(key) : undefined\n if (!text) return null\n try {\n const doc = JSON.parse(text) as JSONContent\n return doc?.type === 'doc' ? doc : null\n } catch {\n return null\n }\n}\n\n/**\n * One document's text as one surface that is always an editor \u2014 Leaf's page,\n * Ship's description and Peek's panel, which each had their own until this.\n * Every app's document can do the same things, wherever it is written.\n *\n * - **Saves when you leave:** on blur, on unmount and on a checklist tick.\n * Never while typing. Escape leaves and keeps the text. A refused save keeps\n * the text and says so; one refused after the editor closed goes to\n * `onLeftUnsaved`.\n * - **Someone else's save arrives** while you are not in it: it is loaded.\n * While you are in it, it waits, and a line says who saved a newer version,\n * with \"Load it\"; leaving with a change saves yours over it \u2014 the later save\n * wins (Miky, LEAF-3's kickoff and 13 October). Your own save coming back is\n * never mistaken for someone else's. With `merges`, no line: leaving merges\n * yours onto theirs.\n * - **A block you both changed asks** (`onCommit` answers {@link DocumentAsks}):\n * their words are in the text, marked at the block's edge, and yours sit\n * beside it with Use mine, Copy and Dismiss. Nothing is saved until every\n * block is chosen; the last choice saves. Leaving before that saves nothing\n * and goes to `onLeftUnsaved`.\n * - **The sign-in ending** holds what was typed (`hold`), and the editor opens\n * with it, unsaved, after the passkey tap.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-edits-a-document-with-one-shared-editor.md\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/the-block-editor-kit-lives-in-protocol-and-ui.md\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/merging-two-changes-to-one-text-never-loses-words.md\n */\nexport function DocumentEditor({\n value,\n format,\n codec,\n onCommit,\n merges = false,\n label,\n placeholder,\n readOnly = false,\n changedBy = null,\n onLeftUnsaved,\n hold,\n holdKey,\n references,\n mentions,\n linkChips,\n upload,\n readMarkdown,\n table = true,\n onCommentOnSelection,\n blockRows,\n referenceView,\n attachmentView,\n wrap,\n onEditor,\n extensions = [],\n}: DocumentEditorProps) {\n const [failed, setFailed] = useState(false)\n const [focused, setFocused] = useState(false)\n const [uploadError, setUploadError] = useState<string | null>(null)\n // The latest props, for the editor's callbacks, which are made once.\n const latest = useRef({ value, format, codec, hold, references, mentions, upload, readMarkdown, onLeftUnsaved })\n useEffect(() => {\n latest.current = { value, format, codec, hold, references, mentions, upload, readMarkdown, onLeftUnsaved }\n })\n const ended = () => latest.current.hold?.ended() ?? false\n /*\n The text the editor holds as saved or loaded. A value that differs is\n someone else's save: loaded at once while you are not in it, waiting with a\n line while you are. `saved` is the same, for the editor's callbacks.\n */\n const [base, setBase] = useState(value)\n const saved = useRef(value)\n // The value your own save replaced: until your save comes back, the value still holds it, and it is not someone else's.\n const [superseded, setSuperseded] = useState<string | null>(null)\n // Every text your own saves wrote since someone else's last loaded: an echo of an earlier one can arrive after a later save.\n const own = useRef(new Set<string>())\n // A save out: nothing is loaded over the text it carries until it is answered.\n const [saving, setSaving] = useState(false)\n const committing = useRef(false)\n // What was typed here when the sign-in last ended, back after the passkey tap and not yet saved.\n // Not when it is what the value already holds (a save out as the sign-in ended went through), or nothing would\n // ever take later changes: only a save clears `restored`, and a save of what is saved sends nothing.\n const [held] = useState(() => {\n const doc = heldDocument(hold, holdKey)\n // A held document the codec cannot write (another version's, or cut short) is not text anyone can keep.\n try {\n return doc && codec.write(doc).value !== value ? doc : null\n } catch {\n return null\n }\n })\n // Until it is saved it is your unsaved text: someone else's save waits behind it, as behind a refused one.\n const [restored, setRestored] = useState(held !== null)\n // The text as last typed. Saving on the way out reads this, not the editor, which may already be torn down.\n const typed = useRef<JSONContent | null>(held)\n const again = useRef(false)\n const left = useRef(false)\n /*\n True from the moment the file dialog is asked for until the window has focus\n again: the dialog takes focus, and that blur must not save and leave.\n */\n const picking = useRef(false)\n const picker = useRef<HTMLInputElement>(null)\n // Blocks a refused save asks about: nothing is saved until each is chosen. The ref is for the callbacks.\n const [asking, setAsking] = useState<Asking | null>(null)\n const askingNow = useRef<Asking | null>(null)\n const ask = (next: Asking | null) => {\n askingNow.current = next\n setAsking(next)\n }\n // While blocks ask, what is lost if the text goes now: the text with your version of each. Otherwise `null`.\n const asked = (): JSONContent | null => {\n const now = askingNow.current\n return now && typed.current ? withBlocksFrom(typed.current, now.blocks, now.mine) : null\n }\n // The editor, for the callbacks made before it is.\n const current = useRef<Editor | null>(null)\n // Where each asking block's \"Your version\" is drawn: elements the editor's decorations place beside and under the block.\n const slots = useRef(new Map<string, HTMLElement>())\n const slotOf = useCallback((id: string, where: AskedSlot) => {\n const key = `${id} ${where}`\n let slot = slots.current.get(key)\n if (!slot) {\n slot = document.createElement('span')\n slot.className = ASKED_BLOCK_CLASSES[where]\n slot.contentEditable = 'false'\n slots.current.set(key, slot)\n }\n return slot\n }, [])\n\n /*\n The save asked: theirs is the saved text now, and the editor holds the\n merge, unsaved, with their words in each block that asks. A value still\n holding what this save replaced is not someone else's. `sent` is the text\n that save carried: what was typed since is kept, in the merge or as your\n version of a block that asks, and a block they changed too asks as well.\n */\n const askAbout = (answer: DocumentAsks, replaced: string, sent: JSONContent) => {\n const { codec: words, format: written } = latest.current\n // Both read back through the codec, so they compare with what the app answers.\n const asRead = (doc: JSONContent) => words.read(words.write(doc).value, written)\n const before = asRead(sent)\n const now = typed.current && typed.current !== sent ? asRead(typed.current) : before\n const since = blocksChanged(before, now)\n const mine = withBlocksFrom(words.read(answer.mine, written), since, now)\n const value = words.read(answer.value, written)\n const theirsToo = (id: string) => !!blockOf(before, id) && JSON.stringify(blockOf(value, id)) !== JSON.stringify(blockOf(before, id))\n const asks = [...answer.blocks, ...since.filter((id) => !answer.blocks.includes(id) && theirsToo(id))]\n // A block that asks must be in the text to be chosen: one they deleted that you changed is held as yours, at the end.\n const missing = asks.flatMap((id) => (blockOf(value, id) ? [] : (blockOf(mine, id) ?? [])))\n const merged = missing.length ? { ...value, content: [...(value.content ?? []), ...missing] } : value\n const held = withTypedSince(merged, now, since.filter((id) => !asks.includes(id)))\n const blocks = asks.filter((id) => blockOf(held, id))\n saved.current = answer.theirs\n shown.current = answer.theirs\n setSuperseded(replaced)\n setBase(answer.theirs)\n const editor = current.current\n if (editor && !editor.isDestroyed) editor.commands.setContent(held, { emitUpdate: false })\n typed.current = held\n ask(blocks.length ? { blocks, mine, theirs: words.read(answer.theirs, written), sinceOpened: !!answer.sinceOpened } : null)\n }\n\n const save = useCallback(\n async (doc: JSONContent | null) => {\n // Read only: a box ticked in a node view is not a save. After an ending the text is held, and a save would be refused.\n if (!doc || readOnly || ended()) return\n // Blocks ask: nothing of yours is saved until each is chosen.\n if (askingNow.current) return\n // A change made while a save is out goes next, not nowhere.\n if (committing.current) {\n again.current = true\n return\n }\n const next = latest.current.codec.write(doc)\n if (next.value === saved.current) return\n committing.current = true\n setSaving(true)\n // The later save wins: whatever the value holds as you save is replaced by yours.\n const replaced = latest.current.value\n const editedFrom = saved.current\n try {\n const answer = await onCommit(next.value, next.contentFormat, editedFrom)\n if (isAsks(answer)) {\n // Closed meanwhile: there is no text left to choose in, and nothing was saved. The app keeps what was sent.\n if (left.current) {\n if (!ended()) latest.current.onLeftUnsaved?.(next.value)\n } else {\n askAbout(answer, replaced, doc)\n setFailed(false)\n }\n return\n }\n const ok = answer\n if (ok) {\n // The editor already shows it, and may hold more typed since: `shown` keeps the effect below from setting it.\n saved.current = next.value\n shown.current = next.value\n own.current.add(next.value)\n setSuperseded(replaced)\n setBase(next.value)\n setRestored(false)\n // A save out as the sign-in ended: what was held then may hold more than this, typed since.\n const store = latest.current.hold\n if (store && holdKey && !store.ended()) store.release(holdKey)\n }\n if (left.current) {\n // Refused because the sign-in ended: the text is held for after the tap, not lost.\n if (!ok && !ended()) latest.current.onLeftUnsaved?.()\n } else setFailed(!ok)\n } catch {\n // A save that throws is a refusal: the text stays, and says so.\n if (left.current) {\n if (!ended()) latest.current.onLeftUnsaved?.()\n } else setFailed(true)\n } finally {\n committing.current = false\n setSaving(false)\n if (again.current && !askingNow.current) {\n again.current = false\n // After an ending it is held for after the tap, and a save would only be refused. Only a change: leaving\n // while a blur's save is out asks again for the same text, and a refused one would be sent and said twice.\n const waiting = typed.current\n if (!ended() && waiting && latest.current.codec.write(waiting).value !== next.value) void latestSave.current(waiting)\n }\n }\n },\n [onCommit, holdKey, readOnly],\n )\n\n // While open, an ending reads the unsaved text. Keyed on the key and on there being a store, not on the store object:\n // a new `hold` each render must not unregister, since the app's unregister forgets what was held unless an ending is under way.\n const holds = !!hold\n useEffect(() => {\n const store = latest.current.hold\n if (!holds || !store || !holdKey) return\n return store.register(holdKey, () => {\n // While blocks ask, your version of each is held: the ask itself does not outlive the passkey trip.\n const doc = asked() ?? typed.current\n return doc && latest.current.codec.write(doc).value !== saved.current ? JSON.stringify(doc) : undefined\n })\n }, [holdKey, holds])\n\n // The latest `save`, for the editor's `onBlur` (made once) and the unmount below.\n const latestSave = useRef(save)\n useEffect(() => {\n latestSave.current = save\n }, [save])\n // The text the editor was last set to, so a `base` it already shows is not set again under the caret.\n const shown = useRef(value)\n\n const openPicker = () => {\n picking.current = true\n const released = () => {\n picking.current = false\n window.removeEventListener('focus', released)\n }\n window.addEventListener('focus', released)\n picker.current?.click()\n }\n const pickFile = useRef(openPicker)\n pickFile.current = openPicker\n\n /* `/` File and a pasted picture: the upload first, then the block \u2014 its attributes are the upload's answer. */\n const attach = async (chosen: File[]) => {\n const uploadOne = latest.current.upload\n if (!uploadOne) return\n setUploadError(null)\n try {\n for (const file of chosen) {\n const attrs = await uploadOne(file)\n if (!editor || editor.isDestroyed) return\n editor.chain().focus().insertContent({ type: 'attachment', attrs }).run()\n }\n } catch (error) {\n setUploadError(error instanceof Error ? error.message : String(error))\n }\n }\n const attachTo = useRef(attach)\n attachTo.current = attach\n\n const editor = useEditor(\n {\n extensions: documentExtensions({\n latest,\n references,\n mentions,\n linkChips,\n table,\n upload: !!upload,\n readMarkdown: !!readMarkdown,\n comments: !!onCommentOnSelection,\n referenceView,\n attachmentView,\n pickFile,\n attach: attachTo,\n extensions,\n }),\n // Made once. A value coming back must not rebuild the editor under the caret; see the effect below.\n content: held ?? codec.read(value, format),\n editable: !readOnly,\n editorProps: {\n // Focusable when read only too: the selection strip, and so Comment on its words, shows only in a focused view.\n attributes: {\n 'aria-label': label,\n role: 'textbox',\n 'aria-multiline': 'true',\n tabindex: '0',\n // A row or a card is its whole line (`LinkPlaces`), drawn on that line: a block inside it would push the\n // separator and trailing break ProseMirror puts beside it onto empty lines of their own (code review).\n class: richTextClassName('default', cn('outline-none [&_[data-link-place]]:inline-block [&_[data-link-place]]:w-full [&_[data-link-place]]:align-top', EDITOR_SELECTION_CLASSES)),\n },\n handleKeyDown: (view, event) => {\n if (event.key !== 'Escape') return false\n // An open list or chip menu closes first; the next Escape leaves.\n if (isSuggestionOpen() || isReferenceMenuOpen(view.state)) return false\n const { selection, tr } = view.state\n // Words selected: the first Escape lets go of them, which also closes the strip.\n if (!selection.empty) {\n view.dispatch(tr.setSelection(TextSelection.create(tr.doc, selection.to)))\n return true\n }\n view.dom.blur()\n return true\n },\n },\n onUpdate: ({ editor: e, transaction }) => {\n typed.current = e.getJSON()\n // A click on a box does not focus the field, so no blur will save it.\n if (isChecklistTick(transaction)) void latestSave.current(typed.current)\n },\n onFocus: () => setFocused(true),\n onBlur: () => {\n setFocused(false)\n // The file dialog took focus: the person has not left.\n if (picking.current) return\n // Yours, if you changed anything: it replaces what waited. If not, what waited is loaded as you leave (below).\n void latestSave.current(typed.current)\n },\n },\n [],\n )\n\n /*\n Someone else's save. Not in the editor: theirs is the text now. In it, or\n with your own text unsaved after a refusal or an ending: it waits, and the\n line below says so. Never over a save that is still out.\n */\n const arrived = value !== base && value !== superseded && !own.current.has(value)\n // Read only, there is nothing of yours to keep: theirs loads even while you select words to comment on.\n if (arrived && (readOnly || (!focused && !saving && !failed && !restored && !asking))) {\n own.current.clear()\n setBase(value)\n }\n const waiting = arrived && !readOnly && (focused || failed || restored || !!asking)\n\n // The text the editor should hold, set into it when it changes \u2014 never under your own typing, which `shown` already holds.\n useEffect(() => {\n saved.current = base\n if (!editor || editor.isDestroyed || base === shown.current) return\n editor.commands.setContent(latest.current.codec.read(base, latest.current.format), { emitUpdate: false })\n shown.current = base\n typed.current = null\n }, [editor, base])\n\n // Made read only or editable while open: the editor follows, without being made again.\n useEffect(() => {\n if (editor && !editor.isDestroyed && editor.isEditable === readOnly) editor.setEditable(!readOnly, false)\n }, [editor, readOnly])\n\n const empty = useEditorState({ editor, selector: ({ editor: ed }) => !ed || ed.isEmpty })\n\n // \"Load it\": theirs replaces what you have not saved.\n const load = () => {\n setBase(latest.current.value)\n setFailed(false)\n setRestored(false)\n // Theirs replaces yours whole, so nothing is left to choose.\n ask(null)\n slots.current.clear()\n }\n\n // Closing saves on the way out. Not when the sign-in ended: the save would be refused and reported as lost over\n // the passkey screen, and the text is held on the device instead. Not while blocks ask: nothing is saved until chosen.\n useEffect(\n () => () => {\n left.current = true\n if (ended()) return\n const draft = asked()\n if (draft) latest.current.onLeftUnsaved?.(latest.current.codec.write(draft).value)\n else void latestSave.current(typed.current)\n },\n [],\n )\n\n useEffect(() => {\n current.current = editor\n onEditor?.(editor)\n return () => onEditor?.(null)\n }, [editor, onEditor])\n\n // The blocks that ask, drawn in the text; none once every one is chosen.\n const askedIds = asking?.blocks\n useEffect(() => {\n if (editor && !editor.isDestroyed) setAskedBlocks(editor, askedIds ?? [], slotOf)\n }, [editor, askedIds, slotOf])\n\n /*\n One block chosen: yours or theirs in its place, or the block gone when the\n one chosen deleted it. The last choice saves, after their text.\n */\n const choose = (id: string, side: Side) => {\n const now = askingNow.current\n if (!editor || editor.isDestroyed || !now) return\n const chosen = blockOf(side === 'mine' ? now.mine : now.theirs, id)\n const at = blockAt(editor.state.doc, id)\n if (at) {\n const end = at.pos + at.node.nodeSize\n const tr = chosen ? editor.state.tr.replaceWith(at.pos, end, editor.schema.nodeFromJSON(chosen)) : editor.state.tr.delete(at.pos, end)\n editor.view.dispatch(tr)\n }\n typed.current = editor.getJSON()\n const rest = now.blocks.filter((block) => block !== id)\n if (rest.length > 0) {\n ask({ ...now, blocks: rest })\n return\n }\n ask(null)\n slots.current.clear()\n void latestSave.current(typed.current)\n }\n\n const who = changedBy?.name ?? 'Someone'\n const drawn = (\n <div className=\"flex flex-col gap-1\">\n {asking?.sinceOpened && <FieldLine tone=\"helper\">This page changed since you opened it.</FieldLine>}\n <EditorBlockHandle editor={editor} actions={blockRows}>\n {/* A table's handles and \u2795 bars while you point at it; the block handle stays the table's. */}\n <EditorTableControls editor={editor}>\n <EditorContent editor={editor} className=\"-mx-2 cursor-text px-2 py-1\" data-document-editor=\"\" />\n </EditorTableControls>\n {empty && !readOnly && placeholder && (\n <span aria-hidden className=\"pointer-events-none absolute left-0 top-1 text-body-2 text-text-muted\">\n {placeholder}\n </span>\n )}\n </EditorBlockHandle>\n {/* Read only with comments off, the strip would have nothing in it: no strip. */}\n {(!readOnly || onCommentOnSelection) && <SelectionToolbar\n editor={editor}\n marks={readOnly ? [] : ['bold', 'italic', 'underline', 'code']}\n link={!readOnly}\n actions={\n onCommentOnSelection\n ? [\n {\n label: 'Comment',\n icon: <IconMessagePlus size={16} stroke={1.5} />,\n run: (ed) => {\n const anchor = anchorOfSelection(ed)\n if (!anchor) return\n // The draft's highlight keeps what is selected marked; the selection itself can go.\n ed.commands.setTextSelection(ed.state.selection.to)\n onCommentOnSelection(anchor)\n },\n },\n ]\n : []\n }\n />}\n <ReferenceMenuView editor={editor} />\n {/* Always there, so `/` \u2192 File, made as the editor opened, has a dialog to open even if `upload` came and went. */}\n <FilePicker ref={picker} multiple onPick={(files) => void attach(files)} />\n {asking?.blocks.flatMap((id) => {\n const mine = blockOf(asking.mine, id)\n const card = <YourVersion words={mine ? wordsOf(mine) : 'You deleted this block.'} onUseMine={() => choose(id, 'mine')} onDismiss={() => choose(id, 'theirs')} />\n // Beside the words, and under the block at phone width: one is shown at a time (`ASKED_BLOCK_CLASSES`).\n // @estiva-escape(estiva/no-hand-rolled-behaviour): into the block's slot in the text (AskedBlocks), not a floating panel.\n return (['beside', 'under'] as const).map((where) => createPortal(card, slotOf(id, where), `${id} ${where}`))\n })}\n {waiting && !merges && (\n <FieldLine tone=\"helper\">\n {`${who} saved a newer version.`}{' '}\n {/* Pressing it must not take focus from the editor: that blur would save yours over theirs first. */}\n <Button variant=\"muted\" size=\"small\" onMouseDown={(event) => event.preventDefault()} onClick={load}>\n Load it\n </Button>{' '}\n {/* What Load it costs, said where it is pressed (Miky, WBD-3's /land, 20 October). */}\n (replaces your changes)\n </FieldLine>\n )}\n {uploadError && <FieldLine tone=\"error\">{uploadError}</FieldLine>}\n {failed && <FieldLine tone=\"error\">Could not save. Your text is still here.</FieldLine>}\n </div>\n )\n return <>{wrap ? wrap(drawn, editor) : drawn}</>\n}\n\n/** What a document's editor is built from: the app's parts, and its latest handlers, read through `latest` (the editor is made once). */\nexport interface DocumentGrammar {\n latest: {\n current: {\n references?: DocumentReferences\n mentions?: DocumentMentions\n upload?: unknown\n readMarkdown?: (text: string) => JSONContent | undefined\n }\n }\n references?: DocumentReferences\n mentions?: DocumentMentions\n linkChips?: LinkChipsOptions\n /** `/` \u2192 Table. */\n table: boolean\n /** `/` \u2192 Upload, and a pasted picture placed. */\n upload: boolean\n /** Markdown pasted as plain text lands as blocks. */\n readMarkdown: boolean\n /** The comment highlights. */\n comments: boolean\n referenceView?: ComponentType<ReferenceViewProps>\n attachmentView?: ComponentType<AttachmentViewProps>\n /** Opens the file dialog, for `/` \u2192 Upload. */\n pickFile: { current: () => void }\n /** Uploads and places pasted pictures. */\n attach: { current: (files: File[]) => Promise<void> }\n extensions: readonly AnyExtension[]\n}\n\n/**\n * A document's grammar, one list for every editor of a document (`DocumentEditor`, `DocumentField`): the blocks, the\n * marks, links where they sit, `/`, and `[` and `@` when the app gives them.\n */\nexport function documentExtensions({ latest, references, mentions, linkChips, table, upload, readMarkdown, comments, referenceView, attachmentView, pickFile, attach, extensions }: DocumentGrammar): AnyExtension[] {\n return [\n DocumentKit.configure({\n strike: false,\n heading: { levels: [1, 2, 3] },\n dropcursor: blockDropCursor,\n codeBlock: false,\n // A link on words is made by pasting a URL over them or by the strip's Link, and opens on a click, as a bare\n // address does \u2014 through `BareLinks`, which opens only a followable address and never hands the tab this window;\n // Tiptap's own click opens without that. A bare address stays text: a link made on it by typing would change what is saved.\n link: { openOnClick: false, shouldAutoLink: () => false, HTMLAttributes: LINK_MARK_ATTRIBUTES },\n }),\n PasteOverWords,\n KeptSelection,\n BareLinks,\n CodeBlockColours,\n TableKit.configure({ table: { resizable: false } }),\n BlockId,\n // A block a refused save asks about, drawn so a save never carries it.\n AskedBlocks,\n Checklist,\n Callout,\n // A link is being edited only while the caret is on its line: anywhere else on the page it previews on hover.\n ReferenceNode.configure({ view: referenceView ?? null, editingLine: true }),\n // A link's chip in a sentence, its row alone on its line, its card in the row's place (SPEC \u00A713.3).\n LinkPlaces,\n // A click on a link offers Open, and alone on its line Show as Row or Card.\n ReferenceMenu,\n UnknownBlock,\n AttachmentNode.configure({ view: attachmentView ?? null }),\n SlashCommands.configure({ sections: slashSections({ table, upload, pickFile }) }),\n ...(references\n ? [\n ReferenceTrigger.configure({\n items: () => [],\n sections: (query) => latest.current.references?.sections(query) ?? [],\n subscribe: (listener) => latest.current.references?.subscribe?.(listener) ?? (() => {}),\n nodeName: 'reference',\n ariaLabel: references.ariaLabel,\n sectionLabel: references.sectionLabel,\n icon: references.icon ?? null,\n }),\n ]\n : []),\n ...(mentions\n ? [PersonReference.configure({ people: () => latest.current.mentions?.people() ?? [], uriOf: (person) => latest.current.mentions?.uriOf(person) ?? null })]\n : []),\n ...(linkChips ? [LinkChips.configure(linkChips)] : []),\n ...(upload\n ? [\n // A pasted picture is placed as `/` File places one; text on the clipboard stays text.\n PastedImages.configure({\n onImages: (pasted) => {\n if (!latest.current.upload) return false\n void attach.current(pasted)\n return true\n },\n }),\n ]\n : []),\n // Markdown pasted as plain text lands as the blocks it spells, tables included.\n ...(readMarkdown ? [PastedMarkdown.configure({ read: (text) => latest.current.readMarkdown?.(text) })] : []),\n // Where each comment is, drawn as a decoration, so a save never carries it.\n ...(comments ? [CommentHighlights] : []),\n ...extensions,\n ]\n}\n\n/**\n * `/`: the shared Format section with a document's checklist and callouts,\n * then Insert with what this editor can do. File and Mention type `[` and `@`,\n * so their lists open; Upload picks a file from the computer (Miky, 15 October\n * QA and 20 October at the Storybook: \"File\" for `[`, a Mention row, \"Upload\").\n */\nfunction slashSections({ table, upload, pickFile }: { table: boolean; upload: boolean; pickFile: { current: () => void } }): SlashSection[] {\n const insert: SlashCommand[] = [\n // Three by three with a header row, as every app's Insert \u2192 Table makes it.\n ...(table ? [{ key: 'insert-table', row: { label: 'Table' }, run: (editor: Editor) => void editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() }] : []),\n // Offered only where the editor has the list the row opens.\n { key: 'insert-link', row: { label: 'File', shortcut: '[' }, keywords: ['[', 'link', 'reference'], needs: ['referenceTrigger'], run: typeTrigger('[') },\n ...(upload ? [{ key: 'insert-upload', row: { label: 'Upload' }, keywords: ['attach', 'file', 'picture'], run: () => pickFile.current() }] : []),\n { key: 'insert-mention', row: { label: 'Mention', shortcut: '@' }, keywords: ['@', 'person', 'people'], needs: ['personReference'], run: typeTrigger('@') },\n ]\n return [formatSection('block'), ...(insert.length > 0 ? [{ label: 'Insert', commands: insert }] : [])]\n}\n", "import { Extension, type Editor } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\n/** Where an asked block's card is drawn: beside its words, or under them at phone width. */\nexport type AskedSlot = 'beside' | 'under'\n\n/** The blocks that ask, and where each one's card is drawn. */\ninterface AskedState {\n ids: readonly string[]\n /** The element one asked block's card is drawn into, there: the editor's, kept for as long as it asks. */\n slot: ((id: string, where: AskedSlot) => HTMLElement) | null\n}\n\nconst askedBlocksKey = new PluginKey<AskedState>('askedBlocks')\n\n/**\n * A block both people changed: marked by a bar in the accent colour at its edge, as long as its words and no longer,\n * with the card that holds your version beside them; its words wrap beside the card, and the next block starts below\n * both. At phone width the card sits under the block, outside the bar (the story `Project changes`, approved 2 November).\n * The block holds the card (the editor's blocks are a flex column's), so the bar is an element of its own, as tall as\n * the block's words as the plugin measures them: a widget, whose changes the editor leaves alone.\n */\nexport const ASKED_BLOCK_CLASSES = {\n block: 'relative -ml-3 pl-3',\n bar: 'absolute left-0 top-0 h-full w-0.5 bg-accent-primary',\n beside: 'hidden md:float-right md:ml-3 md:block md:w-64',\n under: 'mt-2 block md:hidden',\n} as const\n\nconst newBar = () => {\n const bar = document.createElement('span')\n bar.className = ASKED_BLOCK_CLASSES.bar\n bar.dataset.askedBar = ''\n bar.contentEditable = 'false'\n return bar\n}\n\n/**\n * How far down a block its words reach, to the foot of their last line, leaving out the card drawn in it; `null` when\n * it has none to measure.\n */\nfunction wordsHeight(block: HTMLElement): number | null {\n const top = block.getBoundingClientRect().top\n let bottom: number | null = null\n let glyphs = 0\n const range = document.createRange()\n const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT)\n for (let text = walker.nextNode(); text; text = walker.nextNode()) {\n if (text.parentElement?.closest('.ProseMirror-widget')) continue\n range.selectNodeContents(text)\n for (const box of range.getClientRects()) {\n if (box.height > 0 && (bottom === null || box.bottom > bottom)) [bottom, glyphs] = [box.bottom, box.height]\n }\n }\n if (bottom === null) return null\n // A line is taller than its letters: half the difference is below them, as half is above the first.\n const line = parseFloat(getComputedStyle(block).lineHeight)\n return bottom - top + (line > glyphs ? (line - glyphs) / 2 : 0)\n}\n\n/** Each asked block's bar as tall as its words; where nothing can be measured, as tall as the block. */\nfunction measureWords(root: HTMLElement) {\n for (const block of root.querySelectorAll<HTMLElement>('[data-asked-block]')) {\n const bar = block.querySelector<HTMLElement>('[data-asked-bar]')\n if (!bar) continue\n const height = typeof document.createRange().getClientRects === 'function' ? wordsHeight(block) : null\n const next = height === null ? '' : `${height}px`\n if (bar.style.height !== next) bar.style.height = next\n }\n}\n\n/** Each block with a `blockId` the editor holds, and where it is. */\nexport function blockAt(doc: ProseMirrorNode, id: string): { node: ProseMirrorNode; pos: number } | null {\n let found: { node: ProseMirrorNode; pos: number } | null = null\n doc.descendants((node, pos) => {\n if (found) return false\n if (node.attrs.blockId === id) {\n found = { node, pos }\n return false\n }\n return true\n })\n return found\n}\n\n/**\n * The blocks a refused save asks about (`DocumentEditor`'s `DocumentAsks`), drawn as decorations so a save never\n * carries them: the bar at the block's edge, and a slot at its end that the editor draws \"Your version\" into.\n */\nexport const AskedBlocks = Extension.create({\n name: 'askedBlocks',\n\n addProseMirrorPlugins() {\n return [\n new Plugin<AskedState>({\n key: askedBlocksKey,\n state: {\n init: () => ({ ids: [], slot: null }),\n apply(tr, previous) {\n return (tr.getMeta(askedBlocksKey) as AskedState | undefined) ?? previous\n },\n },\n props: {\n decorations(state) {\n const { ids, slot } = askedBlocksKey.getState(state) ?? { ids: [], slot: null }\n if (!slot || ids.length === 0) return null\n const drawn: Decoration[] = []\n for (const id of ids) {\n const at = blockAt(state.doc, id)\n if (!at) continue\n const end = at.pos + at.node.nodeSize\n drawn.push(Decoration.node(at.pos, end, { class: ASKED_BLOCK_CLASSES.block, 'data-asked-block': id }))\n // The same element each time, so the card drawn into it stays as the text around it changes. Beside: first in\n // the block, so its words wrap from its top; under: after the block, outside the bar.\n const widget = { ignoreSelection: true, stopEvent: () => true }\n const widgetAt = (pos: number, where: AskedSlot, side: number) =>\n Decoration.widget(pos, () => slot(id, where), { ...widget, key: `asked-${id}-${where}`, side })\n drawn.push(\n Decoration.widget(at.pos + 1, newBar, { ...widget, key: `asked-${id}-bar`, side: -2 }),\n widgetAt(at.pos + 1, 'beside', -1),\n widgetAt(end, 'under', 1),\n )\n }\n return drawn.length ? DecorationSet.create(state.doc, drawn) : null\n },\n },\n // The bar's height, again whenever the text, the editor's width or a card (drawn after the block) changes it.\n // Nothing is watched or measured while no block asks: typing costs what it did.\n view(view) {\n const measure = () => measureWords(view.dom)\n const resized = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure)\n let watched: readonly Element[] = []\n return {\n update() {\n const asking = (askedBlocksKey.getState(view.state)?.ids.length ?? 0) > 0\n const blocks = asking ? [...view.dom.querySelectorAll('[data-asked-block]')] : []\n if (resized && (blocks.length !== watched.length || blocks.some((block, i) => block !== watched[i]))) {\n resized.disconnect()\n if (blocks.length) for (const element of [view.dom, ...blocks]) resized.observe(element)\n watched = blocks\n }\n if (asking) measure()\n },\n destroy: () => resized?.disconnect(),\n }\n },\n }),\n ]\n },\n})\n\n/** Draw these blocks as asking, with their cards in `slot`; none, to draw nothing. */\nexport function setAskedBlocks(editor: Editor, ids: readonly string[], slot: (id: string, where: AskedSlot) => HTMLElement) {\n if (editor.isDestroyed) return\n editor.view.dispatch(editor.state.tr.setMeta(askedBlocksKey, { ids, slot }))\n}\n", "import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type MouseEvent, type ReactNode } from 'react'\nimport type { AnyExtension, Editor } from '@tiptap/core'\nimport { EditorContent, useEditor, useEditorState, type JSONContent } from '@tiptap/react'\nimport type { AttachmentViewProps, ReferenceViewProps } from './BlockNodes'\nimport { cn } from './cn'\nimport { documentExtensions, type DocumentCodec, type DocumentMentions, type DocumentReferences } from './DocumentEditor'\nimport { useFormBusy } from './formBusy'\nimport type { LinkChipsOptions } from './LinkChips'\nimport { EDITOR_SELECTION_CLASSES, FIELD_SHELL_CLASSES, FIELD_SHELL_FOCUS_CLASSES } from './looks'\nimport { ReferenceMenuView } from './ReferenceMenu'\nimport { richTextClassName } from './RichText'\nimport { SelectionToolbar } from './SelectionToolbar'\nimport { isSuggestionOpen } from './suggestionPopup'\n\nexport interface DocumentFieldProps {\n /** What the field holds, in `format`; `''` when nothing is written. A value that is not its own edit coming back is loaded into it. */\n value: string\n /** The format `value` is in, handed to `codec.read`. */\n format: string\n /** How the app's text and the editor's document turn into each other: `DocumentEditor`'s. */\n codec: DocumentCodec\n /** Every edit, as it is typed: the text and its format, or `''` once it is emptied or holds only spaces and blank lines. Nothing is saved: the form around it sends. */\n onChange: (value: string, contentFormat: string | undefined) => void\n /** The editor's accessible name: the label of the `Field` around it. */\n label: string\n /** Muted words in the empty field. */\n placeholder?: ReactNode\n /** `[` and `/` \u2192 File. */\n references?: DocumentReferences\n /** `@` and `/` \u2192 Mention. */\n mentions?: DocumentMentions\n /** A pasted app URL drawn as the chip of what it names (`LinkChips`). */\n linkChips?: LinkChipsOptions\n /** Plain text pasted as the blocks it spells: the app's reader of markdown, as the editor's document. */\n readMarkdown?: (text: string) => JSONContent | undefined\n /** Draws a link: the app's own, which resolves what it names. */\n referenceView?: ComponentType<ReferenceViewProps>\n /** Draws a placed file: the app's own card. */\n attachmentView?: ComponentType<AttachmentViewProps>\n /** More of the app's own extensions. */\n extensions?: readonly AnyExtension[]\n /** Set by a required `Field` around it, for a screen reader. */\n 'aria-required'?: boolean | 'true' | 'false'\n}\n\nconst NONE: readonly AnyExtension[] = []\nconst nothing = () => {}\n\n/** Nothing but spaces and blank lines: no word, and no link, card or picture (any part of it that is not text or a line break). */\nconst isBlank = (editor: Editor) => {\n let blank = true\n editor.state.doc.descendants((node) => {\n if (node.isText ? /\\S/.test(node.text ?? '') : node.isLeaf && node.type.name !== 'hardBreak') blank = false\n return blank\n })\n return blank\n}\n\n/**\n * A form's field that holds a document: a description written in the form that files it. The document editor's\n * grammar (`DocumentEditor`'s blocks, marks, `[`, `@` and `/`) in a field's box, as a Textarea's beside it. It is the\n * form's: every edit goes back as it is typed, nothing is saved on leaving, Ctrl/Cmd+Enter sends the form, and while\n * the form sends nothing can be written in it.\n *\n * **Told apart by everything it has handed back, not only the last** (Peek's `ProseField`, RIC-13). Keys pressed faster\n * than React renders reach the editor before the value from the previous one comes back. Compared with the last edit\n * alone, that older value looked like one from outside and was loaded over the newer text. A value this field wrote is\n * never an outside value, however late it arrives; each is dropped once the value has shown it, so the queue holds only\n * the edits still in flight. A queue, not a set: `a`, `ab`, `a` (a key and its Backspace) repeats a value.\n */\nexport function DocumentField({\n value,\n format,\n codec,\n onChange,\n label,\n placeholder,\n references,\n mentions,\n linkChips,\n readMarkdown,\n referenceView,\n attachmentView,\n extensions = NONE,\n 'aria-required': required,\n}: DocumentFieldProps) {\n // The latest props, for the editor's callbacks, which are made once.\n const latest = useRef({ value, format, codec, onChange, references, mentions, readMarkdown })\n useEffect(() => {\n latest.current = { value, format, codec, onChange, references, mentions, readMarkdown }\n })\n // What this field has handed back and the value has not shown yet, oldest first.\n const inFlight = useRef<string[]>([value])\n // `''` too is the codec's to read, as the document editor reads it: a block typed into it then gets its id.\n const read = (text: string) => latest.current.codec.read(text, latest.current.format)\n // No upload in a field: `/` has no Upload, and a pasted picture stays the browser's.\n const pickFile = useRef(nothing)\n const attach = useRef(async () => {})\n const [initial] = useState(() => read(value))\n\n const editor = useEditor(\n {\n extensions: documentExtensions({\n latest,\n references,\n mentions,\n linkChips,\n table: false,\n upload: false,\n readMarkdown: !!readMarkdown,\n comments: false,\n referenceView,\n attachmentView,\n pickFile,\n attach,\n extensions,\n }),\n // Made once: a value coming back must not rebuild the editor under the caret; see the effect below.\n content: initial,\n editorProps: {\n attributes: {\n 'aria-label': label,\n role: 'textbox',\n 'aria-multiline': 'true',\n ...(required !== undefined && required !== false ? { 'aria-required': 'true' } : {}),\n // Three lines tall at rest, as a Textarea of three rows beside it. A row or a card is its whole line (`LinkPlaces`).\n // eslint-disable-next-line token-spacing/no-restricted-classes -- @estiva-escape: three lines of the field's own text (140% of 14px each), the height of a Textarea of three rows\n class: richTextClassName('default', cn('outline-none min-h-[4.2em] [&_[data-link-place]]:inline-block [&_[data-link-place]]:w-full [&_[data-link-place]]:align-top', EDITOR_SELECTION_CLASSES)),\n },\n /*\n Ctrl/Cmd+Enter sends the form around it, as from any of its fields. The field asks the form itself: the\n editor marks every Enter it is given as handled (a browser's Enter would otherwise change the text), and the\n form leaves a handled key alone \u2014 measured in Chrome, the form never heard it. An open list keeps its keys.\n */\n handleKeyDown: (view, event) => {\n if (event.key !== 'Enter' || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || isSuggestionOpen()) return false\n const form = view.dom.closest('form')\n if (!form) return false\n form.requestSubmit()\n return true\n },\n },\n onUpdate: ({ editor: ed }) => {\n // Emptied, or only spaces and blank lines, it holds nothing: `''`, so a required field is missing again (Peek's ProseField).\n const next = isBlank(ed) ? { value: '' } : latest.current.codec.write(ed.getJSON())\n inFlight.current.push(next.value)\n latest.current.onChange(next.value, next.contentFormat)\n },\n },\n [],\n )\n\n useEffect(() => {\n if (!editor || editor.isDestroyed) return\n const at = inFlight.current.indexOf(value)\n if (at !== -1) {\n // Its own edit coming round, possibly late. Values render in order, so nothing handed back before it can still\n // arrive: drop those, keep the rest.\n inFlight.current = inFlight.current.slice(at + 1)\n return\n }\n inFlight.current = []\n // `read` takes the latest codec and format, set by the effect above, which runs first.\n editor.commands.setContent(read(value), { emitUpdate: false })\n }, [editor, value])\n\n /*\n While its form sends it waits, as the fields beside it do. The form's disabled fieldset switches off every native\n control in it, and a document's box is not one: it is told here, before the paint, with no edit handed back.\n */\n const busy = useFormBusy()\n useLayoutEffect(() => {\n if (editor && !editor.isDestroyed && editor.isEditable === busy) editor.setEditable(!busy, false)\n }, [editor, busy])\n\n const empty = useEditorState({ editor, selector: ({ editor: ed }) => !ed || ed.isEmpty })\n\n // A press on the box's padding puts the caret in, as a Textarea's does.\n const into = (event: MouseEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget || !editor) return\n event.preventDefault()\n editor.commands.focus('end')\n }\n\n return (\n <>\n <div className={cn(FIELD_SHELL_CLASSES, FIELD_SHELL_FOCUS_CLASSES, 'relative cursor-text px-3 py-2')} onMouseDown={into}>\n <EditorContent editor={editor} />\n {empty && placeholder && (\n <span aria-hidden className=\"pointer-events-none absolute left-3 top-2 text-body-2 text-text-muted\">\n {placeholder}\n </span>\n )}\n </div>\n <SelectionToolbar editor={editor} marks={['bold', 'italic', 'underline', 'code']} link />\n <ReferenceMenuView editor={editor} />\n </>\n )\n}\n"],
5
- "mappings": ";AAAA,SAAS,aAAa,WAAW,QAAQ,gBAAgC;AAEzE,SAAS,iBAAiB;AAC1B,SAAS,QAAQ,iBAAiB;AAClC,SAAS,YAAY,qBAAqB;AAC1C,SAAS,UAAU,UAAU,YAAY,UAAU,qBAAqB;AACxE,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,SAAS,eAAe,wBAAwB;AACzD,SAAS,qBAAqB;AA8btB,cAqBA,YArBA;AApaD,IAAM,mBAAmB,IAAI,UAA4B,eAAe;AAGxE,IAAM,gBAAgB,UAAU,OAAO;AAAA,EAC5C,MAAM;AAAA,EAEN,wBAAwB;AACtB,WAAO;AAAA,MACL,IAAI,OAAyB;AAAA,QAC3B,KAAK;AAAA,QACL,OAAO;AAAA,UACL,MAAM,MAAM;AAAA,UACZ,MAAM,IAAI,UAAU;AAClB,kBAAM,OAAO,GAAG,QAAQ,gBAAgB;AACxC,gBAAI,SAAS,OAAW,QAAO;AAC/B,gBAAI,CAAC,SAAU,QAAO;AAGtB,mBAAO,EAAE,MAAM,GAAG,QAAQ,IAAI,SAAS,IAAI,GAAG,IAAI,GAAG,QAAQ,IAAI,SAAS,EAAE,EAAE;AAAA,UAChF;AAAA,QACF;AAAA,QACA,OAAO;AAAA,UACL,YAAY,OAAO;AACjB,kBAAM,QAAQ,iBAAiB,SAAS,KAAK;AAC7C,gBAAI,CAAC,SAAS,MAAM,SAAS,MAAM,GAAI,QAAO;AAC9C,mBAAO,cAAc,OAAO,MAAM,KAAK;AAAA,cACrC,WAAW,OAAO,MAAM,MAAM,MAAM,IAAI,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aAAa,MACjH;AAAA,sBAAAP,MAACU,gBAAA,EAAc,QAAgB;AAAA,MAC9B,SAAS,eACR,gBAAAV,MAAC,UAAK,eAAW,MAAC,WAAU,yEACzB,uBACH;AAAA,OAEJ;AAAA,IACA,gBAAAA,MAAC,oBAAiB,QAAgB,OAAO,CAAC,QAAQ,UAAU,aAAa,MAAM,GAAG,MAAI,MAAC;AAAA,IACvF,gBAAAA,MAAC,qBAAkB,QAAgB;AAAA,KACrC;AAEJ;",
4
+ "sourcesContent": ["import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'\nimport type { Editor } from '@tiptap/react'\nimport { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport { IconBold, IconCode, IconItalic, IconLink, IconUnderline } from '@tabler/icons-react'\nimport { Form } from './Form'\nimport { Popover } from './Popover'\nimport { TextInput } from './TextInput'\nimport { Toolbar, ToolbarButton, ToolbarSeparator } from './Toolbar'\nimport { shortcutLabel } from './shortcuts'\n\n/**\n * The selection, kept visible while something else has the focus \u2014 Peek's\n * `src/extensions/keptSelection.ts` (PEE-19), moved into the package with the\n * `SelectionToolbar` that needs it (UIG-31, Katerina's ruling 29 September).\n *\n * The toolbar's address field takes the focus, and with it the document's\n * one selection, so the words being linked lost their highlight the moment\n * the field opened (measured 2026-09-07). Linear keeps it, and Katerina asked\n * for the same. The editor's own selection never moved \u2014 ProseMirror keeps it\n * while unfocused \u2014 so this only *draws* it: an inline decoration over the\n * range, in `bg-selected` \u2014 the token every kit editor paints `::selection` in\n * (`EDITOR_SELECTION_CLASSES`) \u2014 mapped through edits and cleared when the field closes.\n *\n * A decoration rather than a second selection, because a document has one\n * and the field needs it. Editor-internal by design (the editor owns its own\n * drawing); nothing here floats, focuses or handles a key.\n */\n\nexport interface KeptRange {\n from: number\n to: number\n}\n\n/** The plugin's key: read what is being kept, or dispatch a change to it. */\nexport const keptSelectionKey = new PluginKey<KeptRange | null>('keptSelection')\n\n/** The extension an editor registers so a selection can stay drawn while a field has the focus. */\nexport const KeptSelection = Extension.create({\n name: 'keptSelection',\n\n addProseMirrorPlugins() {\n return [\n new Plugin<KeptRange | null>({\n key: keptSelectionKey,\n state: {\n init: () => null,\n apply(tr, previous) {\n const meta = tr.getMeta(keptSelectionKey) as KeptRange | null | undefined\n if (meta !== undefined) return meta\n if (!previous) return null\n // Follow the words through an edit, so applying the link to them\n // (or typing before them) does not leave the highlight behind.\n return { from: tr.mapping.map(previous.from), to: tr.mapping.map(previous.to) }\n },\n },\n props: {\n decorations(state) {\n const range = keptSelectionKey.getState(state)\n if (!range || range.from === range.to) return null\n return DecorationSet.create(state.doc, [\n Decoration.inline(range.from, range.to, { class: 'kept-selection bg-bg-selected' }),\n ])\n },\n },\n }),\n ]\n },\n})\n\n/** Draw the selection as it is now, until `releaseSelection`. */\nexport function keepSelection(editor: Editor) {\n const { from, to } = editor.state.selection\n editor.view.dispatch(editor.state.tr.setMeta(keptSelectionKey, { from, to }))\n}\n\n/** Stop drawing it. Nothing kept, nothing dispatched. */\nexport function releaseSelection(editor: Editor) {\n if (editor.isDestroyed || !keptSelectionKey.getState(editor.state)) return\n editor.view.dispatch(editor.state.tr.setMeta(keptSelectionKey, null))\n}\n\n/** What is being drawn, or null. */\nexport function keptSelection(editor: Editor): KeptRange | null {\n return keptSelectionKey.getState(editor.state) ?? null\n}\n\n/** A mark the strip can toggle \u2014 the suite's inline vocabulary (SPEC \u00A713.1) less link and reference. */\nexport type MarkId = 'bold' | 'italic' | 'underline' | 'code'\n\nconst MARKS: Record<MarkId, { label: string; keys: string }> = {\n bold: { label: 'Bold', keys: 'Mod-B' },\n italic: { label: 'Italic', keys: 'Mod-I' },\n underline: { label: 'Underline', keys: 'Mod-U' },\n code: { label: 'Code', keys: 'Mod-E' },\n}\n\n/**\n * Toggle one mark over the current selection. The core `toggleMark`, which\n * each mark's own `toggleBold` and the like wrap: the package names no Tiptap\n * extension, only the marks the suite's format has (SPEC \u00A713.1).\n */\nfunction toggleMark(editor: Editor, id: MarkId): boolean {\n return editor.chain().focus().toggleMark(id).run()\n}\n\n/** The address the selection sits in, or '' \u2014 what the link field opens with. */\nexport function currentLink(editor: Editor): string {\n const href: unknown = editor.getAttributes('link').href\n return typeof href === 'string' ? href : ''\n}\n\n/**\n * What somebody typed into the link field \u2192 an `href`, or null when it cannot\n * be one. A bare host (`google.com`) gets `https://`. A scheme is kept only when\n * SPEC \u00A713.1 lets a reader follow it (http, https, mailto); `javascript:` and\n * the like are refused here. `localhost:5173` is a host and a port: a scheme is\n * never followed by a digit.\n */\nexport function normalizeHref(raw: string): string | null {\n const s = raw.trim()\n if (!s || /\\s/.test(s)) return null\n if (/^(https?:|mailto:)/i.test(s)) return s\n if (/^[a-z][a-z0-9+.-]*:(?!\\d)/i.test(s)) return null\n return `https://${s}`\n}\n\n/**\n * Apply the link field to the selection. Empty removes the link; an address\n * sets it, over the whole link when the caret sits inside one. `false` means\n * the text could not be an address, and the field should stay open.\n */\nexport function applyLink(editor: Editor, raw: string): boolean {\n const chain = editor.chain().focus().extendMarkRange('link')\n // The core commands the Link extension's `setLink` and `unsetLink` wrap, with\n // the same meta; `normalizeHref` has already refused what it would refuse.\n if (!raw.trim()) return chain.unsetMark('link', { extendEmptyMarkRange: true }).setMeta('preventAutolink', true).run()\n const href = normalizeHref(raw)\n if (!href) return false\n return chain.setMark('link', { href }).setMeta('preventAutolink', true).run()\n}\n\n/**\n * Bold / italic / underline / link over selected text \u2014 Peek's\n * `SelectionToolbar` (PEE-18, PEE-19), moved into the package at Katerina's\n * word (29 September, UIG-31) when Ship's description became its second user.\n * Unchanged but for two props: `marks`, which buttons the strip has (Peek's\n * three by default; Ship adds code), and `link`, whether it has the Link button\n * and its field (Peek's editor has a link mark; an editor without one leaves it\n * off). The editor must register `KeptSelection` when `link` is on.\n *\n * The marks apply to a run you have already written, which is why they are\n * not in the `/` menu: typing `/` replaces the selection, so by definition\n * there is nothing selected to apply them to.\n *\n * **The chrome is the shared `Popover`, anchored** (P26). It was a `Menu`, and\n * it never was one: a menu gives its contents roving focus and typeahead,\n * which would fight the link field this panel exists for. An anchored\n * `Popover` is the mode built for exactly this \u2014 it takes no focus, so the\n * caret stays in the text. It is laid out as a row instead of a column\n * through `className`, which `cn` merges last. The panel still portals out of\n * the composer, so no overflow clips it, and Floating UI clamps it on screen.\n *\n * **The anchor is the selection's own point** since 0.12.2. This toolbar is\n * *centred* over the selection (her design, PEE-19, after Linear), and the\n * package's `Popover` aligns left or right only \u2014 Base UI has `center`, the\n * package does not expose it (ADOPTION **B21**). So the placement arithmetic\n * and the hand-measured `SIZE` box stay for now, and the rect handed over is\n * positioned so the panel lands on the same pixel it always has: the\n * package's own 4px gap is subtracted from this file's 8px, and the rect's\n * left edge is the panel's. When `align=\"center\"` exists, `SIZE`, `GAP` and\n * `placement` all go and the anchor becomes the selection's own rect.\n *\n * **Two faces** (PEE-19 \u2014 Katerina, 2026-09-07, after Linear). `marks` is the\n * row of four buttons. `link` is one text field for the address: it opens from\n * the Link button, and opens by itself when the settled selection sits inside\n * a link, with that link's address in it. There is no open, embed or delete\n * button, by her call: the field is the whole control.\n *\n * **What applies the field** (her rule, same day): Enter, and clicking away \u2014\n * anywhere outside the toolbar, the editor included. Enter on an empty field\n * removes the link; clicking away with an empty field changes nothing, since\n * removing is deliberate and leaving is not. Escape drops what was typed and\n * puts the caret back. Once applied, the caret lands after the link, and\n * typing goes on as plain text \u2014 the mark is not inclusive (editorKit).\n *\n * While the field has focus the editor has not, so everything below that\n * hides the toolbar on blur or on an empty editor selection stands down in\n * `link` mode. The editor keeps its selection while unfocused; `focus()` in\n * the apply command puts it back.\n *\n * **Why it waits.** Showing on every selection change put the toolbar under the\n * pointer mid-drag, and made it blink on a plain click \u2014 ProseMirror restores\n * the previous selection when the editor takes focus and collapses it a tick\n * later, so there is a real, non-empty range in between. Both go away by\n * refusing to show while the pointer is down and re-reading the selection after\n * a short settle rather than trusting the event that woke us.\n */\n\nconst ICONS: Record<MarkId, typeof IconBold> = {\n bold: IconBold,\n italic: IconItalic,\n underline: IconUnderline,\n code: IconCode,\n}\n\ntype Mode = 'marks' | 'link'\n\n/** How long a selection must stand still before the toolbar appears. */\nconst SETTLE_MS = 250\nconst GAP = 8\n/** The gap the package's `Popover` adds of its own, subtracted above so the\n * panel keeps this file's 8px. Read from `Popover.tsx`, not guessed. */\nconst POPOVER_GAP = 4\n\nexport interface SelectionToolbarProps {\n /** The editor whose selection the strip follows. `null` while it loads. */\n editor: Editor | null\n /** Which marks the strip toggles, in order. Default bold, italic, underline. */\n marks?: readonly MarkId[]\n /** The Link button and its address field. Needs a link mark in the editor and `KeptSelection`. Default off. */\n link?: boolean\n /**\n * More of the strip, after the marks: the app's own `ToolbarButton`s for what\n * is selected \u2014 a chip's card, say. Each keeps the selection by preventing\n * its press's default, as the marks do. Nothing is added when it renders\n * nothing.\n */\n children?: ReactNode\n /**\n * The app's own buttons after the marks, past a separator: \"Comment\". Each\n * runs with the selection still in place, and the strip closes after it.\n */\n actions?: readonly SelectionAction[]\n}\n\n/** One of the app's buttons in the strip. */\nexport interface SelectionAction {\n /** Says what it does: the tooltip and the button's name. */\n label: string\n /** A 16px icon. */\n icon: ReactNode\n /** The keys that do the same, shown in the tooltip (\"Mod-Shift-M\"). */\n keys?: string\n /** What it does, with the selection as it is. */\n run: (editor: Editor) => void\n}\n\nexport function SelectionToolbar({ editor, marks = ['bold', 'italic', 'underline'], link = false, children, actions = [] }: SelectionToolbarProps) {\n /** The selection's top edge and horizontal centre; the face decides the rest. */\n const [anchor, setAnchor] = useState<{ top: number; centre: number } | null>(null)\n const [mode, setMode] = useState<Mode>('marks')\n const [url, setUrl] = useState('')\n // Re-render as marks turn on and off while the caret moves through the\n // selection, so the pressed states stay honest.\n const [, setTick] = useState(0)\n const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const pointerDown = useRef(false)\n const field = useRef<HTMLInputElement>(null)\n /** What the field holds while it is open; null while it is closed. The\n * listeners below are bound once, so they read this rather than state. */\n const draft = useRef<string | null>(null)\n // Read by the same listeners. Kept in an effect, declared before the focus\n // effect below so the ref already says `link` when the field's focus blurs\n // the editor.\n const modeRef = useRef<Mode>('marks')\n useEffect(() => {\n modeRef.current = mode\n }, [mode])\n // Read by `settle`, which is bound once: words already a link open the field only when there is one.\n const linkOn = useRef(link)\n linkOn.current = link\n\n const hide = useCallback(() => {\n clearTimeout(timer.current)\n draft.current = null\n if (editor) releaseSelection(editor)\n setAnchor(null)\n setMode('marks')\n }, [editor])\n\n /**\n * Leaving the field applies it (Enter or a click away). An address links the\n * words and the caret moves past them; an empty field on the way out is a\n * shrug, not a removal. Idempotent: the outside click reaches this twice,\n * once from the editor press and once from the Menu's own listener.\n */\n const commit = useCallback(() => {\n const text = draft.current\n if (text === null || !editor) return\n draft.current = null\n if (text.trim() && applyLink(editor, text)) {\n editor.commands.setTextSelection(editor.state.selection.to)\n }\n hide()\n }, [editor, hide])\n\n /** Read the selection as it is *now* and place the toolbar, or hide it. */\n const settle = useCallback(() => {\n if (!editor || editor.isDestroyed) return\n // Keeping the selection drawn is itself a transaction, which schedules\n // this; by then the field has the focus, and reading `hasFocus()` here\n // would close it.\n if (modeRef.current === 'link') return\n const { state, view } = editor\n const { empty, from, to } = state.selection\n if (empty || from === to || !view.hasFocus() || pointerDown.current) {\n setAnchor(null)\n setMode('marks')\n return\n }\n const start = view.coordsAtPos(from)\n const end = view.coordsAtPos(to)\n const centre = (Math.min(start.left, end.left) + Math.max(start.right, end.right)) / 2\n // Words that are already a link open on the field, with their address in it.\n const inLink = linkOn.current && editor.isActive('link')\n const address = inLink ? currentLink(editor) : ''\n draft.current = inLink ? address : null\n // The field is about to take the focus; the words stay highlighted.\n if (inLink) keepSelection(editor)\n setMode(inLink ? 'link' : 'marks')\n setUrl(address)\n setAnchor({ top: start.top, centre })\n }, [editor])\n\n useEffect(() => {\n if (!editor) return\n\n const schedule = () => {\n // The field owns the keyboard and the focus; the editor's own events\n // stand down until it closes.\n if (modeRef.current === 'link') return\n setTick((t) => t + 1)\n clearTimeout(timer.current)\n // A collapsed selection hides at once \u2014 waiting to hide is what made the\n // click blink. Only *showing* is deferred.\n if (editor.state.selection.empty) {\n setAnchor(null)\n return\n }\n timer.current = setTimeout(settle, SETTLE_MS)\n }\n\n // The field taking focus is the one blur that must not hide us.\n const onBlur = () => {\n if (modeRef.current !== 'link') hide()\n }\n\n // Only a press *inside the editor* starts a selection. A press on the\n // toolbar itself must not hide it \u2014 doing so unmounted the button before\n // its click could land, so nothing ever applied.\n const startsSelection = (e: MouseEvent) =>\n e.target instanceof Node && editor.view.dom.contains(e.target)\n\n const onPointerDown = (e: MouseEvent) => {\n if (!startsSelection(e)) return\n // A press in the editor while the field is open is a click away: apply\n // first, before the editor moves the caret under the press.\n commit()\n pointerDown.current = true\n hide()\n }\n const onPointerUp = () => {\n if (!pointerDown.current) return\n pointerDown.current = false\n schedule()\n }\n\n editor.on('selectionUpdate', schedule)\n editor.on('transaction', schedule)\n editor.on('blur', onBlur)\n // @estiva-escape(no-hand-rolled-behaviour): watches presses in the editor to follow a text selection; the Popover it opens in has no trigger to own that (Peek's UIG-8 escape, moved here with the part, UIG-31)\n document.addEventListener('mousedown', onPointerDown, true)\n document.addEventListener('mouseup', onPointerUp, true)\n\n return () => {\n clearTimeout(timer.current)\n editor.off('selectionUpdate', schedule)\n editor.off('transaction', schedule)\n editor.off('blur', onBlur)\n document.removeEventListener('mousedown', onPointerDown, true)\n document.removeEventListener('mouseup', onPointerUp, true)\n }\n }, [editor, settle, hide, commit])\n\n // The field takes focus once it is on screen. Not `autoFocus`, and not in\n // the same frame: the Menu renders once hidden to measure itself, and a\n // hidden input cannot take focus \u2014 measured 2026-09-07, the field opened\n // unfocused on a re-selected link. An address already in it is selected\n // whole, so typing replaces it.\n useEffect(() => {\n if (mode !== 'link' || !anchor) return\n const frame = requestAnimationFrame(() => {\n field.current?.focus()\n field.current?.select()\n })\n return () => cancelAnimationFrame(frame)\n }, [mode, anchor])\n\n if (!editor || !anchor) return null\n\n const openField = () => {\n const address = currentLink(editor)\n draft.current = address\n keepSelection(editor)\n setUrl(address)\n setMode('link')\n }\n /** Enter. Unlike a click away, an empty field here means remove. */\n const submit = () => {\n if (!url.trim()) {\n applyLink(editor, '')\n hide()\n editor.commands.focus()\n return\n }\n commit()\n }\n const discard = () => {\n hide()\n editor.commands.focus()\n }\n\n /* A zero-sized rect at the selection's own top edge and centre. The panel's\n width is no longer this file's business: `align=\"center\"` puts the\n panel's middle over this point (B21, package 0.12.2), so the measured\n `SIZE` table and the placement arithmetic that stood in for it are gone.\n The top is this file's GAP less the package's own 4, so the panel keeps\n the 8px it has always had. */\n const anchorRect = new DOMRect(anchor.centre, anchor.top - (GAP - POPOVER_GAP), 0, 0)\n\n return (\n <Popover\n anchor={anchorRect}\n open\n side=\"top\"\n align=\"center\"\n onOpenChange={(next) => {\n if (!next) commit()\n }}\n ariaLabel=\"Text formatting\"\n // The panel gives up its column; the strip inside draws the row. The 4px\n // around it is `contentClassName`'s: on `className` it was added to the\n // package's 8px from 0.12.6 on, and the toolbar grew 8px a side\n // (Katerina, 2026-09-13; migration docs D68, Finding 60). This is the\n // package's own `Popover/A toolbar` story, class for class.\n className=\"w-auto min-w-0\"\n contentClassName=\"p-1\"\n >\n {mode === 'link' ? (\n /* One field, so no strip: a toolbar of one control is a toolbar in\n name only, and `ToolbarInput` cannot take the ref this field is\n focused by (ADOPTION B25). */\n // The package Form (UIG-7): Enter applies the link. `free` and `flex`: one field, which keeps its own height.\n <Form onSubmit={submit} layout=\"free\" className=\"flex\">\n <TextInput\n ref={field}\n value={url}\n onChange={(e) => {\n setUrl(e.target.value)\n draft.current = e.target.value\n }}\n onKeyDown={(e) => {\n if (e.key === 'Escape') {\n // Before the Menu's own Escape, which would apply instead.\n e.stopPropagation()\n discard()\n }\n }}\n placeholder=\"Enter link URL\"\n aria-label=\"Link URL\"\n className=\"w-[264px]\"\n />\n </Form>\n ) : (\n /* Four marks and a link button: one Tab stop, \u2190 \u2192 along them (D29). */\n <Toolbar aria-label=\"Text formatting\" surface={false}>\n {marks.map((id) => {\n const Icon = ICONS[id]\n const active = editor.isActive(id)\n return (\n <ToolbarButton\n key={id}\n aria-label={MARKS[id].label}\n pressed={active}\n tooltip={MARKS[id].label}\n tooltipShortcut={shortcutLabel(MARKS[id].keys)}\n // Keep the selection: focus must not leave the editor on press.\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => toggleMark(editor, id)}\n >\n <Icon size={16} stroke={1.5} />\n </ToolbarButton>\n )\n })}\n {link && (\n <ToolbarButton\n aria-label=\"Link\"\n tooltip=\"Link\"\n onMouseDown={(e) => e.preventDefault()}\n onClick={openField}\n >\n <IconLink size={16} stroke={1.5} />\n </ToolbarButton>\n )}\n {children}\n {/* Between the marks and the app's buttons: with no mark or Link before them (read only), nothing to part. */}\n {actions.length > 0 && (marks.length > 0 || link || children) && <ToolbarSeparator />}\n {actions.map((action) => (\n <ToolbarButton\n key={action.label}\n aria-label={action.label}\n tooltip={action.label}\n tooltipShortcut={action.keys ? shortcutLabel(action.keys) : undefined}\n onMouseDown={(e) => e.preventDefault()}\n onClick={() => {\n // Closing first: it lets go of a kept selection, which the action may want to keep.\n hide()\n action.run(editor)\n }}\n >\n {action.icon}\n </ToolbarButton>\n ))}\n </Toolbar>\n )}\n </Popover>\n )\n}\n", "import { Fragment, useCallback, useContext, useEffect, useLayoutEffect, useRef, useState, type ComponentType, type DragEvent, type ReactNode } from 'react'\nimport { Extension, nodePasteRule, type AnyExtension, type EditorOptions } from '@tiptap/core'\nimport { Editor, type JSONContent } from '@tiptap/react'\nimport { REFUSAL_REASONS, refusalCause, refusalReason, tooLarge, uploadRefusal } from '@estiva-app/conversation'\nimport { IconLock, IconPaperclip, IconSquareRounded, IconX } from '@tabler/icons-react'\nimport { AttachedCard } from './AttachedCard'\nimport { AttachmentCard } from './AttachmentCard'\nimport { ReferenceNode, type ReferenceViewProps } from './BlockNodes'\nimport { Button } from './Button'\nimport { Card } from './Card'\nimport { cn } from './cn'\nimport { BoxFrame, ComposeKeys, COMPOSE_EDITOR_CLASSES, isEmptyDoc as isEmpty, SendBox } from './commentBoxFrame'\nimport {\n CaptionedReference,\n PersonMention,\n ReferenceTrigger,\n SlashCommands,\n UrgentPersonMention,\n formatSection,\n typeTrigger,\n type CodeFormat,\n type MentionPerson,\n type ReferenceSection,\n type SlashCommand,\n type SlashSection,\n} from './ComposerTriggers'\nimport { FieldLine } from './Field'\nimport { FilePicker } from './FilePicker'\nimport { IconButton } from './IconButton'\nimport { inTheBox } from './linked'\nimport { LinkedIcon } from './LinkParts'\nimport { linkedKindOfReference } from './LinkPlaces'\nimport { BoxKit, LINK_MARK_ATTRIBUTES, PasteOverWords } from './links'\nimport { PastedImages } from './PastedImages'\nimport { KeptSelection } from './SelectionToolbar'\nimport { isSuggestionOpen } from './suggestionPopup'\nimport { ToolbarButton } from './Toolbar'\nimport { caretOnOpen } from './threadCard'\nimport { sendsInLayout } from './conversationScroll'\n\n/**\n * The one box every app writes a comment, a reply and a chat line in, from the\n * approved prototype (`concept/comments-everywhere`, Miky 17 October): the\n * box's one frame (`commentBoxFrame`) with everything each app built around it \u2014 `@`,\n * `!@`, `[` and `/`, the keys, drafts, files, the edit mode, sending and a\n * refused send. An app hands over only its people, its `[` sections, its `/`\n * Insert rows and a send that says whether the relay accepted it.\n *\n * It speaks the editor's document. What that document writes as a message,\n * and the document an edit or a draft opens with, are `@estiva-app/conversation`'s\n * (`composerText`, `composerDocument`, `composerDraft`).\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-writes-and-reacts-with-one-shared-box.md\n */\n\n/**\n * What the relay said about a send, an edit or a reaction. `reason` is the refusal as it came (the relay's words, an\n * `Error`, an HTTP body, or `{ cause }` for an app's own): the box says it in `@estiva-app/conversation`'s plain words\n * (`refusalReason`), the same in every app, never the relay's.\n */\nexport type SendAnswer = { accepted: true } | { accepted: false; reason: unknown }\n\n/** What an upload answered: the app's own record of the file, or why not, as it came; the card says `uploadRefusal`'s line. */\nexport type UploadAnswer = { accepted: true; value: unknown } | { accepted: false; reason: unknown }\n\n/** Where a file in the box is: Send waits for one uploading. */\nexport type BoxFileState = 'uploading' | 'ready' | 'failed'\n\n/** A file in the box. */\nexport interface BoxFile {\n id: string\n name: string\n size?: number\n contentType?: string\n state: BoxFileState\n /** Why it failed, under its name. */\n note?: string\n /** What `upload` answered for it: the app's own record (an `imeta`, a URL). */\n value?: unknown\n}\n\n/**\n * Why a send was refused. \"This message was deleted\" is an edit's, a reaction's (Decided, ONE-4) and a reply's, whose\n * message may have gone while it was written (Decided, ONE-10, 9 November); a new top-level message refused the same\n * way is one you can no longer write here.\n */\nfunction sendRefusal(reason: unknown, reply: boolean): string {\n const cause = refusalCause(reason)\n return REFUSAL_REASONS[cause === 'gone' && !reply ? 'no-access' : cause]\n}\n\n/** A draft, in the box's terms \u2014 `@estiva-app/conversation`'s `composerDraft` is one. */\nexport interface CommentBoxDraft {\n read(): JSONContent | undefined\n write(body: JSONContent): void\n clear(): void\n}\n\n/** Editing something already sent: the same box, with Cancel and Save. */\nexport interface CommentBoxEdit {\n /** What it says now, as `composerDocument` opens it. */\n body: JSONContent\n /** Its files, which can be taken off; with `upload` and `writesFiles`, more can be added by `/` \u2192 Upload, a paste or a drop. A box reopened after a refusal is given the files that save carried. */\n files?: BoxFile[]\n /**\n * The app's `onSave` writes the files it is handed, so a file can be added while editing (with `upload`).\n * Opt-in, so an app whose save drops them never offers it: a file added and silently lost.\n */\n writesFiles?: boolean\n /** Why the relay refused this edit, as it came, when the app reopens a box it closed at once: said under it as it opens. Read as the box opens, so a reopen is a new box (a new `key`). */\n refused?: unknown\n onCancel: () => void\n /** Save; the box holds the words until the answer, and a refusal is said under it. */\n onSave: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => Promise<SendAnswer>\n}\n\n/**\n * What a draft shows under the box, as the app reads it from the box's\n * document \u2014 `@estiva-app/conversation`'s `boxReadOf`, which reads it as the\n * message will be sent (why:\n * https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-on-words-counts-toward-the-card.md).\n */\nexport interface BoxUnderRead {\n /** The one card, before any \u2715: what it names, and the app's own view of it, drawn as it draws a sent one. */\n card?: { value: string; view: ReactNode }\n /** The live parts, drawn as the app draws them under a sent message. An edit carries none, so the edit box shows none. */\n parts?: readonly { key: string; view: ReactNode }[]\n /** Everything the draft names. A \u2715 is forgotten once what it took off is no longer named, so a link put back gets its card again. */\n names: readonly string[]\n}\n\n/** What the box shows under itself while something is written. */\nexport interface BoxUnder {\n /** Read on every change, and once more as it is sent. */\n read: (body: JSONContent) => BoxUnderRead\n /** Called with a listener; call it when `read` would answer differently (what a link names came back). */\n changed?: (listener: () => void) => () => void\n}\n\n/** What was under the box as it was sent or saved. */\nexport interface BoxSentUnder {\n /** The card still shown, by what it names: absent when there was none, or \u2715 took it off. */\n card?: string\n}\n\n/** What a new comment will be on, above the box (Leaf's \"On \u201Cwords\u201D\", Ship's block: each hand-made until 3 November). */\nexport interface BoxAbout {\n /** The line: what the posted card's `about` will show. */\n view: ReactNode\n /** \u2715 beside it, in the app's words: \"Comment on the whole document instead\", \"Remove\". Absent, no \u2715. */\n remove?: { label: string; onRemove: () => void }\n}\n\nexport interface CommentBoxProps {\n /** Who `@` and `!@` offer. */\n people: readonly MentionPerson[]\n /** What `[` lists for what was typed, already in the app's order. Absent, `[` opens nothing. */\n references?: (query: string) => readonly ReferenceSection[]\n /** Called with a listener while `[` is open; call it when `references` would answer differently (a search landed). */\n referencesChanged?: (listener: () => void) => () => void\n /**\n * A `[` row's and chip's 16px icon from what it points at. Absent, the kit's icon for the kind its address names\n * (`LinkedIcon`), and a neutral square for an address that names none.\n */\n referenceIcon?: (uri: string | null) => ReactNode | undefined\n /** The app's own `/` Insert rows, after the shared Format section: {@link commentBoxRows} and its own. */\n insert?: readonly SlashCommand[]\n /** `/` \u2192 Code: a mark inside the line, or a block. */\n code?: CodeFormat\n /** Send what is written, with the files that are ready and the card still shown; resolves with the relay's answer. */\n send: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => Promise<SendAnswer>\n /** The card and parts in the box while something is written, with the files, \u2715 on the card. Absent, there are none. */\n under?: BoxUnder\n /**\n * What the new comment will be on, in a strip above the box on the inset fill: the `about` the posted card will carry\n * (a `QuotedLine`, the app's words for a block), with \u2715 in it, in the app's words, to drop it. Not drawn on an edit or\n * a closed box.\n */\n about?: BoxAbout\n /**\n * The app shows a send before the relay answers: the box empties at once,\n * and a refusal puts the words back. Otherwise the box holds the words, shut,\n * until the answer.\n */\n showsAtOnce?: boolean\n /**\n * The box answers a message, which can be deleted while you write: a send refused because it went says \"this message\n * was deleted, or you can no longer write here\". A box that starts something new says \"you can no longer write here\".\n */\n reply?: boolean\n /** The editor's accessible name: what the box is for. */\n label: string\n /** Said in the empty box. */\n placeholder: ReactNode\n /** Keeps what is written when the box goes away. Give the box a React `key` per destination. */\n draft?: CommentBoxDraft\n /** Editing something already sent. */\n edit?: CommentBoxEdit\n /** Offers the paperclip, `/` \u2192 File, a pasted picture and a dropped file: uploads one, and answers. */\n upload?: (file: File) => Promise<UploadAnswer>\n /** The file picker's `accept`. */\n accept?: string\n /** The box cannot write here (an archived file, signed out): a line saying why takes its place. Closed from the start, it builds no editor. */\n closed?: { reason: ReactNode }\n /**\n * How a link the box holds is drawn \u2014 a pasted one, a pasted `nostr:` address, and a `[` pick alike: the app's view\n * of the kit's `LinkChip`, told it is being edited (no preview; a click stays in the draft). Absent, a `nostr:`\n * reference reads as its URI and a `[` pick as its caption.\n */\n referenceView?: ComponentType<ReferenceViewProps>\n /** The app's own extra editor extensions: link chips, highlights. */\n extensions?: readonly AnyExtension[]\n autoFocus?: boolean\n /** Called with what was sent once it went out: at once when `showsAtOnce`, else on the answer. */\n onSent?: (body: JSONContent, files: BoxFile[], under: BoxSentUnder) => void\n /** Called when a send shown at once was refused, so the app takes it back. */\n onRefused?: () => void\n /** The bar down the text's left edge shows while this holds, besides while an urgent mention is in the box: the app's own marks (a highlight). */\n marked?: (editor: Editor) => boolean\n /** Called with the box's editor once it is drawn, and with `null` as it goes: an app's launcher inserts into the box last used. */\n onEditor?: (editor: Editor | null) => void\n className?: string\n}\n\nconst ATTACH_EVENT = 'commentbox:attach'\n\n/** Asks the box around the editor for a file, as the paperclip does. */\nconst askForFile = (editor: Editor) => editor.view.dom.dispatchEvent(new CustomEvent(ATTACH_EVENT, { bubbles: true }))\n\n/**\n * The `/` Insert rows the kit offers. Pass the ones an app can perform, in\n * its order, with its own after them; an edit drops Upload and Urgent itself.\n * `file` is the Upload row, named as in a document's `/`.\n */\nexport const commentBoxRows: Readonly<Record<'file' | 'mention' | 'urgent' | 'reference', SlashCommand>> = {\n file: { key: 'insert-file', row: { label: 'Upload' }, keywords: ['attach', 'file', 'picture'], run: askForFile },\n mention: { key: 'insert-mention', row: { label: 'Mention', shortcut: '@' }, keywords: ['@', 'Mention a person'], run: typeTrigger('@') },\n urgent: { key: 'insert-urgent', row: { label: 'Urgent', shortcut: '!@' }, keywords: ['!@', 'Urgent mention'], run: typeTrigger('!@') },\n reference: { key: 'insert-reference', row: { label: 'Reference', shortcut: '[' }, keywords: ['[', 'Reference'], run: typeTrigger('[') },\n}\n\n/** Ctrl/Cmd+Enter sends as Enter does; Escape cancels an edit (an open list, or the selection strip, takes Escape first). */\nconst BoxKeys = Extension.create<{ onEscape: (editor: Editor) => boolean }>({\n name: 'commentBoxKeys',\n addOptions() {\n return { onEscape: () => false }\n },\n addKeyboardShortcuts() {\n return {\n 'Mod-Enter': ({ editor }) => (editor.storage as unknown as { composeKeys?: { send: (() => boolean) | null } }).composeKeys?.send?.() ?? false,\n // Open now, with no grace: the first Escape closes a list, the next is a deliberate cancel (suggestionPopup).\n Escape: ({ editor }) => (isSuggestionOpen() ? false : this.options.onEscape(editor as unknown as Editor)),\n }\n },\n})\n\n/** What `removed` still holds of what the draft names; the same set when nothing was forgotten. */\nconst stillNamed = (removed: ReadonlySet<string>, names: readonly string[]): ReadonlySet<string> =>\n [...removed].every((value) => names.includes(value)) ? removed : new Set([...removed].filter((value) => names.includes(value)))\n\nconst SQUARE = <IconSquareRounded size={16} stroke={1.5} className=\"text-text-secondary\" />\nconst SMALL_SQUARE = <IconSquareRounded size={14} stroke={1.5} />\n\n/** The kit's icon for the kind a `nostr:` address names, at a row's or a chip's size; nothing for one that names none. */\nfunction kindIconOf(uri: string | null, size: 14 | 16): ReactNode | undefined {\n const kind = uri ? linkedKindOfReference(uri) : undefined\n return kind ? <LinkedIcon kind={kind} size={size} /> : undefined\n}\n\n/**\n * A `nostr:` address pasted into the box becomes its link at once, as a pasted app URL does (Katerina, 30 Oct): a file\n * (`naddr`) or a message (`nevent`, `note`), drawn by the app's `referenceView`. A person's (`npub`) stays the text\n * it is; `@` names a person.\n */\nconst PastedAddresses = Extension.create({\n name: 'pastedAddresses',\n addPasteRules() {\n const type = this.editor.schema.nodes.reference\n if (!type) return []\n return [\n nodePasteRule({\n find: /nostr:(?:naddr1|nevent1|note1)[023456789acdefghjklmnpqrstuvwxyz]+/g,\n type,\n getAttributes: (match) => ({ uri: match[0] }),\n }),\n ]\n },\n})\n\n/** What the box's editor reads as it runs: the box holding it now, swapped in when a box takes a spare. */\ninterface BoxLive {\n edit?: CommentBoxEdit\n people: readonly MentionPerson[]\n references?: CommentBoxProps['references']\n referencesChanged?: CommentBoxProps['referencesChanged']\n referenceIcon?: CommentBoxProps['referenceIcon']\n /** Takes pasted pictures; false when the box takes no files. */\n attach: (files: File[]) => boolean\n}\n\n/** One editor's link to the box holding it: the live props, and the `/` sections the box refills every render. */\ninterface BoxHold {\n current: BoxLive\n sections: SlashSection[]\n}\n\n/** What an app adds to every box's editor: a spare is built only for these. */\ninterface BoxApp {\n extensions: readonly AnyExtension[]\n referenceView: ComponentType<ReferenceViewProps> | null\n}\n\nconst NO_EXTENSIONS: readonly AnyExtension[] = []\nconst sameApp = (a: BoxApp, b: BoxApp) =>\n a.referenceView === b.referenceView && a.extensions.length === b.extensions.length && a.extensions.every((one, i) => one === b.extensions[i])\n\nfunction boxExtensions(hold: BoxHold, app: BoxApp): AnyExtension[] {\n // The app's icons when it gives them; the kit's for the kind each address names otherwise (Katerina, 30 Oct).\n const own = (uri: string | null, size: 14 | 16) => (hold.current.referenceIcon ? hold.current.referenceIcon(uri) : kindIconOf(uri, size))\n const iconFor = (uri: string | null) => own(uri, 16)\n return [\n // A link drawn as one, as in a document: it read as plain words in the box before (Katerina, 29 Oct).\n BoxKit.configure({ link: { openOnClick: false, HTMLAttributes: LINK_MARK_ATTRIBUTES } }),\n PasteOverWords,\n KeptSelection,\n ComposeKeys,\n BoxKeys.configure({\n onEscape: (ed) => {\n const editing = hold.current.edit\n if (!editing) return false\n // Words selected: the strip is over them, and the first Escape closes it, leaving the caret at their end.\n // The next is the deliberate cancel, as with an open list (Katerina, 21 Oct: the edit box gets the strip).\n const { selection } = ed.state\n if (!selection.empty) {\n ed.commands.setTextSelection(selection.to)\n return true\n }\n editing.onCancel()\n return true\n },\n }),\n PersonMention.configure({ people: () => hold.current.people }),\n // An edit makes nobody urgent (CON-24): `!@` opens no list there, as `/` offers no Urgent.\n UrgentPersonMention.extend({\n addOptions() {\n const parent = this.parent!()\n return { ...parent, suggestion: { ...parent.suggestion, allow: () => !hold.current.edit } }\n },\n }).configure({ people: () => hold.current.people }),\n // A `[` pick draws as the app draws every other link in the box (Katerina, 30 Oct: one chip look in every box).\n CaptionedReference.configure({ icon: SMALL_SQUARE, iconFor: (uri) => own(uri, 14), view: app.referenceView }),\n ReferenceTrigger.configure({\n items: () => [],\n sections: (query) => hold.current.references?.(query) ?? [],\n subscribe: (listener) => hold.current.referencesChanged?.(listener) ?? (() => {}),\n ariaLabel: 'References',\n sectionLabel: 'References',\n icon: SQUARE,\n iconFor,\n }),\n SlashCommands.configure({ sections: hold.sections }),\n ReferenceNode.configure({ view: app.referenceView }),\n ...(app.referenceView ? [PastedAddresses] : []),\n PastedImages.configure({ onImages: (files: File[]) => hold.current.attach(files) }),\n ...app.extensions,\n ]\n}\n\ninterface Held {\n editor: Editor\n hold: BoxHold\n destroyAt?: ReturnType<typeof setTimeout>\n}\n\nfunction buildBox(app: BoxApp, options: Partial<EditorOptions>): Held {\n const hold: BoxHold = { current: { people: [], attach: () => false }, sections: [] }\n return { editor: new Editor({ ...options, extensions: boxExtensions(hold, app) }), hold }\n}\n\n/*\n A box's editor, built ahead, as Peek's composer has been since 4ef41d41:\n building one (schema, commands, view) is the longest single step in drawing\n a box. One is built while the page is idle for the app `keepCommentBoxWarm`\n names, and the next empty box with those extensions takes it and builds the\n next; any other box builds its own on the spot.\n*/\nlet warmApp: BoxApp | null = null\nlet spare: Held | null = null\nlet sparing = false\n\nfunction scheduleSpare() {\n if (!warmApp || spare || sparing || typeof window === 'undefined' || !window.requestIdleCallback) return\n sparing = true\n window.requestIdleCallback(() => {\n sparing = false\n // No autofocus: it would fire on the detached spare. The box that takes it focuses it.\n if (warmApp && !spare) spare = buildBox(warmApp, { autofocus: false })\n })\n}\n\n/** Keeps an editor built ahead for the next empty box given these `extensions` and `referenceView`, so it opens at once. */\nexport function keepCommentBoxWarm(app: { extensions?: readonly AnyExtension[]; referenceView?: ComponentType<ReferenceViewProps> } = {}): void {\n const next = { extensions: app.extensions ?? NO_EXTENSIONS, referenceView: app.referenceView ?? null }\n if (warmApp && sameApp(warmApp, next)) return\n warmApp = next\n spare?.editor.destroy()\n spare = null\n scheduleSpare()\n}\n\n/** `useEditor` with no deps, taking a spare when one fits: built once, given the latest `editorProps`, destroyed when the box goes. */\nfunction useBoxEditor(app: BoxApp, content: JSONContent | undefined, options: Pick<EditorOptions, 'editable' | 'editorProps'>): Held {\n const args = useRef({ app, content, options })\n args.current = { app, content, options }\n const [held, setHeld] = useState(() => {\n const fits = !content && spare && !spare.editor.isDestroyed && warmApp && sameApp(warmApp, app)\n const taken = fits ? spare : null\n if (taken) {\n spare = null\n taken.editor.setOptions(options)\n }\n const one = taken ?? buildBox(app, { ...options, content })\n // A render thrown away never mounts: what it built goes with it. Later than React lets a transition run (5 s).\n one.destroyAt = setTimeout(() => one.editor.destroy(), 10_000)\n scheduleSpare()\n return one\n })\n // Mounted, it is this box's until it unmounts \u2014 and not remounted at once, as in StrictMode.\n useLayoutEffect(() => {\n clearTimeout(held.destroyAt)\n /*\n Shown again after React kept its state but ran this cleanup (a Suspense boundary\n that suspended again, an <Activity> that hid it): the editor went, so build one\n from what the box would open with now \u2014 its draft holds what was typed.\n */\n if (held.editor.isDestroyed) {\n const { app: now, content: opening, options: current } = args.current\n setHeld(buildBox(now, { ...current, content: opening }))\n return\n }\n return () => {\n held.destroyAt = setTimeout(() => held.editor.destroy(), 1)\n }\n }, [held])\n // The attributes are what changes after it is built: the label.\n const props = useRef(options.editorProps)\n props.current = options.editorProps\n const attributes = JSON.stringify(options.editorProps.attributes ?? {})\n useEffect(() => {\n if (!held.editor.isDestroyed) held.editor.setOptions({ editorProps: props.current })\n }, [held, attributes])\n return held\n}\n\n/** Whether the document holds an urgent mention: the box draws its bar while one is in it. */\nconst holdsUrgent = (editor: Editor): boolean => {\n let found = false\n editor.state.doc.descendants((node) => {\n if (node.type.name === 'urgentMention') found = true\n return !found\n })\n return found\n}\n\nlet fileCount = 0\n\n/** The line that takes the box's place where nothing can be written: a lock and why. */\nfunction ClosedLine({ reason, className }: { reason: ReactNode; className?: string }) {\n return (\n <Card fill=\"inset\" className={cn('flex items-start gap-3 px-4 py-3', className)}>\n <IconLock size={16} stroke={1.5} className=\"mt-0.5 shrink-0 text-text-muted\" aria-hidden />\n <p className=\"text-body-2 text-text-secondary\">{reason}</p>\n </Card>\n )\n}\n\nexport function CommentBox(props: CommentBoxProps) {\n const { closed, className } = props\n /*\n Closed from the start (an archived file, signed out), nothing is written here: the line alone, and no editor is\n built to say it. Once opened, the box keeps its editor through a close, so what was written comes back with it.\n */\n const [built, setBuilt] = useState(!closed)\n if (!closed && !built) setBuilt(true)\n if (closed && !built) return <ClosedLine reason={closed.reason} className={className} />\n return <OpenCommentBox {...props} />\n}\n\nfunction OpenCommentBox({\n people,\n references,\n referencesChanged,\n referenceIcon,\n insert = [],\n code = 'block',\n send,\n under,\n about,\n showsAtOnce = false,\n label,\n placeholder,\n draft,\n edit,\n upload,\n accept,\n closed,\n referenceView,\n extensions = NO_EXTENSIONS,\n autoFocus,\n onSent,\n onRefused,\n marked,\n onEditor,\n className,\n reply = false,\n}: CommentBoxProps) {\n const [files, setFiles] = useState<BoxFile[]>(edit?.files ?? [])\n const [sending, setSending] = useState(false)\n // The plain reason, never the relay's words (ONE-4).\n const [refused, setRefused] = useState<string | null>(edit?.refused ? refusalReason(edit.refused) : null)\n // What shows under the box, and what \u2715 took off.\n const [reading, setReading] = useState<BoxUnderRead | undefined>(undefined)\n const [removed, setRemoved] = useState<ReadonlySet<string>>(() => new Set())\n const picker = useRef<HTMLInputElement>(null)\n const root = useRef<HTMLDivElement>(null)\n // The latest props, for callbacks made once.\n const latest = useRef({ edit, upload, draft, under })\n latest.current = { edit, upload, draft, under }\n const save = useRef<() => boolean>(() => false)\n\n const attachFiles = useCallback((picked: File[]): boolean => {\n const uploadOne = latest.current.upload\n if (!uploadOne || (latest.current.edit && !latest.current.edit.writesFiles)) return false\n for (const file of picked) {\n fileCount += 1\n const id = `file-${fileCount}`\n const card = { id, name: file.name, size: file.size, contentType: file.type }\n // Over the server's limit for its type: said on its card before anything uploads (Miky, 4 Nov).\n const over = tooLarge(file)\n if (over) {\n setFiles((all) => [...all, { ...card, state: 'failed', note: over }])\n continue\n }\n setFiles((all) => [...all, { ...card, state: 'uploading' }])\n const failed = (reason: unknown) => setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'failed', note: uploadRefusal(reason, file) } : f)))\n uploadOne(file).then((answer) => {\n if (!answer.accepted) return failed(answer.reason)\n setFiles((all) => all.map((f) => (f.id === id ? { ...f, state: 'ready', value: answer.value } : f)))\n }, failed)\n }\n return true\n }, [])\n\n // An edit can add a file, in every app (Miky, 26 Oct, PEEKM-4) whose save writes it, but makes nobody urgent (CON-24); no upload, no File.\n const takesFiles = !!upload && (!edit || !!edit.writesFiles)\n const rows = insert.filter((c) => !(!takesFiles && c.key === commentBoxRows.file.key) && !(edit && c.key === commentBoxRows.urgent.key))\n const { editor, hold } = useBoxEditor({ extensions, referenceView: referenceView ?? null }, edit?.body ?? draft?.read(), {\n editable: !closed,\n editorProps: { attributes: { class: COMPOSE_EDITOR_CLASSES, role: 'textbox', 'aria-multiline': 'true', 'aria-label': label } },\n })\n // The editor's callbacks are made once, with the editor: they read this box's latest props through its hold.\n hold.current = { edit, people, references, referencesChanged, referenceIcon, attach: attachFiles }\n // `/` reads its sections each time it opens, from this one array: refilled every render, so a row that\n // comes or goes with `upload`, `insert` or `code` after the box opened is offered as it is now.\n hold.sections.splice(0, hold.sections.length, formatSection(code), ...(rows.length > 0 ? [{ label: 'Insert', commands: rows }] : []))\n\n // The bar down the text's left edge, while an urgent mention or the app's own mark is in the box.\n const [marking, setMarking] = useState(false)\n const markedBy = useRef(marked)\n markedBy.current = marked\n // Before paint: an edit or a draft opening with an urgent mention draws its bar in its first frame.\n useLayoutEffect(() => {\n const read = () => setMarking(holdsUrgent(editor) || !!markedBy.current?.(editor))\n read()\n editor.on('update', read)\n return () => {\n editor.off('update', read)\n }\n }, [editor])\n\n const handOut = useRef(onEditor)\n handOut.current = onEditor\n useEffect(() => {\n handOut.current?.(editor)\n return () => handOut.current?.(null)\n }, [editor])\n\n // Whether the edit's words are gone: Save waits for something to save, and a refusal says the changes are in the box only while they are.\n const editing = !!edit\n const [wordless, setWordless] = useState(() => editing && !!editor && isEmpty(editor))\n useEffect(() => {\n if (!editor || !editing) return\n const read = () => setWordless(isEmpty(editor))\n read()\n editor.on('update', read)\n return () => {\n editor.off('update', read)\n }\n }, [editor, editing])\n\n // Drafts: every change is kept, and an empty box is no draft.\n useEffect(() => {\n if (!editor || edit) return\n const keep = () => {\n const kept = latest.current.draft\n if (!kept) return\n if (isEmpty(editor)) kept.clear()\n else kept.write(editor.getJSON())\n }\n editor.on('update', keep)\n return () => {\n editor.off('update', keep)\n }\n }, [editor, edit])\n\n // What shows under the box, read on every change and whenever the app's answers change.\n const reads = !!under\n useEffect(() => {\n if (!editor || !reads) {\n setReading(undefined)\n return\n }\n const read = () => {\n const now = latest.current.under?.read(editor.getJSON())\n setReading(now)\n setRemoved((was) => stillNamed(was, now?.names ?? []))\n }\n read()\n editor.on('update', read)\n const unsubscribe = latest.current.under?.changed?.(read)\n return () => {\n editor.off('update', read)\n unsubscribe?.()\n }\n }, [editor, reads])\n\n // What goes with a send or a save: read from what is sent, minus what \u2715 took off.\n const underOf = useCallback(\n (body: JSONContent): BoxSentUnder => {\n const card = latest.current.under?.read(body).card?.value\n return card && !removed.has(card) ? { card } : {}\n },\n [removed],\n )\n\n useEffect(() => {\n editor?.setEditable(!closed && !sending)\n }, [editor, closed, sending])\n\n useEffect(() => {\n if (!editor || !(autoFocus || edit)) return\n const frame = requestAnimationFrame(() => editor.commands.focus('end'))\n return () => cancelAnimationFrame(frame)\n // Once, as the box opens.\n }, [editor])\n\n // At a thread's foot in a ConversationLayout: the caret, each time the thread opens, with no scroll to it.\n const caret = useContext(caretOnOpen)\n useEffect(() => {\n if (!editor || !caret) return\n const frame = requestAnimationFrame(() => editor.commands.focus('end', { scrollIntoView: false }))\n return () => cancelAnimationFrame(frame)\n }, [editor, caret])\n\n // `/` \u2192 File asks for a file the way the paperclip does.\n useEffect(() => {\n const box = root.current\n if (!box || !takesFiles) return\n const ask = () => picker.current?.click()\n box.addEventListener(ATTACH_EVENT, ask)\n return () => box.removeEventListener(ATTACH_EVENT, ask)\n }, [takesFiles])\n\n const uploading = files.some((f) => f.state === 'uploading')\n // A file that did not upload holds Send until its \u2715 takes it off, so it is never sent without it unnoticed.\n const failed = files.filter((f) => f.state === 'failed').length\n const ready = files.some((f) => f.state === 'ready')\n\n // In a ConversationLayout's box: the reader's own comment brings the comments down to it as it is drawn.\n const layout = useContext(sendsInLayout)\n const go = useCallback(\n (ed: Editor): boolean => {\n layout?.sending()\n const body = ed.getJSON()\n const sent = files.filter((f) => f.state === 'ready')\n const sentUnder = underOf(body)\n setRefused(null)\n const answered = (answer: Promise<SendAnswer>) => answer.catch((reason: unknown): SendAnswer => ({ accepted: false, reason }))\n if (showsAtOnce) {\n // Shown at once: the box empties now (the send box clears it); a refusal puts the words back above anything written since,\n // and what \u2715 took off with them.\n const took = removed\n setFiles((all) => all.filter((f) => f.state !== 'ready'))\n draft?.clear()\n onSent?.(body, sent, sentUnder)\n void answered(send(body, sent, sentUnder)).then((answer) => {\n if (answer.accepted) return\n layout?.refused()\n onRefused?.()\n if (ed.isDestroyed) {\n // The box went away before the answer: the words wait in its draft.\n draft?.write(body)\n return\n }\n if (isEmpty(ed)) ed.commands.setContent(body)\n else ed.commands.insertContentAt(0, body.content ?? [])\n ed.commands.focus('end')\n setRemoved((now) => new Set([...now, ...took]))\n setFiles((all) => [...sent, ...all])\n setRefused(sendRefusal(answer.reason, reply))\n })\n return true\n }\n // Held: the words stay, shut, until the relay answers.\n setSending(true)\n void answered(send(body, sent, sentUnder)).then((answer) => {\n setSending(false)\n if (!answer.accepted) {\n layout?.refused()\n setRefused(sendRefusal(answer.reason, reply))\n return\n }\n if (!ed.isDestroyed) ed.commands.clearContent(true)\n setRemoved(new Set())\n setFiles((all) => all.filter((f) => !sent.includes(f)))\n draft?.clear()\n onSent?.(body, sent, sentUnder)\n })\n return false\n },\n [files, removed, underOf, showsAtOnce, send, draft, onSent, onRefused, layout, reply],\n )\n\n // An edit holding nothing, no words and no file, cannot be saved: Save is off, and nothing is said (Miky, 4 Nov). One\n // emptied of its words that keeps a file is saved, in every app.\n const holdsNothing = !!edit && wordless && files.length === 0\n save.current = () => {\n if (!editor || !edit || sending || uploading || failed > 0 || (isEmpty(editor) && files.length === 0)) return true\n setRefused(null)\n setSending(true)\n const body = editor.getJSON()\n void edit\n .onSave(body, files, underOf(body))\n .catch((reason: unknown): SendAnswer => ({ accepted: false, reason }))\n .then((answer) => {\n setSending(false)\n if (!answer.accepted) setRefused(refusalReason(answer.reason))\n })\n return true\n }\n\n // Enter and Ctrl/Cmd+Enter save an edit; the send box wires them itself.\n useEffect(() => {\n if (!editor || !edit) return\n const storage = (editor.storage as unknown as { composeKeys?: { send: (() => boolean) | null } }).composeKeys\n if (!storage) return\n storage.send = () => save.current()\n return () => {\n storage.send = null\n }\n }, [editor, edit])\n\n if (closed) return <ClosedLine reason={closed.reason} className={className} />\n\n const fileCards =\n files.length > 0 ? (\n <>\n {files.map((f) => (\n <AttachmentCard\n key={f.id}\n pending\n name={f.name}\n size={f.size}\n contentType={f.contentType}\n state={f.state}\n note={f.note}\n onRemove={() => setFiles((all) => all.filter((one) => one !== f))}\n />\n ))}\n </>\n ) : undefined\n\n // In the box, under the text with the files (Katerina, 29 Oct: \"the file's \u2715 and inside the box\"): the files, then\n // the card with its \u2715 and the live parts on a line of their own (none in an edit, which carries none). On the files'\n // fill, the card's values as words until it is sent (`inTheBox`).\n const card = reading?.card && !removed.has(reading.card.value) ? reading.card : undefined\n const parts = edit ? [] : (reading?.parts ?? [])\n const attached =\n card || parts.length > 0 ? (\n <>\n {fileCards}\n <inTheBox.Provider value>\n {/* min-w-0: a card with a long title would otherwise be as wide as its title, past the box's edge (29 Oct). */}\n <div data-box-under className=\"flex min-w-0 basis-full flex-col gap-2\">\n {card && <AttachedCard onRemove={() => setRemoved((was) => new Set([...was, card.value]))}>{card.view}</AttachedCard>}\n {parts.map((part) => (\n <Fragment key={part.key}>{part.view}</Fragment>\n ))}\n </div>\n </inTheBox.Provider>\n </>\n ) : (\n fileCards\n )\n\n const refusedLine = refused && (\n <FieldLine tone=\"error\">\n {edit ? `Not saved: ${refused}.${holdsNothing ? '' : ' Your changes are still in the box.'}` : `Not sent: ${refused}. Your text is back in the box.`}\n </FieldLine>\n )\n\n const onDrop = (event: DragEvent<HTMLDivElement>) => {\n const dropped = Array.from(event.dataTransfer?.files ?? [])\n if (dropped.length === 0 || !takesFiles) return\n event.preventDefault()\n attachFiles(dropped)\n }\n\n const fileLines = (\n <>\n {uploading && !sending && <FieldLine>Uploading\u2026 {edit ? 'Save' : 'Send'} waits for the file.</FieldLine>}\n {failed > 0 && !uploading && !sending && (\n <FieldLine>\n {failed === 1 ? 'Remove the file that did not upload' : 'Remove the files that did not upload'} to {edit ? 'save' : 'send'}.\n </FieldLine>\n )}\n </>\n )\n\n if (edit) {\n // No paperclip: the edit box shows only its keys (Decided 2026-10-17); a file comes by `/` \u2192 Upload, a paste or a drop.\n return (\n <div ref={root} className={cn('flex flex-col gap-1', className)} onDragOver={takesFiles ? (e) => e.preventDefault() : undefined} onDrop={onDrop}>\n <BoxFrame\n editor={editor}\n marked={marking}\n // The same strip as the send box: writing and editing work the same way (Katerina, 21 Oct).\n selection={{ link: true }}\n ring={false}\n attachments={attached}\n className={cn(sending && '[&_.ProseMirror]:text-text-muted')}\n footer={\n // No keys written under the edit box: Cancel and Save say it (Katerina, 1 November).\n <div className=\"flex items-center justify-end gap-2\">\n <div className=\"flex shrink-0 items-center gap-2\">\n <Button variant=\"outlined\" size=\"small\" onClick={edit.onCancel}>\n Cancel\n </Button>\n <Button variant=\"primary\" size=\"small\" disabled={uploading || failed > 0 || sending || holdsNothing} onClick={() => save.current()}>\n Save\n </Button>\n </div>\n </div>\n }\n />\n {takesFiles && <FilePicker ref={picker} multiple accept={accept} onPick={attachFiles} />}\n {sending && <FieldLine>Saving\u2026</FieldLine>}\n {fileLines}\n {refusedLine}\n </div>\n )\n }\n\n return (\n <div ref={root} className={cn('flex flex-col gap-1', className)} onDragOver={upload ? (e) => e.preventDefault() : undefined} onDrop={onDrop}>\n {about && (\n // The whole strip, its \u2715 in it, on the inset fill the closed box's line has (Katerina, 3 November: B); 8px above\n // the box with the column's 4px. 36px tall with or without \u2715, so the box does not move when an app offers none.\n <Card data-box-about fill=\"inset\" className=\"mb-1 flex min-h-9 items-center gap-2 py-1 pl-3 pr-1\">\n <div className=\"min-w-0 flex-1\">{about.view}</div>\n {about.remove && (\n <IconButton tooltip={about.remove.label} aria-label={about.remove.label} onClick={about.remove.onRemove}>\n <IconX size={16} stroke={1.5} />\n </IconButton>\n )}\n </Card>\n )}\n <SendBox\n editor={editor}\n onSend={go}\n placeholder={placeholder}\n tools={\n upload ? (\n <ToolbarButton tooltip=\"Attach a file\" aria-label=\"Attach a file\" disabled={sending} onClick={() => picker.current?.click()}>\n <IconPaperclip size={16} stroke={1.5} />\n </ToolbarButton>\n ) : undefined\n }\n attachments={attached}\n ready={ready}\n marked={marking}\n holding={uploading || failed > 0 || sending}\n selection={{ link: true }}\n className={cn(sending && '[&_[data-composer-editor]]:text-text-muted')}\n />\n {upload && <FilePicker ref={picker} multiple accept={accept} onPick={attachFiles} />}\n {sending && <FieldLine>Sending\u2026</FieldLine>}\n {fileLines}\n {refusedLine}\n </div>\n )\n}\n", "/**\n * refusals, the one set of words every app says when a send, an edit, a\n * reaction or a file is refused (ONE-4).\n *\n * A refusal comes from the relay (`invalid: \u2026`, `restricted: \u2026`, an HTTP body),\n * from Estiva ID, from the builders' own checks (`content is N bytes, max M`),\n * from the network, or from the app itself. Whatever it was, a person reads\n * one plain reason for its cause, the same in Peek, Ship and Leaf, and never\n * the relay's words: those go to the console. The comment box and the cards\n * put the reason in their sentence (\"Not sent: <reason>. Your text is back in\n * the box.\"), so a reason is lower case and ends with no full stop.\n *\n * An app with a cause of its own hands `{ cause }` rather than a sentence, so\n * its words are these too. A file's own words (`uploadRefusal`) are a whole\n * line on its card, and `tooLarge` stops a file over the relay's limit before\n * it uploads (Miky, 4 Nov: the server's limits, checked in every app first).\n */\n\n/** Why something was refused, as far as a person needs to know. */\nexport type RefusalCause =\n | 'too-long'\n | 'gone'\n | 'no-access'\n | 'archived'\n | 'busy'\n | 'clock'\n | 'signed-out'\n | 'unknown'\n\n/**\n * Each cause's reason, put in a sentence by the box or the card. `gone` is\n * what the relay says for an edit or a reaction on a message that was deleted\n * or that you can no longer write beside: it does not say which.\n */\nexport const REFUSAL_REASONS: Readonly<Record<RefusalCause, string>> = {\n 'too-long': 'it is too long',\n gone: 'this message was deleted, or you can no longer write here',\n 'no-access': 'you can no longer write here',\n archived: 'this team is archived',\n busy: 'too many at once, try again in a moment',\n clock: 'your computer\u2019s clock is wrong; set it and try again',\n 'signed-out': 'you are signed out; sign in again',\n unknown: 'something went wrong, try again',\n}\n\n/** The text a refusal carries: a string, an `Error`'s message, or `{ error }` / `{ message }` / `{ reason }`, one JSON body deep. */\nfunction textOf(reason: unknown): string {\n if (reason == null) return ''\n if (typeof reason === 'string') {\n const json = reason.trim()\n if (json.startsWith('{')) {\n try {\n return textOf(JSON.parse(json)) || reason\n } catch {\n return reason\n }\n }\n return reason\n }\n if (reason instanceof Error) return textOf(reason.message)\n if (typeof reason === 'object') {\n const r = reason as Record<string, unknown>\n for (const key of ['error', 'message', 'reason']) {\n const value = r[key]\n if (typeof value === 'string') return textOf(value)\n if (value && typeof value === 'object') return textOf(value)\n }\n }\n return String(reason)\n}\n\nconst CAUSES = new Set<string>(Object.keys(REFUSAL_REASONS))\n\n/*\n In order: the first that matches is the cause. Scope and identity before\n `restricted:`, which also prefixes \"insufficient scope\". Each reason above\n maps back to its own cause, so a reason passed on twice stays the same.\n\n Words, because the relay sends no reason code yet (SPEC: \"until then a\n refusal is its sentence alone\"). When the TEA issue \"When the server says\n no, every app knows why\" adds them, `refusalCause` reads the code first and\n these rules stay only for a refusal that carries none.\n why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-refusal-starts-with-a-reason-code-every-app-reads.md\n*/\nconst RULES: readonly [RegExp, RefusalCause][] = [\n [/content (is \\d+ bytes, max|exceeds maximum size)|too long/i, 'too-long'],\n [/rate-limited|quota|too many|too busy|relay is busy|admission|\\b429\\b|concurrency/i, 'busy'],\n [/timestamp too far|clock/i, 'clock'],\n [/auth-required|insufficient scope|does not match authenticated|signed out|sign in|\\b401\\b|token_rejected|session_expired/i, 'signed-out'],\n [/archived/i, 'archived'],\n [/(target|parent) (event )?not found|not (editable|deletable) by you|was deleted|no longer on this page/i, 'gone'],\n [/^(restricted|blocked):|not a (channel |relay )?member|only members|no longer (post|write)|banned|timed out until|writes are fenced|\\b403\\b/i, 'no-access'],\n]\n\n/** What a refusal comes to; `{ cause }` is taken as it is. */\nexport function refusalCause(reason: unknown): RefusalCause {\n if (reason && typeof reason === 'object' && 'cause' in reason) {\n const cause = (reason as { cause: unknown }).cause\n if (typeof cause === 'string' && CAUSES.has(cause)) return cause as RefusalCause\n }\n const text = textOf(reason)\n for (const [rule, cause] of RULES) if (rule.test(text)) return cause\n return 'unknown'\n}\n\n/** The plain reason for any refusal, to say after \"Not sent:\", \"Not saved:\" or \"Not reacted:\". */\nexport function refusalReason(reason: unknown): string {\n return REFUSAL_REASONS[refusalCause(reason)]\n}\n\n/** Why a file did not upload, as far as a person needs to know. */\nexport type UploadCause = 'too-large' | 'type' | 'unreadable' | 'busy' | 'signed-out' | 'no-access' | 'unknown'\n\nconst MB = 1024 * 1024\n\n/**\n * The relay's size limits (buzz `BUZZ_MAX_*_BYTES`, read back on production on\n * 4 Nov): a GIF 10 MB, another picture 50 MB, anything else 100 MB, since\n * Cloudflare refuses a larger body before the relay sees it (a video's 500 MB\n * is never reached). Cloudflare's 100 MB is taken as decimal, the lower\n * reading, so nothing that passes here is turned away there.\n */\nexport const UPLOAD_LIMITS = { gif: 10 * MB, image: 50 * MB, other: 100_000_000 } as const\n\n/** The most a file of this type may be, in bytes. */\nexport function uploadLimit(type: string | undefined): number {\n const t = (type ?? '').toLowerCase()\n if (t === 'image/gif') return UPLOAD_LIMITS.gif\n if (t.startsWith('image/')) return UPLOAD_LIMITS.image\n return UPLOAD_LIMITS.other\n}\n\n// Whole MB either way: 10,485,760 bytes and 100,000,000 bytes both say what the limit is called.\nconst tooLargeLine = (bytes: number) => `Too large: the most is ${bytes % MB === 0 ? bytes / MB : Math.round(bytes / 1e6)} MB`\n\n/** The line for a file over its limit, said before it uploads; undefined when it fits. */\nexport function tooLarge(file: { size: number; type?: string }): string | undefined {\n const limit = uploadLimit(file.type)\n return file.size > limit ? tooLargeLine(limit) : undefined\n}\n\nconst UPLOAD_LINES: Readonly<Record<Exclude<UploadCause, 'too-large'>, string>> = {\n type: 'This type of file can\u2019t be added',\n unreadable: 'This file could not be read',\n busy: 'Too many at once, try again in a moment',\n 'signed-out': 'Sign in again',\n 'no-access': 'You can no longer add files here',\n unknown: 'Could not upload, try again',\n}\n\n/**\n * The line on a file's card when its upload was refused: from protocol's\n * `upload failed: <status> <body>`, any other error, or `{ cause }`. A 413\n * names the limit the relay gave, or the type's own when Cloudflare answered.\n */\nexport function uploadRefusal(reason: unknown, file?: { type?: string }): string {\n if (reason && typeof reason === 'object' && 'cause' in reason) {\n const cause = (reason as { cause: unknown }).cause\n if (cause === 'too-large') return tooLargeLine(uploadLimit(file?.type))\n if (typeof cause === 'string' && Object.hasOwn(UPLOAD_LINES, cause)) return UPLOAD_LINES[cause as keyof typeof UPLOAD_LINES]\n }\n const raw = reason instanceof Error ? reason.message : typeof reason === 'string' ? reason : textOf(reason)\n const status = Number(/upload failed:\\s*(\\d{3})/i.exec(raw)?.[1] ?? 0)\n const said = textOf(raw.replace(/^.*?upload failed:\\s*\\d{3}\\s*/is, ''))\n if (status === 413 || /file too large/i.test(said)) {\n const max = Number(/max (\\d+)\\)?/i.exec(said)?.[1] ?? 0)\n if (/dimensions/i.test(said)) return UPLOAD_LINES.unreadable\n return tooLargeLine(max || uploadLimit(file?.type))\n }\n if (status === 415 || /content type|unsupported container/i.test(said)) return UPLOAD_LINES.type\n if (status === 422 || /metadata|invalid image|duration|resolution/i.test(said)) return UPLOAD_LINES.unreadable\n if (status === 429 || /rate limit|concurrency/i.test(said)) return UPLOAD_LINES.busy\n if (status === 401 || /authentication failed|signed out/i.test(said)) return UPLOAD_LINES['signed-out']\n if (status === 403) return UPLOAD_LINES['no-access']\n return UPLOAD_LINES.unknown\n}\n", "import type { ComponentType, MouseEvent } from 'react'\nimport { Extension, InputRule, Node, type Editor } from '@tiptap/core'\nimport { DOMSerializer, type Node as ProseMirrorNode, type Slice } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state'\nimport { Mapping, ReplaceAroundStep } from '@tiptap/pm/transform'\nimport { Decoration, DecorationSet, type EditorView, type NodeView } from '@tiptap/pm/view'\nimport { NodeViewWrapper, ReactNodeViewRenderer, ReactRenderer, type ReactNodeViewProps } from '@tiptap/react'\nimport { Checkbox, type CheckboxProps } from './Checkbox'\nimport { calloutLook } from './RichText'\nimport { placeOf, type LinkPlace } from './LinkPlaces'\nimport { referenceMenuClick } from './ReferenceMenu'\nimport { isSuggestionOpen } from './suggestionPopup'\n\n/*\n * The four nodes an editor of a block document needs that a stock schema does\n * not have (SPEC \u00A713.3) \u2014 moved here from Ship's `editorSchema.tsx` (RIC-14,\n * SHI-2) when Peek became the second editor of the same documents (MAN-9).\n *\n * They are one half of a pair. The other half is `@estiva-app/protocol`'s\n * `toEditorDocument` / `fromEditorDocument`, which turn a stored document into\n * the JSON these nodes read and back: the node names (`unknownBlock`,\n * `reference`, `attachment`) and the `blockId` attribute are that translation's,\n * and must not drift from it. This package does not import protocol, as\n * `RichText` does not: the translation hands over everything a view draws.\n *\n * Everything else a document can contain is already a ProseMirror node of the\n * same name \u2014 StarterKit's and TableKit's \u2014 which is why this file is short.\n */\n\n/**\n * The block types \u00A713.3 puts an id on, as the editor's node names \u2014\n * protocol's `EDITOR_BLOCK_TYPES`, less `unknownBlock`, which declares its own.\n */\nconst BLOCK_TYPES = [\n 'paragraph',\n 'heading',\n 'bulletList',\n 'orderedList',\n 'listItem',\n 'blockquote',\n 'codeBlock',\n 'horizontalRule',\n // A table and everything inside it (UIG-18): a row or a cell whose id was\n // re-minted on each save would detach any comment anchored to it.\n 'table',\n 'tableRow',\n 'tableHeader',\n 'tableCell',\n // Without this an attachment's id is re-minted on every save, and every\n // comment anchored to it stops resolving.\n 'attachment',\n]\nconst BLOCK_TYPE_SET = new Set(BLOCK_TYPES)\n\n/** protocol's `newBlockId`: six random bytes as hex. */\nfunction newBlockId(): string {\n return Array.from(crypto.getRandomValues(new Uint8Array(6)), (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\n/** Whether anything typed or inserted is inside \u2014 protocol's `holdsText`. An empty paragraph is not; a lone line break is. */\nfunction holdsText(node: ProseMirrorNode): boolean {\n let found = false\n node.descendants((child) => {\n if (found) return false\n if ((child.isText && child.text !== '') || child.type.name === 'hardBreak' || child.type.name === 'reference') found = true\n return !found\n })\n return found\n}\n\ninterface Claim {\n pos: number\n node: ProseMirrorNode\n /** An unknown block: the translation hands its source back untouched, so re-minting it here would be undone on save. */\n fixed: boolean\n}\n\n/** Every block that claims an id, by id, in document order. */\nfunction claimsIn(doc: ProseMirrorNode): Map<string, Claim[]> {\n const claims = new Map<string, Claim[]>()\n doc.descendants((node, pos, parent) => {\n const fixed = node.type.name === 'unknownBlock'\n if (!fixed && !BLOCK_TYPE_SET.has(node.type.name)) return\n // A list inside a list item is no block (MAN-13): an id it arrived with is\n // cleared, never a claim that could take a real block's.\n if (parent?.type.name === 'listItem' && LISTS.has(node.type.name)) return\n const id = node.attrs.blockId\n if (typeof id !== 'string' || id === '') return\n const copies = claims.get(id)\n if (copies) copies.push({ pos, node, fixed })\n else claims.set(id, [{ pos, node, fixed }])\n })\n return claims\n}\n\n/**\n * The copy the block that was there before carried on into: where the start\n * of its content landed. Enter at the very start pushes that content into the\n * lower half; a split anywhere else leaves it in the upper; a pasted copy,\n * above or below, never moves it out of the original.\n */\nfunction carriedOn(copies: Claim[], before: Claim, mapping: Mapping): Claim | undefined {\n if (before.node.isLeaf) {\n const at = mapping.map(before.pos, 1)\n return copies.find((c) => c.pos === at)\n }\n const at = mapping.map(textStart(before), 1)\n return copies.find((c) => c.pos < at && at < c.pos + c.node.nodeSize)\n}\n\n/** The start of a block's text, inside the paragraph a list item or quote wraps it in. */\nfunction textStart({ pos, node }: { pos: number; node: ProseMirrorNode }): number {\n let start = pos + 1\n if (!node.isTextblock) {\n let found = false\n node.descendants((child, at) => {\n if (found) return false\n if (child.isTextblock) {\n start = pos + 1 + at + 1\n found = true\n }\n return !found\n })\n }\n return start\n}\n\n/**\n * Where a block claims an id another block keeps \u2014 see {@link BlockId}. An\n * unknown block always keeps its id; otherwise the copy the original carried\n * on into, and failing that protocol's rule: the first that holds text, or\n * the first.\n */\nfunction repeatedBlockIds(doc: ProseMirrorNode, before: ProseMirrorNode, mapping: Mapping): number[] {\n const claims = claimsIn(doc)\n let previous: Map<string, Claim[]> | undefined\n const losers: number[] = []\n for (const [id, copies] of claims) {\n if (copies.length < 2) continue\n previous ??= claimsIn(before)\n const original = previous.get(id)?.[0]\n const owner =\n copies.find((c) => c.fixed) ??\n (original && carriedOn(copies, original, mapping)) ??\n copies.find((c) => holdsText(c.node)) ??\n copies[0]\n for (const copy of copies) if (copy !== owner && !copy.fixed) losers.push(copy.pos)\n }\n return losers\n}\n\n/**\n * The blocks a save turns into blocks \u2014 exactly what protocol's\n * `blockFromEditor` walks \u2014 so a list, a table and its rows and cells are\n * walked into, and a list item or a quote is not: the save flattens their\n * paragraph wrappers into inline runs, so an id there would be dropped.\n */\nconst BLOCK_CONTAINERS = new Set(['bulletList', 'orderedList', 'table', 'tableRow', 'tableHeader', 'tableCell'])\n\n/** The wrappers the save flattens: their paragraphs become inline runs of theirs. */\nconst FLATTENED = new Set(['listItem', 'blockquote'])\n\n/**\n * The lists Tab puts inside a list item (MAN-13). \u00A713.3 keeps a list flat and\n * marks an item's depth, so the save walks into such a list for its items and\n * writes no block for the list itself: its items get ids, it gets none.\n */\nconst LISTS = new Set(['bulletList', 'orderedList'])\n\n/** The lists inside a list item, with where each starts. */\nfunction innerLists(item: ProseMirrorNode, pos: number): { pos: number; node: ProseMirrorNode }[] {\n const out: { pos: number; node: ProseMirrorNode }[] = []\n item.forEach((child, offset) => {\n if (LISTS.has(child.type.name)) out.push({ pos: pos + 1 + offset, node: child })\n })\n return out\n}\n\nconst idOf = (node: ProseMirrorNode): string | undefined => {\n const id = node.attrs.blockId\n return typeof id === 'string' && id !== '' ? id : undefined\n}\n\n/** Every block the save turns into a block, in document order. */\nfunction addressedBlocks(doc: ProseMirrorNode): { pos: number; node: ProseMirrorNode }[] {\n const out: { pos: number; node: ProseMirrorNode }[] = []\n const visit = (node: ProseMirrorNode, pos: number) => {\n if (!BLOCK_TYPE_SET.has(node.type.name)) return\n out.push({ pos, node })\n if (BLOCK_CONTAINERS.has(node.type.name)) node.forEach((child, offset) => visit(child, pos + 1 + offset))\n if (node.type.name === 'listItem') {\n for (const list of innerLists(node, pos)) list.node.forEach((child, offset) => visit(child, list.pos + 1 + offset))\n }\n }\n doc.forEach((node, offset) => visit(node, offset))\n return out\n}\n\n/** Where a block the save would give an id has none, so it would get a new one on every save. */\nfunction unnamedBlocks(doc: ProseMirrorNode): number[] {\n return addressedBlocks(doc)\n .filter((b) => idOf(b.node) === undefined)\n .map((b) => b.pos)\n}\n\n/**\n * Where a paragraph inside a list item or a quote claims an id, or a list\n * inside a list item does \u2014 both of which the save drops.\n */\nfunction hiddenIds(doc: ProseMirrorNode): number[] {\n const out: number[] = []\n doc.descendants((node, pos) => {\n if (!FLATTENED.has(node.type.name)) return\n node.forEach((child, offset) => {\n const inner = child.isTextblock || (node.type.name === 'listItem' && LISTS.has(child.type.name))\n if (inner && idOf(child) !== undefined) out.push(pos + 1 + offset)\n })\n })\n return out\n}\n\n/**\n * The id each block a wrap or a lift brought in takes over \u2014 see\n * {@link BlockId}. An id the save addressed before the change and does not\n * now goes to the innermost new block its text was carried into: the quote or\n * the list item around a paragraph, or the paragraph lifted out of one.\n * A block the change deleted hands nothing on. What it asks is whether the\n * block's own opening survived, the token left of its text, not its first\n * character: the `/` menu and a typed `> ` or `- ` delete what was typed at\n * the very start of the text in the same change as the wrap.\n */\nfunction handedOver(doc: ProseMirrorNode, before: ProseMirrorNode, mapping: Mapping, unnamed: number[]): Map<number, string> {\n const out = new Map<number, string>()\n if (unnamed.length === 0) return out\n const now = new Set(addressedBlocks(doc).map((b) => idOf(b.node)))\n // By where their text starts, and of a list and its item around the same text, the item first.\n const gone = addressedBlocks(before)\n .filter((b) => !b.node.isLeaf && idOf(b.node) !== undefined && !now.has(idOf(b.node)))\n .map((b) => ({ ...b, start: textStart(b) }))\n .sort((a, b) => a.start - b.start || b.pos - a.pos)\n for (const old of gone) {\n const id = idOf(old.node)!\n const { pos: at, deleted } = mapping.mapResult(old.start, -1)\n if (deleted) continue\n let inner: number | undefined\n for (const pos of unnamed) {\n if (out.has(pos)) continue\n if (pos < at && at < pos + doc.nodeAt(pos)!.nodeSize && (inner === undefined || pos > inner)) inner = pos\n }\n if (inner !== undefined) {\n out.set(inner, id)\n now.add(id)\n }\n }\n return out\n}\n\n/**\n * Whether a change could have made a repeat or a block without an id: only a\n * step that brings in blocks can, or one that wraps or lifts them \u2014 lifting\n * the paragraph out of a quote or a one-item list brings in nothing, yet\n * leaves a block the save addresses with the wrapper's missing id. Typing,\n * deleting and marks do neither, so most keystrokes skip the walk.\n */\nfunction bringsInBlocks(transactions: readonly Transaction[]): boolean {\n return transactions.some((tr) =>\n tr.steps.some((step) => {\n if (step instanceof ReplaceAroundStep) return true\n const slice = (step as { slice?: Slice }).slice\n let blocks = false\n slice?.content.forEach((node) => {\n if (node.isBlock) blocks = true\n })\n return blocks\n }),\n )\n}\n\n/**\n * `id` on every block, carried as the `blockId` attribute.\n *\n * A global attribute rather than one per node type, because \u00A713.3 puts an id\n * on **every** block and a type that quietly lacked one would mint a fresh id\n * on every save \u2014 detaching each anchored comment on it (RFC 0.4 \u00A76) with\n * nothing on screen to say so.\n *\n * Rendered as `data-block-id`, which is what `RichText` already emits, so the\n * reading and the editing surface address a block the same way.\n *\n * **A split gives the new half its own id, the moment it happens** (MAN-10).\n * ProseMirror copies a split node's attrs to both halves, so Enter leaves two\n * blocks claiming one id. Enter at the very start of a paragraph puts the\n * copy *above* it \u2014 and once something is typed there, nothing at save time\n * can tell which half was the original, so protocol's `fromEditorDocument`\n * gave the id, and every comment anchored to it, to the new line. Settled\n * here instead, in the same transaction, where the change itself says which\n * copy the original carried on into \u2014 so a copy pasted above a block does\n * not take its id either. The others get fresh ids. `fromEditorDocument`\n * keeps its own rule (the copy that holds text) as the backstop for an\n * editor without this extension; where the change says nothing, this falls\n * back to that rule too.\n *\n * **A block that arrives without an id gets one, the moment it arrives**\n * (MAN-11): a paste, a `/` menu insert, the empty paragraph a new editor\n * starts with and the one StarterKit keeps at the end. `fromEditorDocument`\n * mints an id for such a block on every save and the editor never sees it, so\n * each save gave it a different one \u2014 a blur with no edit published again, and\n * a comment anchored to it in between was detached. The editor's first\n * document is filled in when it is created, outside the undo history and\n * without an update, so opening a description is not an edit.\n *\n * **A wrap or a lift hands the id on** (MAN-12). Turning a paragraph into a\n * quote or a list wraps it, and ProseMirror leaves its attrs on the paragraph\n * inside \u2014 where the save flattens it and drops the id, so the quote or list\n * item was published under a new one and every comment anchored to the\n * paragraph was detached. The quote or the list item takes the paragraph's id\n * instead, and the list around it a fresh one; lifting the text back out hands\n * the id to the paragraph again. The paragraph inside keeps no id, as one\n * loaded from a stored document has none.\n */\nexport const BlockId = Extension.create({\n name: 'blockId',\n onCreate() {\n const { state, view } = this.editor\n const unnamed = unnamedBlocks(state.doc)\n if (unnamed.length === 0) return\n const tr = state.tr\n for (const pos of unnamed) tr.setNodeAttribute(pos, 'blockId', newBlockId())\n view.dispatch(tr.setMeta('addToHistory', false).setMeta('preventUpdate', true))\n },\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('blockIdSplit'),\n appendTransaction: (transactions, old, state) => {\n if (!bringsInBlocks(transactions)) return null\n const mapping = new Mapping()\n for (const tr of transactions) mapping.appendMapping(tr.mapping)\n const unnamed = unnamedBlocks(state.doc)\n const handed = handedOver(state.doc, old.doc, mapping, unnamed)\n const ids = new Map<number, string | null>()\n for (const pos of repeatedBlockIds(state.doc, old.doc, mapping)) ids.set(pos, newBlockId())\n for (const pos of unnamed) ids.set(pos, handed.get(pos) ?? newBlockId())\n for (const pos of hiddenIds(state.doc)) ids.set(pos, null)\n if (ids.size === 0) return null\n const tr = state.tr\n for (const [pos, id] of ids) tr.setNodeAttribute(pos, 'blockId', id)\n return tr\n },\n }),\n ]\n },\n addGlobalAttributes() {\n return [\n {\n types: BLOCK_TYPES,\n attributes: {\n blockId: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute('data-block-id'),\n renderHTML: (attributes: Record<string, unknown>) =>\n attributes.blockId ? { 'data-block-id': String(attributes.blockId) } : {},\n },\n },\n },\n ]\n },\n})\n\n/** An http(s) URL, or null. */\nconst webUrl = (raw: string | null): string | null => (raw && /^https?:\\/\\/\\S+$/i.test(raw) ? raw : null)\n\n/** What a reference's view is handed: the `nostr:` URI it stands for, and the URL a URL chip was written as. */\nexport interface ReferenceViewProps {\n uri: string\n href?: string\n /**\n * Where it sits, so how it draws: `chip` in a sentence, `row` alone on its\n * line, `card` in the row's place (`LinkPlaces`, \u00A713.3). Always `chip` in an\n * editor without `LinkPlaces`.\n */\n place?: LinkPlace\n /**\n * Being edited, so a chip or a row shows no hover preview: a click on it opens its menu, or does nothing in a box\n * being written in. In a box, always while it can be written in; in a document (`editingLine`), only while the\n * caret is on its line, so a link elsewhere on the page previews on hover.\n */\n editing?: boolean\n}\n\nexport interface ReferenceNodeOptions {\n /**\n * Draws the reference as the thing it points at \u2014 the app's own chip, which\n * knows how to resolve it. Without one, the URI is drawn as text.\n */\n view: ComponentType<ReferenceViewProps> | null\n /**\n * A link counts as being edited (`editing`) only while the caret is on its\n * line: its textblock, between the hard breaks either side, while the editor\n * has focus. `DocumentEditor` sets it, so a page that is always editable\n * still previews the links its writer is not working on (Katerina, 30 Oct).\n * Off, every link is being edited while the editor is editable, as in a\n * message's box.\n */\n editingLine: boolean\n}\n\n/** A card's own controls: a press on one stays theirs, see `keepCardPresses`. */\nconst CARD_CONTROLS = 'button, [role=\"combobox\"]'\n\n/** What a click in a card goes on to: its links (the title, the count) and its controls. Its empty space opens the menu. */\nconst CARD_CLICKS = `a[href], input, select, ${CARD_CONTROLS}`\n\n/**\n * ProseMirror sees a press before React does and takes the caret into the\n * text, which closed a card's picker before it opened (Leaf's fix, moved here\n * so every app has it). It leaves alone a press whose default is prevented.\n */\nfunction keepCardPresses(element: HTMLElement | null): (() => void) | undefined {\n if (!element) return undefined\n const keep = (event: globalThis.MouseEvent) => {\n if (event.target instanceof Element && event.target.closest(CARD_CONTROLS)) event.preventDefault()\n }\n element.addEventListener('mousedown', keep)\n return () => element.removeEventListener('mousedown', keep)\n}\n\n/** Every reference on the caret's line: the textblock it is in, between the hard breaks either side of it. */\nfunction caretLineReferences(state: EditorState): { pos: number; size: number }[] {\n const { $head } = state.selection\n const block = $head.parent\n if (!block.isTextblock) return []\n const start = $head.start()\n const at = $head.parentOffset\n const lines: { from: number; to: number; references: { pos: number; size: number }[] }[] = [{ from: 0, to: block.content.size, references: [] }]\n block.forEach((child, offset) => {\n const line = lines[lines.length - 1]\n if (child.type.name === 'hardBreak') {\n line.to = offset\n lines.push({ from: offset + child.nodeSize, to: block.content.size, references: [] })\n } else if (child.type.name === 'reference') line.references.push({ pos: start + offset, size: child.nodeSize })\n })\n return lines.find((line) => at >= line.from && at <= line.to)?.references ?? []\n}\n\n/** Whether a node view's decorations put it on the caret's line. */\nfunction onCaretLine(decorations: readonly Decoration[] | undefined): boolean {\n return (decorations ?? []).some((decoration) => (decoration.spec as { caretLine?: boolean }).caretLine === true)\n}\n\n/**\n * A `nostr:` reference, drawn as the thing it points at \u2014 SPEC \u00A713.1.\n *\n * An **atom**: it has no editable interior, because its text is the URI and\n * nobody edits half a `naddr`. Selecting it selects the whole reference, which\n * is also how deleting one works. `marks` carries the run's other marks, so a\n * bold reference comes back bold.\n *\n * `embed` is the card its writer chose \u2014 `detailed`, drawn in the row's place\n * when the reference is alone on its line, or null for its row (SPEC \u00A713.3, \"A\n * reference's card\"; older writers wrote `compact`, which draws the row) \u2014 and\n * `extra` every key of the mark this version does not know. Both are declared\n * so that ProseMirror keeps them: an undeclared attribute is dropped when the\n * node is made, and the card with it. With `LinkPlaces`, the view is told where\n * the reference sits (`place`) and draws its chip, row or card.\n *\n * `href` makes it a **URL chip**: an app URL that reads as the chip of what it\n * names, and is that URL on the wire (\u00A713.3). `uri` is what it names, filled in\n * by `LinkChips` once the app has resolved it; until then it draws as the URL.\n */\nexport const ReferenceNode = Node.create<ReferenceNodeOptions>({\n name: 'reference',\n group: 'inline',\n inline: true,\n atom: true,\n selectable: true,\n draggable: false,\n addOptions() {\n return { view: null, editingLine: false }\n },\n addProseMirrorPlugins() {\n if (!this.options.editingLine) return []\n const editor = this.editor\n return [\n new Plugin({\n key: new PluginKey('referenceCaretLine'),\n props: {\n // Read on every update, a focus and a blur included (Tiptap sends a transaction for each), so it follows the caret.\n decorations: (state) =>\n editor.isFocused && editor.isEditable\n ? DecorationSet.create(\n state.doc,\n caretLineReferences(state).map(({ pos, size }) => Decoration.node(pos, pos + size, {}, { caretLine: true })),\n )\n : null,\n },\n }),\n ]\n },\n addAttributes() {\n return {\n // A pasted URL chip keeps only its URL: what it names is the editor's to resolve (`LinkChips`), never\n // the clipboard's, which could show one object while saving another URL (security review).\n uri: { default: '', parseHTML: (element: HTMLElement) => (webUrl(element.getAttribute('data-href')) ? '' : (element.getAttribute('data-reference') ?? '')) },\n marks: { default: [] as string[] },\n embed: { default: null as string | null, parseHTML: (element: HTMLElement) => element.getAttribute('data-embed') },\n extra: { default: null as Record<string, unknown> | null, parseHTML: () => null },\n // An http(s) URL only: `LinkChips` makes no other, and a pasted `javascript:` must not reach a saved link.\n href: { default: null as string | null, parseHTML: (element: HTMLElement) => webUrl(element.getAttribute('data-href')) },\n }\n },\n parseHTML() {\n return [{ tag: 'span[data-reference]' }]\n },\n renderHTML({ node }) {\n // A copy to the clipboard as HTML, and the whole drawing when no view is given.\n // The card goes along, so a paste keeps it; a URL chip copies as its URL.\n const embed = typeof node.attrs.embed === 'string' ? { 'data-embed': node.attrs.embed } : {}\n // Only a web address: the document's `href` is whatever its writer saved, and this attribute is read back by a paste.\n const web = webUrl(typeof node.attrs.href === 'string' ? node.attrs.href : null)\n const href = web ? { 'data-href': web } : {}\n return ['span', { 'data-reference': String(node.attrs.uri), ...embed, ...href }, String(node.attrs.href || node.attrs.uri)]\n },\n renderText({ node }) {\n return String(node.attrs.href || node.attrs.uri)\n },\n addNodeView() {\n const View = this.options.view\n if (!View) return null\n const { editingLine } = this.options\n return ReactNodeViewRenderer(({ node, editor, getPos, decorations }: ReactNodeViewProps) => {\n const uri = String(node.attrs.uri ?? '')\n const href = typeof node.attrs.href === 'string' && node.attrs.href ? node.attrs.href : undefined\n const place = placeOf(decorations)\n const editing = editor.isEditable && (!editingLine || onCaretLine(decorations))\n return (\n <NodeViewWrapper\n as=\"span\"\n // A row or a card is the whole line.\n className={place === 'chip' ? 'inline' : 'block w-full'}\n // A card keeps its pickers while the text is edited too (Katerina, 30 Oct): a press on one is not the text's.\n ref={place === 'card' ? keepCardPresses : undefined}\n // While editing, a click opens the chip's menu (`ReferenceMenu`) rather than following the chip.\n onClickCapture={(event: MouseEvent) => {\n // A click in something the view portals out \u2014 a picker's list, a hover card \u2014 reaches here through React's\n // tree, not the page's: it is that thing's, not a click on the link.\n const pos = getPos()\n if (typeof pos !== 'number') return\n // (`Node` here is Tiptap's; a click's target is an Element.)\n const own = editor.view.nodeDOM(pos)\n if (!(event.target instanceof Element) || !own || !own.contains(event.target)) return\n // A card's own links and controls take the click, while editing too: its title opens the file, its count the\n // conversation, its status and owner change it. Only its empty space opens the menu (Katerina, 30 Oct).\n if (place === 'card' && event.target.closest(CARD_CLICKS)) return\n if (referenceMenuClick(editor, pos)) {\n event.preventDefault()\n event.stopPropagation()\n return\n }\n // Being written with no menu to open \u2014 a message's box: a click on the link does not leave the draft\n // (Katerina, 30 Oct: a chip in the box does not follow a click).\n if (!editingLine && editor.isEditable && event.target.closest('a[href]')) event.preventDefault()\n }}\n >\n {/* A URL chip not resolved yet reads as the URL it was written as. */}\n {uri ? <View uri={uri} {...(href ? { href } : {})} place={place} editing={editing} /> : <span>{href}</span>}\n </NodeViewWrapper>\n )\n }, {\n // Words typed beside a link leave its node as it was, and Tiptap then skips the redraw; its place has changed (code\n // review), or the caret came onto its line or left it.\n update: ({ oldNode, newNode, oldDecorations, newDecorations, updateProps }) => {\n const moved = placeOf(oldDecorations) !== placeOf(newDecorations) || onCaretLine(oldDecorations) !== onCaretLine(newDecorations)\n if (oldNode !== newNode || moved) updateProps()\n return true\n },\n })\n },\n})\n\n/**\n * A block this editor has no design for, kept whole.\n *\n * \u00A713.3: a reader MUST render an unknown block's inline text and MUST NOT drop\n * it silently. **An editor is the dangerous case** \u2014 ProseMirror discards a\n * node its schema does not know, and the save after that would delete somebody\n * else's block with no error anywhere on the way. So the block's own JSON\n * rides in `source`, and protocol's `fromEditorDocument` hands it back\n * untouched; `text` is its inline text, worked out by `toEditorDocument`.\n *\n * Not editable, deliberately: an affordance that lets a person change\n * something they cannot see is worse than one that says the content is there\n * and belongs to another surface.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/the-block-editor-kit-lives-in-protocol-and-ui.md\n */\nexport const UnknownBlock = Node.create({\n name: 'unknownBlock',\n group: 'block',\n atom: true,\n selectable: true,\n addAttributes() {\n return {\n blockId: { default: null },\n source: { default: null },\n text: { default: '' },\n }\n },\n parseHTML() {\n return [{ tag: 'div[data-unknown-block]' }]\n },\n renderHTML({ node }) {\n return ['div', { 'data-unknown-block': String(node.attrs.blockId ?? '') }, String(node.attrs.text ?? '')]\n },\n addNodeView() {\n return ReactNodeViewRenderer(UnknownBlockView)\n },\n})\n\nfunction UnknownBlockView({ node }: ReactNodeViewProps) {\n const source = node.attrs.source as { id?: string; type?: string } | null\n const text = String(node.attrs.text ?? '')\n return (\n <NodeViewWrapper\n data-block-id={source?.id}\n data-block-type={source?.type}\n className=\"rounded-md border border-border-default bg-bg-inset px-2 py-1 text-text-secondary\"\n >\n {text || `A ${source?.type ?? 'block'} this app cannot edit yet.`}\n </NodeViewWrapper>\n )\n}\n\n/** What an attachment's view is handed: the block's `imeta` fields. */\nexport interface AttachmentViewProps {\n attrs: Record<string, unknown>\n}\n\nexport interface AttachmentNodeOptions {\n /** Draws the file \u2014 the app's own attachment card. Without one, its name is drawn as text. */\n view: ComponentType<AttachmentViewProps> | null\n}\n\n/**\n * A file placed in a document \u2014 SPEC \u00A713.3's `attachment` block (SHI-2).\n *\n * An atom: the file is the block, there is nothing inside it to edit, and a\n * caret that could sit \"inside\" an image is a way to produce documents no\n * reader has a rule for. Selectable and deletable, so removing one is Backspace\n * like anything else.\n *\n * Its attributes are the `imeta` fields exactly, because that is what \u00A713.3\n * specifies. Each is declared, and that is not boilerplate: ProseMirror **drops\n * an attribute its schema does not name**, so an undeclared `thumb` would\n * survive the editor and vanish on save \u2014 the silent deletion `UnknownBlock`\n * exists to prevent.\n */\nexport const AttachmentNode = Node.create<AttachmentNodeOptions>({\n name: 'attachment',\n group: 'block',\n atom: true,\n selectable: true,\n draggable: false,\n addOptions() {\n return { view: null }\n },\n addAttributes() {\n return {\n url: { default: '' },\n m: { default: '' },\n x: { default: '' },\n size: { default: 0 },\n dim: { default: null },\n thumb: { default: null },\n alt: { default: null },\n filename: { default: null },\n }\n },\n parseHTML() {\n return [{ tag: 'div[data-attachment-block]' }]\n },\n renderHTML({ node }) {\n // A copy to the clipboard, and the whole drawing when no view is given.\n return ['div', { 'data-attachment-block': String(node.attrs.x ?? '') }, String(node.attrs.filename ?? 'attachment')]\n },\n addNodeView() {\n const View = this.options.view\n if (!View) return null\n return ReactNodeViewRenderer(({ node }: ReactNodeViewProps) => (\n <NodeViewWrapper className=\"my-2\">\n <View attrs={node.attrs} />\n </NodeViewWrapper>\n ))\n },\n})\n\nconst TICK = 'checklistTick'\n\n/**\n * Whether a change is a click on a checklist item's box. The click does not\n * focus the editor, so no blur follows it: an editor that saves on blur saves\n * a tick straight away instead (RIC-19, Miky 2026-10-13: one click ticks).\n */\nexport function isChecklistTick(transaction: Transaction): boolean {\n return transaction.getMeta(TICK) === true\n}\n\n/** A list or quote command by name: StarterKit's declare them, and this package builds without StarterKit. */\ntype Chain = ReturnType<Editor['chain']>\nfunction named(chain: Chain, command: string, ...args: unknown[]): Chain {\n const own = (chain as unknown as Record<string, ((...a: unknown[]) => Chain) | undefined>)[command]\n return own ? own(...args) : chain\n}\n\n/** The list item the caret's paragraph is the first line of, if it is. */\nfunction itemAtCaret(state: EditorState): { node: ProseMirrorNode; pos: number } | null {\n const { $from } = state.selection\n if ($from.depth < 2) return null\n const item = $from.node(-1)\n if (item.type.name !== 'listItem' || $from.index(-1) !== 0) return null\n return { node: item, pos: $from.before(-1) }\n}\n\nconst sameAttrs = (a: ProseMirrorNode, b: ProseMirrorNode) =>\n Object.keys({ ...a.attrs, ...b.attrs }).every((key) => a.attrs[key] === b.attrs[key])\n\n/**\n * A list item, drawn with a box before it when it is a checklist item. The box\n * is the package's `Checkbox`, as `RichText` draws it, and the item's own\n * text and inner lists follow it in a `div`. Any change to the item's\n * attributes draws it again, which is what a tick is.\n *\n * The box is named by the item's words, and follows them as they are typed.\n * Whether it ticks follows the editor's `editable`, read again on every\n * update \u2014 `setEditable` sends one \u2014 not only when the item was drawn\n * (Katerina, review of #170). Not editable, it is a picture, and the box around\n * it says done or not to a screen reader, as `RichText`'s does.\n */\nfunction listItemView(editor: Editor, node: ProseMirrorNode, view: EditorView, getPos: () => number | undefined): NodeView {\n const toDOM = node.type.spec.toDOM\n const { dom, contentDOM } = toDOM ? DOMSerializer.renderSpec(document, toDOM(node)) : { dom: document.createElement('li'), contentDOM: undefined }\n const checked = node.attrs.checked\n if (typeof checked !== 'boolean') return { dom, contentDOM: contentDOM ?? dom, update: (next) => next.type === node.type && sameAttrs(next, node) }\n\n const li = dom as HTMLElement\n const box = document.createElement('span')\n box.contentEditable = 'false'\n box.setAttribute('data-checklist-box', '')\n const body = document.createElement('div')\n li.replaceChildren(box, body)\n const tick = (next: boolean) => {\n const pos = getPos()\n if (pos === undefined || !view.editable) return\n view.dispatch(view.state.tr.setNodeAttribute(pos, 'checked', next).setMeta(TICK, true))\n }\n let words = node.firstChild?.textContent.trim() || 'Item'\n const props = (): CheckboxProps => ({ checked, onChange: view.editable ? tick : undefined, 'aria-label': words })\n const renderer = new ReactRenderer<unknown, CheckboxProps>(Checkbox, { editor, props: props(), as: 'span' })\n box.appendChild(renderer.element)\n // What the box last drew: an update that changes neither leaves it alone, so typing does not draw every box again.\n let drawn = ''\n const sync = () => {\n const now = `${view.editable}:${words}`\n if (now === drawn) return\n drawn = now\n renderer.updateProps(props())\n for (const [name, value] of Object.entries({ role: 'checkbox', 'aria-checked': String(checked), 'aria-readonly': 'true', 'aria-label': words })) {\n if (view.editable) box.removeAttribute(name)\n else box.setAttribute(name, value)\n }\n }\n sync()\n editor.on('update', sync)\n return {\n dom: li,\n contentDOM: body,\n update: (next) => {\n if (next.type !== node.type || !sameAttrs(next, node)) return false\n words = next.firstChild?.textContent.trim() || 'Item'\n sync()\n return true\n },\n stopEvent: (event) => box.contains(event.target as globalThis.Node),\n ignoreMutation: (mutation) => box.contains(mutation.target),\n destroy: () => {\n editor.off('update', sync)\n renderer.destroy()\n },\n }\n}\n\n/**\n * A checklist item \u2014 SPEC \u00A713.3's `checked` on a list item (RIC-19): `true`\n * ticked, `false` not, absent a plain item. Add it beside `BlockId`.\n *\n * - **The box ticks with one click**, where the description is read, and the\n * change says so (`isChecklistTick`), so the app saves it at once.\n * - **`[ ] ` or `[] ` at the start of a line** makes it, `[x] ` ticked; in a\n * list it turns that item into one.\n * - **Enter** starts the next item unticked: a new item never takes the tick\n * of the one it was split from. At the start of an item, the text moves down\n * with its tick and the empty item above is unticked. On an empty item Enter\n * leaves the list, as in any list.\n * - **Backspace** at the start of a checklist item takes its box away first;\n * the next one joins it to the item above, as in any list.\n *\n * An editor without it drops `checked` on save and keeps the item and its text.\n */\nexport const Checklist = Extension.create({\n name: 'checklist',\n // Before the list item's own Enter and Backspace.\n priority: 101,\n addGlobalAttributes() {\n return [\n {\n types: ['listItem'],\n attributes: {\n checked: {\n default: null,\n keepOnSplit: false,\n parseHTML: (element: HTMLElement) => {\n const value = element.getAttribute('data-checked')\n return value === 'true' ? true : value === 'false' ? false : null\n },\n renderHTML: (attributes: Record<string, unknown>) =>\n typeof attributes.checked === 'boolean' ? { 'data-checked': String(attributes.checked) } : {},\n },\n },\n },\n ]\n },\n addInputRules() {\n return [\n new InputRule({\n find: /^\\[([ xX]?)\\]\\s$/,\n handler: ({ state, range, match, chain }) => {\n const checked = match[1].toLowerCase() === 'x'\n const inList = itemAtCaret(state) !== null\n // Without a bullet list to make, the typed text stays as it was typed.\n if (!inList && !(chain() as unknown as Record<string, unknown>).toggleBulletList) return null\n const deleted = chain().deleteRange(range)\n const listed = inList ? deleted : named(deleted, 'toggleBulletList')\n listed.updateAttributes('listItem', { checked }).run()\n },\n }),\n ]\n },\n addKeyboardShortcuts() {\n return {\n Enter: () => {\n // An open `/`, `@` or `[` list picks its row: running first, this split the line under it and left the `/` behind (LFB-3).\n if (isSuggestionOpen()) return false\n const { state } = this.editor\n const item = itemAtCaret(state)\n const { $from, empty } = state.selection\n if (!item || typeof item.node.attrs.checked !== 'boolean') return false\n // Over a selection: the selection goes and the next item is unticked, as for a caret in the text.\n if (!empty) return this.editor.chain().deleteSelection().splitListItem('listItem', { checked: false }).run()\n // An empty item: the list item's own Enter, which leaves the list.\n if ($from.parent.content.size === 0) return false\n if ($from.parentOffset > 0) return this.editor.commands.splitListItem('listItem', { checked: false })\n return this.editor\n .chain()\n .splitListItem('listItem', { checked: item.node.attrs.checked })\n .command(({ tr }) => {\n tr.setNodeAttribute(tr.mapping.map(item.pos), 'checked', false)\n return true\n })\n .run()\n },\n Backspace: () => {\n const { state } = this.editor\n const item = itemAtCaret(state)\n const { $from, empty } = state.selection\n if (!item || !empty || $from.parentOffset > 0 || typeof item.node.attrs.checked !== 'boolean') return false\n this.editor.view.dispatch(state.tr.setNodeAttribute(item.pos, 'checked', null))\n return true\n },\n }\n },\n addProseMirrorPlugins() {\n const editor = this.editor\n return [\n new Plugin({\n key: new PluginKey('checklist'),\n props: { nodeViews: { listItem: (node, view, getPos) => listItemView(editor, node, view, getPos) } },\n }),\n ]\n },\n})\n\n/**\n * A callout \u2014 SPEC \u00A713.3's `tone` on a quote (RIC-19): a quote drawn to stand\n * out, in one of GitHub's alert kinds (`note`, `tip`, `important`, `warning`,\n * `caution`). Its look is `RichText`'s, by `data-tone`; a tone it does not\n * know looks like `note`, and the editor keeps it as written. Add it beside\n * `BlockId`.\n */\nexport const Callout = Extension.create({\n name: 'callout',\n addGlobalAttributes() {\n return [\n {\n types: ['blockquote'],\n attributes: {\n tone: {\n default: null,\n parseHTML: (element: HTMLElement) => element.getAttribute('data-tone'),\n // As `RichText` draws it: the tone as written, and the look it is drawn in.\n renderHTML: (attributes: Record<string, unknown>) =>\n typeof attributes.tone === 'string' ? { 'data-tone': attributes.tone, 'data-callout': calloutLook(attributes.tone) } : {},\n },\n },\n },\n ]\n },\n})\n", "/**\n * Where a reference in a block document sits, and so how it draws \u2014 SPEC \u00A713.3,\n * \"A reference's card\" (C22, C24): its chip in a sentence, its row alone on its\n * line, and its card in the row's place when its writer chose one.\n *\n * The rule is the protocol's (`documentLineDrawOf` in `@estiva-app/protocol`),\n * read here off the editor's own tree so it can be asked on every keystroke\n * without writing the document out. `linkPlaces.test.ts` runs the same\n * documents through both and holds them to one answer.\n *\n * - **Alone on its line**: a top-level paragraph, or a list item's, whose line\n * (up to a hard break) holds this reference and nothing but spaces besides.\n * A heading, a quote, a callout and a table cell are sentences, and so is\n * anything inside a block this rule does not name.\n * - **A marker around it** (bold, italic, code\u2026) makes it a sentence.\n * - **A person or a Folder** alone on its line stays a chip.\n * - **Its card** is `embed` `detailed`; anything else (none, `compact`, a value\n * this version does not know) draws the row.\n *\n * `LinkPlaces` puts each reference's place on a node decoration, which\n * `ReferenceNode`'s view reads and hands to the app's view as `place`.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-on-words-counts-toward-the-card.md\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-lone-links-chip-menu-offers-row-or-card.md\n */\nimport { Extension } from '@tiptap/core'\nimport type { Node as PmNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport { thingKindOf } from './KindIcon'\nimport type { LinkedKind } from './linked'\n\n/** How a reference draws: its chip, its row, or its card in the row's place. */\nexport type LinkPlace = 'chip' | 'row' | 'card'\n\n/** The blocks a line may sit inside and still be alone: a list and its items. */\nconst CONTAINERS = new Set(['bulletList', 'orderedList', 'listItem'])\n\nconst BECH32 = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'\n\n/** The 5-bit words of a bech32 string's data part, checksum dropped, or null. */\nfunction bech32Words(text: string): number[] | null {\n const at = text.lastIndexOf('1')\n if (at < 1 || text.length - at < 7) return null\n const words: number[] = []\n for (const char of text.slice(at + 1, -6)) {\n const word = BECH32.indexOf(char)\n if (word < 0) return null\n words.push(word)\n }\n return words\n}\n\n/** An `naddr`'s kind (TLV type 3), or null when it does not hold one. */\nfunction naddrKind(naddr: string): number | null {\n const words = bech32Words(naddr)\n if (!words) return null\n const bytes: number[] = []\n let acc = 0\n let bits = 0\n for (const word of words) {\n acc = (acc << 5) | word\n bits += 5\n while (bits >= 8) {\n bits -= 8\n bytes.push((acc >> bits) & 0xff)\n }\n }\n for (let i = 0; i + 1 < bytes.length; ) {\n const type = bytes[i]\n const length = bytes[i + 1]\n if (type === 3 && length === 4 && i + 6 <= bytes.length) return ((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i + 4] << 8) | bytes[i + 5]) >>> 0\n i += 2 + length\n }\n return null\n}\n\n/** A Folder's kind. */\nconst FOLDER = 39000\n\n/** A document's kind: it draws a page, as `linkedFrom` draws it. */\nconst PAGE = 30842\n\n/**\n * What a `nostr:` reference names, by the icon it draws, read off its address\n * alone: a message (`nevent`, `note`), a file by its kind (`naddr`, a document\n * a page), or undefined for what has no kind icon (a person, anything else).\n */\nexport function linkedKindOfReference(uri: string): LinkedKind | undefined {\n const bare = uri.toLowerCase().replace(/^nostr:/, '')\n if (bare.startsWith('nevent1') || bare.startsWith('note1')) return 'message'\n if (!bare.startsWith('naddr1')) return undefined\n const kind = naddrKind(bare)\n if (kind === null) return undefined\n return kind === PAGE ? 'page' : thingKindOf(kind)\n}\n\n/**\n * Whether what `uri` names stays a chip alone on its line: a person (`npub`,\n * `nprofile`) or a Folder (an `naddr` of kind 39000).\n */\nexport function staysChip(uri: string): boolean {\n const bare = uri.toLowerCase().replace(/^nostr:/, '')\n if (bare.startsWith('npub1') || bare.startsWith('nprofile1')) return true\n return bare.startsWith('naddr1') && naddrKind(bare) === FOLDER\n}\n\n/** Whether the textblock holding `pos` keeps the line rule: a paragraph at the top, or a list item's. */\nfunction keepsLineRule(doc: PmNode, pos: number): boolean {\n const $pos = doc.resolve(pos)\n if ($pos.parent.type.name !== 'paragraph' && $pos.parent.type.name !== 'listItem') return false\n for (let depth = 1; depth < $pos.depth; depth++) if (!CONTAINERS.has($pos.node(depth).type.name)) return false\n return true\n}\n\n/** Whether the reference at `index` of `block` is alone on its line: only spaces beside it, up to a hard break either side. */\nfunction aloneOnLine(block: PmNode, index: number): boolean {\n for (const step of [-1, 1]) {\n for (let i = index + step; i >= 0 && i < block.childCount; i += step) {\n const child = block.child(i)\n if (child.type.name === 'hardBreak') break\n if (!child.isText || (child.text ?? '').trim() !== '') return false\n }\n }\n return true\n}\n\n/** How the reference node at `pos` draws. Anything that is not a reference with a `uri` draws as a chip. */\nexport function linkPlaceAt(doc: PmNode, pos: number): LinkPlace {\n const node = doc.nodeAt(pos)\n if (!node || node.type.name !== 'reference') return 'chip'\n const uri = String(node.attrs.uri ?? '')\n // A URL chip whose URL is not resolved yet names nothing: it reads as the URL.\n if (!uri || staysChip(uri)) return 'chip'\n if (Array.isArray(node.attrs.marks) && node.attrs.marks.length > 0) return 'chip'\n if (!keepsLineRule(doc, pos)) return 'chip'\n const $pos = doc.resolve(pos)\n if (!aloneOnLine($pos.parent, $pos.index())) return 'chip'\n return node.attrs.embed === 'detailed' ? 'card' : 'row'\n}\n\n/** Every reference that does not draw as its chip, with its place. */\nexport function linkPlaces(doc: PmNode): { pos: number; size: number; place: Exclude<LinkPlace, 'chip'> }[] {\n const out: { pos: number; size: number; place: Exclude<LinkPlace, 'chip'> }[] = []\n doc.descendants((node, pos) => {\n if (node.type.name !== 'reference') return true\n const place = linkPlaceAt(doc, pos)\n if (place !== 'chip') out.push({ pos, size: node.nodeSize, place })\n return false\n })\n return out\n}\n\n/** The place a node view's decorations give it; `chip` without one. */\nexport function placeOf(decorations: readonly Decoration[] | undefined): LinkPlace {\n for (const decoration of decorations ?? []) {\n const place = (decoration.spec as { linkPlace?: LinkPlace }).linkPlace\n if (place) return place\n }\n return 'chip'\n}\n\nconst key = new PluginKey<DecorationSet>('linkPlaces')\n\n/**\n * Marks each reference that draws as its row or its card, for `ReferenceNode`'s\n * view. Without it every reference is a chip, as in a message's box.\n */\nexport const LinkPlaces = Extension.create({\n name: 'linkPlaces',\n addProseMirrorPlugins() {\n const decorate = (doc: PmNode) =>\n DecorationSet.create(\n doc,\n linkPlaces(doc).map(({ pos, size, place }) => Decoration.node(pos, pos + size, { 'data-link-place': place }, { linkPlace: place })),\n )\n return [\n new Plugin<DecorationSet>({\n key,\n state: {\n init: (_, state) => decorate(state.doc),\n apply: (tr, set) => (tr.docChanged ? decorate(tr.doc) : set),\n },\n props: { decorations: (state) => key.getState(state) },\n }),\n ]\n },\n})\n", "/**\n * What a link in a document offers its writer: Open, and \u2014 alone on its line \u2014\n * Show as Row or Card (SPEC \u00A713.3, \"A reference's card\"). Card puts its card in\n * the row's place (`embed` `detailed`); Row puts the row back (no `embed`).\n * Nothing writes `compact`. A chip in a sentence, and a person or a Folder alone\n * on its line (which stay chips), offer Open only (`linkPlaceAt`).\n *\n * **Where it opens**: a click on a link while editing opens the menu instead\n * of following it, and a lone-line link just put in \u2014 pasted, picked with `[`,\n * or a pasted URL becoming its chip (`LinkChips`) \u2014 opens it by itself, so the\n * card can be chosen at once. That menu takes no focus: the person is still\n * writing, and typing on closes it with no card. Enter on a selected link opens\n * it from the keyboard.\n *\n * **Keys while it is open**, handed over by the editor as the `/` menu's are:\n * \u2193 and \u2191 move through the rows (nothing is highlighted until they do, so\n * Enter after a paste still starts a new line), Enter chooses the highlighted\n * row, Escape closes it. Any edit or caret move closes it.\n *\n * Open does what a click on the chip does when reading: the app's own chip\n * gets the click, so it opens where the app opens it. A chip with nothing to\n * click opens its URL in a new tab; one with neither \u2014 a person, a link still\n * loading or not available \u2014 offers no Open, and a menu left with nothing in\n * it does not open.\n *\n * Two parts: the extension `ReferenceMenu` holds which chip the menu is open\n * on, and `ReferenceMenuView` draws it beside `EditorContent`. Pair them with\n * `ReferenceNode` and `LinkPlaces`.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-lone-links-chip-menu-offers-row-or-card.md\n */\nimport { useCallback, useEffect, useReducer } from 'react'\nimport { Extension, type Editor } from '@tiptap/core'\nimport { useEditorState } from '@tiptap/react'\nimport { NodeSelection, Plugin, PluginKey, TextSelection, type EditorState, type Transaction } from '@tiptap/pm/state'\nimport { ReplaceStep } from '@tiptap/pm/transform'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { IconCheck, IconExternalLink } from '@tabler/icons-react'\nimport { CHIPS_MADE } from './LinkChips'\nimport { linkPlaceAt } from './LinkPlaces'\nimport { MenuItem, MenuSection, MenuSeparator } from './Menu'\nimport { Popover } from './Popover'\nimport { setReferenceCardAt } from './ReferenceCards'\n\ninterface MenuState {\n /** The chip's position. */\n pos: number\n /** The highlighted row of `rowsOf`, or -1 for none. */\n active: number\n}\n\nconst key = new PluginKey<MenuState | null>('referenceMenu')\n\n/** How a lone-line link can show. */\ntype ShowAs = 'row' | 'card'\n\nconst SHOW_AS: { as: ShowAs; label: string }[] = [\n { as: 'row', label: 'Row' },\n { as: 'card', label: 'Card' },\n]\n\n/** A row of the menu: Open, or a way to show the link. */\ntype Row = 'open' | ShowAs\n\n/** The chip's own control to click, or null. */\nfunction chipTarget(view: EditorView, pos: number): HTMLElement | null {\n const dom = view.nodeDOM(pos)\n return dom instanceof HTMLElement ? dom.querySelector<HTMLElement>('a[href], button') : null\n}\n\n/** An http(s) URL chip's URL, or ''. */\nfunction webHref(view: EditorView, pos: number): string {\n const href = view.state.doc.nodeAt(pos)?.attrs.href\n return typeof href === 'string' && /^https?:\\/\\//i.test(href) ? href : ''\n}\n\n/**\n * The menu's rows: Open when there is something to open \u2014 the link's own\n * control as the app drew it, or its URL \u2014 and Row and Card when it is alone\n * on its line and is neither a person nor a Folder (`linkPlaceAt`). A person,\n * and a link still loading or not available, draw nothing to click: no Open\n * (Katerina, 30 Oct). The view asks again as the app's drawing changes.\n */\nfunction rowsOf(view: EditorView, pos: number): Row[] {\n const open: Row[] = chipTarget(view, pos) || webHref(view, pos) ? ['open'] : []\n return linkPlaceAt(view.state.doc, pos) === 'chip' ? open : [...open, ...SHOW_AS.map((show) => show.as)]\n}\n\n/** A chip node, or null. */\nfunction chipAt(state: EditorState, pos: number) {\n const node = state.doc.nodeAt(pos)\n return node && node.type.name === 'reference' ? node : null\n}\n\n/**\n * The chip this transaction just put right before the caret \u2014 a paste, a `[`\n * pick (which adds a space after it), or a URL becoming its chip \u2014 or null.\n * An undo, and a document loaded over the editor, put nothing in.\n */\nfunction justPlaced(tr: Transaction, state: EditorState): number | null {\n if (!tr.docChanged || tr.getMeta('history$') || tr.getMeta('preventUpdate')) return null\n // A whole document set over the editor \u2014 someone else's edit loaded \u2014 is not something the person put in.\n const whole = tr.steps.some((step) => step instanceof ReplaceStep && step.from === 0 && step.to === tr.before.content.size)\n if (whole && tr.getMeta('uiEvent') !== 'paste') return null\n // A URL becoming its chip opens the menu only when it was pasted, with the caret still right after it.\n const made = tr.getMeta(CHIPS_MADE) as { pasted: boolean } | undefined\n if (made && !made.pasted) return null\n const { selection } = state\n if (!selection.empty) return null\n let at = selection.from\n let before = selection.$from.nodeBefore\n if (!made && before?.isText && before.text === ' ') {\n at -= 1\n before = state.doc.resolve(at).nodeBefore\n }\n if (!before || before.type.name !== 'reference' || !before.attrs.uri) return null\n const pos = at - before.nodeSize\n const old = tr.mapping.invert().map(pos)\n const was = tr.before.nodeAt(old)\n // The same chip as before the step \u2014 a key pressed after it, a card set on it \u2014 is not new. One put in just before\n // an identical chip pushes that chip along, so it no longer maps onto `pos` (code review).\n if (was && was.type.name === 'reference' && was.attrs.uri === before.attrs.uri && tr.mapping.map(old, 1) === pos) return null\n // Only a link alone on its line has a card to choose; in a sentence the menu would offer Open alone.\n if (linkPlaceAt(state.doc, pos) === 'chip') return null\n return pos\n}\n\nfunction dispatchMenu(view: EditorView, next: MenuState | null): void {\n view.dispatch(view.state.tr.setMeta(key, next))\n}\n\n// True while Open hands the click to the chip, so the chip's own click is not taken for a click that opens the menu.\nlet passing = false\n\n/** Opens what the chip at `pos` names, as a click on it does when reading. */\nfunction openChip(view: EditorView, pos: number): void {\n const target = chipTarget(view, pos)\n if (target) {\n passing = true\n try {\n target.click()\n } finally {\n passing = false\n }\n return\n }\n const href = webHref(view, pos)\n if (href) window.open(href, '_blank', 'noopener,noreferrer')\n}\n\n/** Runs `row` of the menu open on the chip at `pos`, and closes it. */\nfunction choose(editor: Editor, pos: number, row: Row | undefined): void {\n dispatchMenu(editor.view, null)\n if (row === 'open') openChip(editor.view, pos)\n else if (row) setReferenceCardAt(editor, pos, row === 'card' ? 'detailed' : 'none')\n}\n\n/** Whether the menu is open, for an editor's own Escape: while it is, Escape closes it rather than leaving. */\nexport function isReferenceMenuOpen(state: EditorState): boolean {\n return !!key.getState(state)\n}\n\n/**\n * A click on the chip at `pos`, from its node view: while editing, with the\n * menu installed, it opens the menu, and the caller stops the click there.\n * Returns false when the click should go on to the chip.\n */\nexport function referenceMenuClick(editor: Editor, pos: number): boolean {\n if (passing || editor.isDestroyed || !editor.isEditable || key.getState(editor.state) === undefined) return false\n // A chip with nothing to open and no card to choose has no menu: the click goes on to it.\n if (!chipAt(editor.state, pos) || rowsOf(editor.view, pos).length === 0) return false\n editor.view.dispatch(caretAfter(editor.state, pos).setMeta(key, { pos, active: -1 }))\n return true\n}\n\n/**\n * The caret right after the chip, as a paste leaves it: a selected chip would\n * bring up the selection toolbar beside the menu, and typing would replace it.\n */\nfunction caretAfter(state: EditorState, pos: number): Transaction {\n const node = state.doc.nodeAt(pos)\n return state.tr.setSelection(TextSelection.create(state.doc, pos + (node?.nodeSize ?? 1)))\n}\n\n/** Which chip the menu is open on: see the module comment. */\nexport const ReferenceMenu = Extension.create({\n name: 'referenceMenu',\n // Before the editor's own keys, so Enter on a highlighted row is the row's, not a new line.\n priority: 1000,\n addProseMirrorPlugins() {\n const editor = this.editor\n return [\n new Plugin<MenuState | null>({\n key,\n state: {\n init: () => null,\n apply: (tr, value, before, after) => {\n const meta = tr.getMeta(key) as MenuState | null | undefined\n if (meta !== undefined) return meta\n const placed = justPlaced(tr, after)\n if (placed !== null) return { pos: placed, active: -1 }\n if (!value) return null\n const pos = tr.mapping.map(value.pos)\n if (!chipAt(after, pos)) return null\n // What another plugin appends \u2014 an id, a trailing line \u2014 is not the person typing on, and nor is a URL\n // elsewhere becoming its chip when its answer comes back (code review).\n if (tr.docChanged && !tr.getMeta('appendedTransaction') && tr.getMeta(CHIPS_MADE) === undefined) return null\n const onChip = after.selection instanceof NodeSelection && after.selection.from === pos\n if (tr.selectionSet && !after.selection.eq(before.selection) && !onChip) return null\n return pos === value.pos ? value : { ...value, pos }\n },\n },\n props: {\n handleDOMEvents: {\n // Focus gone, the keys no longer reach the menu, and a card chosen now would miss the save on leaving (code review).\n blur: (view) => {\n if (key.getState(view.state)) dispatchMenu(view, null)\n return false\n },\n },\n handleKeyDown: (view, event) => {\n // With a modifier, a key is the editor's: Shift+\u2193 extends the selection, Mod+Enter is not a pick.\n if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return false\n const open = key.getState(view.state)\n if (!open) {\n // Enter on a selected chip: the menu, from the keyboard, its first row highlighted.\n const { selection } = view.state\n if (event.key !== 'Enter' || !view.editable || !(selection instanceof NodeSelection) || selection.node.type.name !== 'reference') return false\n if (rowsOf(view, selection.from).length === 0) return false\n view.dispatch(caretAfter(view.state, selection.from).setMeta(key, { pos: selection.from, active: 0 }))\n return true\n }\n const rows = rowsOf(view, open.pos)\n if (event.key === 'Escape') {\n dispatchMenu(view, null)\n return true\n }\n if (rows.length === 0) return false\n if (event.key === 'ArrowDown') {\n dispatchMenu(view, { ...open, active: (open.active + 1) % rows.length })\n return true\n }\n if (event.key === 'ArrowUp') {\n dispatchMenu(view, { ...open, active: open.active <= 0 ? rows.length - 1 : open.active - 1 })\n return true\n }\n if (event.key === 'Enter' && open.active >= 0) {\n choose(editor, open.pos, rows[open.active])\n return true\n }\n return false\n },\n },\n }),\n ]\n },\n})\n\n/** What the panel draws: the link the menu is open on, and how it shows. */\ninterface Shown {\n pos: number\n active: number\n shownAs: ShowAs\n}\n\nexport interface ReferenceMenuViewProps {\n editor: Editor | null\n}\n\n/** The menu `ReferenceMenu` holds, hung under its chip. Render it always, beside `EditorContent`. */\nexport function ReferenceMenuView({ editor }: ReferenceMenuViewProps) {\n const shown = useEditorState({\n editor,\n selector: ({ editor: ed }): Shown | null => {\n if (!ed || ed.isDestroyed) return null\n const open = key.getState(ed.state)\n if (!open) return null\n if (!chipAt(ed.state, open.pos)) return null\n // `compact` and a value this version does not know draw the row (\u00A713.3), so they read as Row here.\n return { pos: open.pos, active: open.active, shownAs: linkPlaceAt(ed.state.doc, open.pos) === 'card' ? 'card' : 'row' }\n },\n })\n // A press anywhere in the panel keeps focus in the text, as a row's does: the editor saves and ends its menus when it loses focus.\n const keepFocus = useCallback((list: HTMLDivElement | null) => {\n const panel = list?.closest('[role=\"dialog\"]')\n if (!panel) return\n const keep = (event: Event) => event.preventDefault()\n panel.addEventListener('mousedown', keep)\n return () => panel.removeEventListener('mousedown', keep)\n }, [])\n\n const live = shown && editor && !editor.isDestroyed ? editor : null\n const dom = live && shown ? live.view.nodeDOM(shown.pos) : null\n const anchor = dom instanceof HTMLElement ? dom : null\n // Whether there is something to open is the app's drawing, which can arrive after the menu (right after a `[` pick)\n // or change under it (a link that loads): the rows are asked again when it does.\n const [, redraw] = useReducer((count: number) => count + 1, 0)\n useEffect(() => {\n if (!anchor || typeof MutationObserver === 'undefined') return\n const observer = new MutationObserver(redraw)\n observer.observe(anchor, { childList: true, subtree: true, attributes: true, attributeFilter: ['href'] })\n return () => observer.disconnect()\n }, [anchor])\n const rows = live && shown ? rowsOf(live.view, shown.pos) : []\n const opens = rows[0] === 'open'\n const showAs = rows.includes('card')\n const run = (row: Row) => {\n if (editor && shown) choose(editor, shown.pos, row)\n }\n\n return (\n // finalFocus={false}: focus never left the text.\n <Popover\n anchor={anchor}\n open={!!shown && !!anchor && rows.length > 0}\n onOpenChange={(next) => {\n if (!next && editor && !editor.isDestroyed && key.getState(editor.state)) dispatchMenu(editor.view, null)\n }}\n side=\"bottom\"\n align=\"left\"\n ariaLabel=\"Link\"\n finalFocus={false}\n >\n {shown && (\n <div ref={keepFocus} role=\"menu\" aria-label=\"Link\" className=\"flex flex-col gap-0.5\">\n {/* Only when there is something to open: the chip's own control, or its URL (code review). */}\n {opens && (\n <MenuItem\n role=\"menuitem\"\n tabIndex={-1}\n label=\"Open\"\n leading={<IconExternalLink size={16} />}\n selected={shown.active === 0}\n onMouseDown={(event) => {\n event.preventDefault()\n run('open')\n }}\n />\n )}\n {showAs && (\n <>\n {opens && <MenuSeparator />}\n <div role=\"group\" aria-label=\"Show as\">\n <MenuSection label=\"Show as\">\n {SHOW_AS.map(({ as, label }, i) => (\n <MenuItem\n key={as}\n role=\"menuitemradio\"\n aria-checked={shown.shownAs === as}\n tabIndex={-1}\n label={label}\n selected={shown.active === i + (opens ? 1 : 0)}\n trailing={shown.shownAs === as ? <IconCheck size={16} aria-hidden /> : undefined}\n onMouseDown={(event) => {\n event.preventDefault()\n run(as)\n }}\n />\n ))}\n </MenuSection>\n </div>\n </>\n )}\n </div>\n )}\n </Popover>\n )\n}\n", "/**\n * An app URL in a document reads as the chip of what it names \u2014 SPEC \u00A713.3,\n * \"A reference's card\", and \u00A77.7.\n *\n * The URL stays the URL: the chip is the `reference` node with `href` set (a\n * URL chip, `ReferenceNode`), which a document writes back as the URL it was,\n * plain text with no card and a `link` mark with one. Never a `nostr:`\n * reference in its place: the URL is how a person addresses the object.\n *\n * What a URL names is the app's to say \u2014 its manifests and its relay \u2014 so the\n * app hands this extension two functions: `referenceOf`, what it has resolved\n * so far, and `ask`, to look up the URLs it has not. A URL that names nothing,\n * or whose answer has not come back, stays text; when `ask` settles the\n * document is looked at again.\n *\n * The URL being typed stays text while the caret is in it or at its end, so a\n * half-typed address never turns into a chip under the person's fingers. A\n * pasted URL is whole, so it is asked about and made a chip at once, the caret\n * still at its end \u2014 where `ReferenceMenu` opens its menu.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-link-is-stored-as-the-url-a-person-wrote.md\n */\nimport { Extension, type Editor } from '@tiptap/core'\nimport { closeHistory } from '@tiptap/pm/history'\nimport type { Node as PmNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey, type EditorState, type Selection, type Transaction } from '@tiptap/pm/state'\n\nexport interface LinkChipsOptions {\n /**\n * The `nostr:` reference an app URL names, from what the app has resolved\n * (\u00A77.7) \u2014 protocol's `referenceOfLink(url, resolveLink)`. Undefined while it\n * names nothing, or its answer has not come back.\n */\n referenceOf: ((url: string) => string | undefined) | null\n /** Look up what these URLs name. When it settles, the document is looked at again. */\n ask: ((urls: string[]) => Promise<unknown> | void) | null\n /**\n * How many URLs one editor asks about in its life, the first ones; the rest\n * stay text. An app's answer can cost a relay query, and a document pasted\n * full of links must not spend the writer's quota. Default 24.\n */\n limit: number\n}\n\ninterface LinkChipsState {\n options: LinkChipsOptions\n /** The last few pastes, mapped through every edit since. */\n pasted: PastedRange[]\n}\n\nconst key = new PluginKey<LinkChipsState>('linkChips')\n\n/** The meta on the transaction that made chips: `{ pasted }`. */\nexport const CHIPS_MADE = 'linkChipsMade'\n\n/** How many pastes are remembered; one is what the person just did. */\nconst PASTES_KEPT = 8\n\n/**\n * A link on words in marker text (skipped), or a bare URL \u2014 the grammar of\n * protocol's `urlRunsIn`, which a reader turns into chips by, so what an editor\n * makes a chip is what a reader would.\n */\nconst LINK_OR_URL = /(\\[[^[\\]\\n]+\\]\\((?:https?:\\/\\/|mailto:)[^\\s)]+\\))|(https?:\\/\\/[^\\s<>\"'`]+)/g\nconst TRAILING = new Set(['.', ',', ';', ':', '!', '?', ')', ']'])\n\n/** Each URL and where it sits; `end` is where its run ends before trailing punctuation is trimmed, which typing may yet continue. */\nfunction urlRuns(text: string): { url: string; from: number; to: number; end: number }[] {\n if (!text.includes('://')) return []\n const out: { url: string; from: number; to: number; end: number }[] = []\n for (const m of text.matchAll(LINK_OR_URL)) {\n if (m[1]) continue\n const start = m.index\n if (text.slice(Math.max(0, start - 2), start) === '](' || text[start - 1] === '[') continue\n let end = m[0].length\n while (end > 0 && TRAILING.has(m[0][end - 1])) end--\n out.push({ url: m[0].slice(0, end), from: start, to: start + end, end: start + m[0].length })\n }\n return out\n}\n\ninterface Found {\n /** Text URLs that name something: made chips. */\n chips: { from: number; to: number; url: string; uri: string; marks: string[]; pasted: boolean }[]\n /** URL chips whose URL is answered now: given their reference. */\n fills: { pos: number; uri: string }[]\n /** Every URL still waiting for an answer, or naming nothing. */\n open: string[]\n}\n\n/** Where something was pasted: a URL wholly inside one was not typed, so the caret at its end does not hold it as text. */\nexport interface PastedRange {\n from: number\n to: number\n}\n\n/**\n * What to change in a document, and what to ask. `selection` null treats no\n * URL as being typed; a URL inside one of `pasted` is never being typed.\n */\nexport function findLinkChips(doc: PmNode, selection: Selection | null, referenceOf: LinkChipsOptions['referenceOf'], pasted: readonly PastedRange[] = []): Found {\n const found: Found = { chips: [], fills: [], open: [] }\n const open = new Set<string>()\n doc.descendants((node, pos) => {\n // A fence is literal (\u00A713.1): its URLs are text.\n if (node.type.spec.code) return false\n if (node.type.name === 'reference') {\n const href = typeof node.attrs.href === 'string' ? node.attrs.href : ''\n if (href && !node.attrs.uri) {\n const uri = referenceOf?.(href)\n if (uri) found.fills.push({ pos, uri })\n else open.add(href)\n }\n return false\n }\n if (!node.isText || !node.text) return true\n // A URL in code is literal.\n if (node.marks.some((m) => m.type.spec.code || m.type.name === 'code')) return false\n // A link on words is the link's. A link whose text is its own URL \u2014 an editor's autolink, or its paste rule \u2014 is\n // that URL, as a document reads one (protocol's `inlineToEditor`): its chip, with the link mark left behind.\n const link = node.marks.find((m) => m.type.name === 'link')\n if (link && !(link.attrs.href === node.text && /^https?:\\/\\//.test(node.text))) return false\n const runs = link ? [{ url: node.text, from: 0, to: node.text.length, end: node.text.length }] : urlRuns(node.text)\n for (const run of runs) {\n const from = pos + run.from\n const to = pos + run.to\n // Being typed or selected: the caret inside it or at its end (`https://a.` is still being typed), or a\n // selection over any of it. A caret before it is not.\n // A pasted URL is whole: it becomes its chip with the caret still at its end, so its menu can open at once.\n const wasPasted = pasted.some((range) => range.from <= from && pos + run.end <= range.to)\n const typing = selection && selection.to > from && selection.from <= pos + run.end\n if (typing && !(selection.empty && wasPasted)) continue\n const uri = referenceOf?.(run.url)\n if (uri) found.chips.push({ from, to, url: run.url, uri, marks: node.marks.filter((m) => m !== link).map((m) => m.type.name), pasted: wasPasted })\n else open.add(run.url)\n }\n return false\n })\n found.open = [...open]\n return found\n}\n\nfunction apply(state: EditorState, found: Found): Transaction | null {\n if (!found.chips.length && !found.fills.length) return null\n const type = state.schema.nodes.reference\n if (!type) return null\n const tr = state.tr\n // A fill keeps the node's size, so the chips' positions still hold; the chips go last first.\n for (const { pos, uri } of found.fills) {\n const node = tr.doc.nodeAt(pos)\n if (node) tr.setNodeMarkup(pos, undefined, { ...node.attrs, uri })\n }\n for (const chip of [...found.chips].reverse()) {\n tr.replaceWith(chip.from, chip.to, type.create({ uri: chip.uri, href: chip.url, marks: chip.marks }))\n }\n // Whether a pasted URL became its chip: `ReferenceMenu` opens on that one, never on a URL typed by hand.\n const pasted = found.chips.some((chip) => chip.pasted)\n tr.setMeta(CHIPS_MADE, { pasted })\n // A pasted URL's chip is its own undo step, so Ctrl+Z gives the URL back rather than taking the paste away (OPT-19,\n // as Peek's pasted link did). Any other chip is not a step of the person's: undo takes back what they typed.\n return pasted ? closeHistory(tr) : tr.setMeta('addToHistory', false)\n}\n\n/**\n * Look at the document again \u2014 after the app learned what more URLs name some\n * other way. Dispatches only when there is a chip to make: an empty\n * transaction would wake every other plugin (a trailing paragraph appears).\n */\nexport function refreshLinkChips(editor: Editor): void {\n if (editor.isDestroyed) return\n const chips = key.getState(editor.state)\n if (!chips) return\n const tr = apply(editor.state, findLinkChips(editor.state.doc, editor.state.selection, chips.options.referenceOf, chips.pasted))\n if (tr) editor.view.dispatch(tr)\n}\n\n/**\n * Turns the app URLs in a document into URL chips. Pair it with `ReferenceNode`;\n * `LinkPlaces` then draws a lone one as its row or its card, and\n * `ReferenceMenu` lets its writer choose.\n */\nexport const LinkChips = Extension.create<LinkChipsOptions>({\n name: 'linkChips',\n addOptions() {\n return { referenceOf: null, ask: null, limit: 24 }\n },\n addProseMirrorPlugins() {\n const options = this.options\n const editor = this.editor\n return [\n new Plugin<LinkChipsState>({\n key,\n // The options, where `refreshLinkChips` can read them from the state alone, and where the last pastes landed.\n state: {\n init: () => ({ options, pasted: [] }),\n apply: (tr, value, before, after) => {\n if (!tr.docChanged) return value\n // A paste edited inside is being typed again: forgotten, so each keystroke in it is not an ask (security review).\n const pasted = value.pasted\n .map((range) => ({ from: tr.mapping.map(range.from, 1), to: tr.mapping.map(range.to, -1), size: range.to - range.from }))\n .filter((range) => range.from < range.to && range.to - range.from === range.size)\n .map(({ from, to }) => ({ from, to }))\n if (tr.getMeta('uiEvent') === 'paste') {\n const from = tr.mapping.map(before.selection.from, -1)\n if (from < after.selection.to) pasted.push({ from, to: after.selection.to })\n }\n return { options, pasted: pasted.slice(-PASTES_KEPT) }\n },\n },\n appendTransaction: (trs, _old, state) => {\n if (!trs.some((tr) => tr.docChanged || tr.selectionSet)) return null\n return apply(state, findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted))\n },\n view: (view) => {\n // Each URL is asked once; one whose ask failed is forgotten, so a later look asks again.\n const asked = new Set<string>()\n // The URL being typed is not asked about: each prefix of it would spend one of `limit`, and a query.\n const look = (state: EditorState) => {\n if (!options.ask) return\n const { open } = findLinkChips(state.doc, state.selection, options.referenceOf, key.getState(state)?.pasted)\n // The limit counts the URLs the document still holds unanswered: a message box lives across many messages,\n // and one that counted every URL it was ever asked would stop making chips after a day's links (OPT-19).\n const waiting = new Set(open)\n for (const url of asked) if (!waiting.has(url)) asked.delete(url)\n const fresh = open.filter((url) => !asked.has(url)).slice(0, Math.max(0, options.limit - asked.size))\n if (!fresh.length) return\n for (const url of fresh) asked.add(url)\n const forget = () => {\n for (const url of fresh) asked.delete(url)\n }\n let answer: Promise<unknown> | void\n try {\n answer = options.ask(fresh)\n } catch {\n forget()\n return\n }\n void Promise.resolve(answer).then(() => refreshLinkChips(editor), forget)\n }\n look(view.state)\n // Once the view is up, so a dispatch lands: what the app already knows turns into chips on open.\n queueMicrotask(() => {\n try {\n refreshLinkChips(editor)\n } catch {\n // Unmounted before it ran.\n }\n })\n return {\n update: (next, prev) => {\n // A caret leaving a URL finishes it, so a move is looked at as an edit is.\n if (next.state.doc !== prev.doc || !next.state.selection.eq(prev.selection)) look(next.state)\n },\n }\n },\n }),\n ]\n },\n})\n", "/**\n * The card a block document's writer chose for a reference \u2014 SPEC \u00A713.3, \"A\n * reference's card\": `embed` on the `reference` node (`ReferenceNode`), so the\n * card moves and goes with its chip. `ReferenceMenu` writes it (Show as Row or\n * Card) and `LinkPlaces` draws it in the row's place.\n *\n * The extension that placed a slot after each line for the app's card, and its\n * hook, were deprecated by `LinkPlaces` and are gone (Katerina's widget review,\n * 30 Oct): no app used them. What stays reads and writes the choice.\n */\nimport type { Editor } from '@tiptap/core'\nimport type { Node as PmNode } from '@tiptap/pm/model'\nimport { NodeSelection, type EditorState } from '@tiptap/pm/state'\n\n/** A layout a writer can choose; `none` is no card. */\nexport type ReferenceCardLayout = 'none' | 'compact' | 'detailed'\n\n/** One card to draw: the reference's `nostr:` URI and how much to show. */\nexport interface ReferenceCard {\n uri: string\n layout: Exclude<ReferenceCardLayout, 'none'>\n}\n\ninterface Placement {\n key: string\n /** The end of the textblock's content. */\n pos: number\n cards: ReferenceCard[]\n}\n\n/** `embed` as a node holds it: an unknown string draws as compact (\u00A713.3), anything else is none. */\nfunction layoutOf(raw: unknown): ReferenceCard['layout'] | undefined {\n if (typeof raw !== 'string' || raw === '' || raw === 'none') return undefined\n return raw === 'detailed' ? 'detailed' : 'compact'\n}\n\n/** Every line that asks for a card, in document order. */\nexport function referenceCardPlacements(doc: PmNode): Placement[] {\n const out: Placement[] = []\n const seen = new Map<string, number>()\n doc.descendants((node, pos, parent) => {\n if (!node.isTextblock) return true\n const cards: ReferenceCard[] = []\n node.forEach((child) => {\n if (child.type.name !== 'reference') return\n const layout = layoutOf(child.attrs.embed)\n // A URL chip whose URL is not resolved yet (`LinkChips`) has nothing to draw a card of, yet.\n if (layout && child.attrs.uri) cards.push({ uri: String(child.attrs.uri), layout })\n })\n if (cards.length) {\n // The textblock's own id, or its list item's or cell's: the nearest one.\n const id = node.attrs.blockId ?? parent?.attrs.blockId\n const base = id ? `b:${String(id)}` : `p:${pos}`\n const n = seen.get(base) ?? 0\n seen.set(base, n + 1)\n out.push({ key: n ? `${base}:${n}` : base, pos: pos + node.nodeSize - 1, cards })\n }\n return false\n })\n return out\n}\n\n/**\n * The chip the person has selected, with what it names and its card \u2014 or null.\n *\n * Selected as a node (a click, where a click on the chip does not follow its\n * link), or inside a selected range that holds that one chip and nothing but\n * spaces besides (Shift+arrow over it, or a drag across it): an app whose chip\n * is a link has no other way to select it.\n */\nexport function referenceAtSelection(state: EditorState): { pos: number; uri: string; layout: ReferenceCardLayout } | null {\n const { selection } = state\n let found: { pos: number; node: PmNode } | null = null\n if (selection instanceof NodeSelection) {\n if (selection.node.type.name === 'reference') found = { pos: selection.from, node: selection.node }\n } else if (!selection.empty) {\n let only = true\n state.doc.nodesBetween(selection.from, selection.to, (node, pos) => {\n if (node.type.name === 'reference') {\n if (found) only = false\n found = { pos, node }\n return false\n }\n if (node.isText) {\n const from = Math.max(selection.from, pos) - pos\n const to = Math.min(selection.to, pos + node.nodeSize) - pos\n if ((node.text ?? '').slice(from, to).trim() !== '') only = false\n }\n return true\n })\n if (!only) found = null\n }\n if (!found) return null\n const { pos, node } = found as { pos: number; node: PmNode }\n // A URL chip that names nothing yet has no card to choose.\n if (!node.attrs.uri) return null\n return { pos, uri: String(node.attrs.uri ?? ''), layout: layoutOf(node.attrs.embed) ?? 'none' }\n}\n\n/** Sets the card of the selected chip. `none` removes it. The selection stays as it was. */\nexport function setReferenceCard(editor: Editor, layout: ReferenceCardLayout): boolean {\n const at = referenceAtSelection(editor.state)\n return at ? setReferenceCardAt(editor, at.pos, layout) : false\n}\n\n/** Sets the card of the chip at `pos` \u2014 one that names something. `none` removes it. The selection stays as it was. */\nexport function setReferenceCardAt(editor: Editor, pos: number, layout: ReferenceCardLayout): boolean {\n const node = editor.state.doc.nodeAt(pos)\n if (!node || node.type.name !== 'reference' || !node.attrs.uri) return false\n const wasNode = editor.state.selection instanceof NodeSelection && editor.state.selection.from === pos\n // Same size, so a range maps onto itself; a node selection is made again, since the node is replaced.\n const tr = editor.state.tr.setNodeMarkup(pos, undefined, { ...node.attrs, embed: layout === 'none' ? null : layout })\n if (wasNode) tr.setSelection(NodeSelection.create(tr.doc, pos))\n editor.view.dispatch(tr)\n return true\n}\n", "// @estiva-escape(component-has-a-page, component-has-a-story): draws nothing of its own \u2014 it opens a SuggestionMenu from a Tiptap suggestion plugin, and SuggestionMenu's page and stories show it (UIG-31)\nimport { forwardRef, useRef, useImperativeHandle } from 'react'\nimport { ReactRenderer } from '@tiptap/react'\nimport { exitSuggestion, type SuggestionKeyDownProps, type SuggestionOptions, type SuggestionProps } from '@tiptap/suggestion'\nimport { SuggestionMenu, type SuggestionMenuHandle, type SuggestionMenuRow, type SuggestionMenuSection } from './SuggestionMenu'\n\n/*\n * Is a type-ahead list open? \u2014 Peek's counter (`mention.tsx`), moved here with\n * the lists it counts (UIG-31).\n *\n * A counter rather than a boolean: two suggestion plugins can overlap for a\n * moment while one hands over to the other (`/` choosing \"Mention\" types `@`).\n * An editor asks before it acts on Enter or Escape, so a key that chose a row\n * does not also send the message or cancel the edit.\n *\n * A list counts while it shows rows, not while its trigger listens: since a\n * space stopped closing one (f586437a), \"meet @ 5pm\" leaves `@` listening\n * behind a hidden list to the end of the line, and that Enter must still send.\n *\n * And only while its editor has focus (71a4577b): a list left by a click ends,\n * or it would stay counted and swallow Escape in the box clicked into.\n */\nlet openCount = 0\nlet lastClose = 0\n\n/**\n * Open, or closed less than 100ms ago \u2014 what an Enter handler asks. Choosing a\n * row with Enter closes the list, and that same Enter must not also send.\n */\nexport function isSuggestionActive(): boolean {\n return openCount > 0 || Date.now() - lastClose < 100\n}\n\n/**\n * Open *now*, with no grace period \u2014 what an Escape handler asks. The first\n * Escape closes the list, the second is somebody's deliberate press.\n */\nexport function isSuggestionOpen(): boolean {\n return openCount > 0\n}\n\n/** How a list looks and what fills it \u2014 everything but the editor's own wiring. */\nexport interface SuggestionPopupOptions<T> {\n /** Names the list \u2014 \"Commands\", \"People\". */\n ariaLabel: string\n /** The box's width, e.g. `w-[300px]`. */\n width: string\n /** The cap before the rows scroll, e.g. `max-h-[400px]`. */\n maxHeight: string\n /** The plugin's items, and the typed query, \u2192 the sections to draw. One unlabeled section by default. */\n sections?: (items: T[], query: string) => readonly SuggestionMenuSection<T>[]\n itemKey: (item: T) => string\n row: (item: T) => SuggestionMenuRow\n /**\n * With `refresh`: called with a listener while the list is open; the app\n * calls it when its data has changed (a search landing), and the open list is\n * drawn again for the same query. Returns the unsubscribe, run when the list\n * closes however it closes.\n */\n subscribe?: (listener: () => void) => () => void\n /** The items for a query, as the plugin's `items` answers \u2014 asked again when `subscribe` fires. */\n refresh?: (query: string) => T[]\n}\n\ntype Props<T> = SuggestionProps<T> & { options: SuggestionPopupOptions<T> }\n\n// `forwardRef`, so Tiptap's `ReactRenderer` hands its `ref` through whichever\n// way it detects a component that takes one.\nconst Popup = forwardRef<SuggestionMenuHandle, Props<unknown>>(function Popup({ options, ...props }, handle) {\n const menu = useRef<SuggestionMenuHandle>(null)\n useImperativeHandle(handle, () => ({ onKeyDown: (event) => menu.current?.onKeyDown(event) ?? false }))\n const sections = options.sections ? options.sections(props.items, props.query) : [{ items: props.items }]\n return (\n <SuggestionMenu\n handle={menu}\n rect={props.clientRect ?? null}\n editorElement={props.editor.view.dom}\n ariaLabel={options.ariaLabel}\n width={options.width}\n maxHeight={options.maxHeight}\n sections={sections}\n itemKey={options.itemKey}\n row={options.row}\n onSelect={(item) => props.command(item)}\n />\n )\n})\n\n/**\n * The `render` of a Tiptap suggestion plugin, drawn as a `SuggestionMenu` \u2014\n * the popup controller Peek wrote four times (`mention.tsx`, `slashCommands.tsx`),\n * once.\n *\n * Suggestion({ editor, char: '/', items, command,\n * render: suggestionPopup({ ariaLabel: 'Commands', width: 'w-[300px]',\n * maxHeight: 'max-h-[400px]', itemKey, row, sections }) })\n *\n * It mounts the list when the query starts and removes it when it ends: the\n * plugin owns the list's life. Escape closes it and is used up; \u2191, \u2193 and Enter\n * go to the list; every other key stays the editor's. The list portals itself\n * (the package `Popover`), so the mount point is only a mount point.\n */\nexport function suggestionPopup<T>(options: SuggestionPopupOptions<T>): NonNullable<SuggestionOptions<T>['render']> {\n return () => {\n let component: ReactRenderer<SuggestionMenuHandle, Props<T>> | null = null\n let container: HTMLDivElement | null = null\n let last: SuggestionProps<T> | null = null\n let unsubscribe: (() => void) | undefined\n let counted = false\n let unlisten: (() => void) | undefined\n const count = (shown: boolean) => {\n if (shown === counted) return\n counted = shown\n openCount = shown ? openCount + 1 : Math.max(0, openCount - 1)\n }\n // The plugin's state outlives a blur \u2014 no transaction runs \u2014 so leaving the\n // box ends the query here, as Escape does: coming back finds no list, and\n // Enter sends (Miky, 2026-10-06). Leaving the window is not leaving the box,\n // and a press in the list's own panel never takes focus (SuggestionMenu).\n const listen = (props: SuggestionProps<T>) => {\n const { view } = props.editor\n const dom = view.dom\n const onBlur = () => {\n // A window that loses focus leaves its active element where it was.\n if (dom.contains(document.activeElement) || !last) return\n const from = last.range.from\n // Not a pick: no grace for the other box's Enter.\n count(false)\n for (const plugin of view.state.plugins) {\n const state = plugin.getState(view.state) as { active?: boolean; range?: { from: number } } | undefined\n if (state?.active && state.range?.from === from && plugin.spec.key) exitSuggestion(view, plugin.spec.key)\n }\n }\n dom.addEventListener('blur', onBlur)\n unlisten = () => dom.removeEventListener('blur', onBlur)\n }\n const exit = () => {\n unsubscribe?.()\n unsubscribe = undefined\n unlisten?.()\n unlisten = undefined\n last = null\n // The grace is for the Enter that picked a row and closed the list, not\n // for a keystroke that only left it with no rows.\n if (counted) lastClose = Date.now()\n count(false)\n if (!component) return\n component.destroy()\n container?.remove()\n component = null\n container = null\n }\n return {\n onStart: (props) => {\n count(props.items.length > 0)\n component = new ReactRenderer<SuggestionMenuHandle, Props<T>>(Popup as never, { props: { ...props, options }, editor: props.editor })\n container = document.createElement('div')\n document.body.appendChild(container)\n container.appendChild(component.element)\n last = props\n listen(props)\n const { subscribe, refresh } = options\n if (subscribe && refresh) {\n // The plugin asks for items only when the query changes; an answer\n // landing later draws the open list again with the same props.\n unsubscribe = subscribe(() => {\n if (!last || !component) return\n last = { ...last, items: refresh(last.query) }\n count(last.items.length > 0)\n component.updateProps({ ...last, options })\n })\n }\n },\n onUpdate: (props) => {\n last = props\n count(props.items.length > 0)\n component?.updateProps({ ...props, options })\n },\n onKeyDown: ({ event }: SuggestionKeyDownProps) => {\n if (event.key === 'Escape') {\n exit()\n return true\n }\n return component?.ref?.onKeyDown(event) ?? false\n },\n onExit: exit,\n }\n }\n}\n", "// @estiva-escape(component-has-a-page, component-has-a-story): CommentBox's own frame, not offered to apps \u2014 CommentBox's page and stories show it (Katerina, 21 Oct: one box)\nimport { useCallback, useEffect, useState, type ReactNode } from 'react'\nimport { Extension } from '@tiptap/core'\nimport { EditorContent, type Editor } from '@tiptap/react'\nimport { IconArrowUp } from '@tabler/icons-react'\nimport { IconButton } from './IconButton'\nimport { Toolbar } from './Toolbar'\nimport { cn } from './cn'\nimport { richTextClassName } from './RichText'\nimport { ScrollArea } from './ScrollArea'\nimport { BOX_HINT_CLASSES, EDITOR_SELECTION_CLASSES, WRITING_BOX_CLASSES, WRITING_RING_CLASSES } from './looks'\nimport { SelectionToolbar, type SelectionToolbarProps } from './SelectionToolbar'\nimport { isSuggestionActive } from './suggestionPopup'\n\n/**\n * The frame `CommentBox` writes in, from Katerina's Leaf prototype (9\n * October): the text, scrolling in a `ScrollArea` past half the window, the\n * bar down its left while it is marked, what is attached, and a footer. The\n * send box and the edit box are this one frame with different footers, so a\n * change to the box is made once (Katerina, 21 Oct: the scrollbar had to be\n * fixed in two copies). It was `ComposeBox`, a part of its own until 0.85.0;\n * no app used it, and two box names invited the wrong pick.\n */\n\n/** The classes the box's editor wears: rich text with no outline. It never scrolls itself; the box does, in a `ScrollArea`. */\nexport const COMPOSE_EDITOR_CLASSES = richTextClassName('default', cn('outline-none w-full bg-transparent min-h-[20px] [&>p+p]:-mt-1', EDITOR_SELECTION_CLASSES))\n\n/**\n * A long draft stops at half the window and scrolls inside the box, so its\n * first line can be reached (PEE-59). The package's `ScrollArea` scrolls it,\n * not the browser: its bar, and one that shows while there is more (Katerina,\n * 21 Oct: the browser's bar, and none at all in some browsers).\n *\n * The region reaches into the box's right padding (the box's `p-3`) and its\n * content gives it back, so the text ends where it did and the bar sits 3px\n * from the box's edge, as every other box's bar does (Katerina, 21 Oct: the gap\n * on the right; measured 15px before, 3px after).\n */\nexport const COMPOSE_SCROLL_CLASSES = { area: '-mr-3', viewport: 'max-h-[50vh]', content: 'pr-3' }\n\ntype ComposeKeysStorage = { send: (() => boolean) | null }\n\n/**\n * Enter sends; Shift+Enter is a new line \u2014 in a list a new item (or out of the\n * list, on an empty one), in a quote a new line (or out of it, on an empty one).\n * Peek's keys, as its ComposeBox has them. Enter while a `/`, `@` or `[` list is\n * open picks a row instead. `ComposeBox` says what sending does.\n */\nexport const ComposeKeys = Extension.create<Record<string, never>, ComposeKeysStorage>({\n name: 'composeKeys',\n addStorage() {\n return { send: null }\n },\n addKeyboardShortcuts() {\n return {\n Enter: () => {\n if (isSuggestionActive()) return false\n this.storage.send?.()\n return true\n },\n 'Shift-Enter': ({ editor }) => {\n const { $from } = editor.state.selection\n for (let d = $from.depth; d > 0; d--) {\n const node = $from.node(d)\n if (node.type.name === 'listItem') {\n return node.textContent.length === 0 ? editor.commands.liftListItem('listItem') : editor.commands.splitListItem('listItem')\n }\n if (node.type.name === 'blockquote') {\n if ($from.parent.textContent.length === 0) return editor.commands.lift('paragraph')\n break\n }\n }\n return editor.commands.splitBlock()\n },\n }\n },\n})\n\n/** Nothing written: no text, no chip and no picture \u2014 empty lines, spaces, lists or quotes only. */\nexport function isEmptyDoc(editor: Editor): boolean {\n const doc = editor.state.doc\n if (doc.textContent.trim().length > 0) return false\n let empty = true\n doc.descendants((node) => {\n // A text node is a leaf, so an atom too: only spaces are left of it here.\n if (node.isAtom && !node.isText && node.type.name !== 'hardBreak') empty = false\n })\n return empty\n}\n\nexport interface BoxFrameProps {\n /** The box's editor, with `ComposeKeys` in its extensions and `COMPOSE_EDITOR_CLASSES` on it. `null` while it loads. */\n editor: Editor | null\n /** The bar down the text's left: an urgent mention or a highlight, as Peek draws it. */\n marked?: boolean\n /** The selection strip over the text, with these buttons. Absent, no strip (the edit box). */\n selection?: Pick<SelectionToolbarProps, 'marks' | 'link' | 'actions'>\n /** Said while the text is empty: words, and a `Kbd` where a key helps. */\n placeholder?: ReactNode\n empty?: boolean\n /** What is attached, under the text: `AttachmentCard pending`s. */\n attachments?: ReactNode\n /** The row under it all: the tools and Send, or the keys and Cancel/Save. */\n footer: ReactNode\n /** Signal's focus ring. Off for the edit box, whose edge only darkens on focus, as in Ship. Default on. */\n ring?: boolean\n /** On the box itself. */\n className?: string\n}\n\n/** The one frame both boxes draw: the bordered box, its text in a `ScrollArea`, what is attached, the footer. */\nexport function BoxFrame({ editor, marked = false, selection, placeholder, empty = false, attachments, footer, ring = true, className }: BoxFrameProps) {\n return (\n // Focused, the edge darkens (the send box in Signal takes the accent and its glow instead). In Leaf, the edge every\n // field takes, in the send box and the edit box alike (Katerina, 31 October); never the accent on Peek's edit box (1 November).\n <div className={cn(WRITING_BOX_CLASSES, ring && WRITING_RING_CLASSES, 'focus-within:border-border-strong leaf:focus-within:border-border-focus transition-colors', className)}>\n <div data-composer-editor data-marked={marked || undefined} className={cn('relative min-h-[20px] transition-all', marked && 'border-l-4 border-border-strong pl-2')}>\n <ScrollArea className={COMPOSE_SCROLL_CLASSES.area} viewportClassName={COMPOSE_SCROLL_CLASSES.viewport} contentClassName={COMPOSE_SCROLL_CLASSES.content}>\n <EditorContent editor={editor} />\n </ScrollArea>\n {selection && <SelectionToolbar editor={editor} {...selection} />}\n {empty && placeholder != null && (\n <div className=\"pointer-events-none absolute inset-0 flex flex-wrap items-center gap-1 text-body-2 text-text-muted\">{placeholder}</div>\n )}\n </div>\n {attachments && <div className=\"flex flex-wrap gap-2\">{attachments}</div>}\n {footer}\n </div>\n )\n}\n\nexport interface SendBoxProps {\n /** The box's editor. `null` while it loads. */\n editor: Editor | null\n /**\n * Send what is written. The box empties afterwards \u2014 unless this returns\n * `false`: nothing was sent, and the words stay.\n */\n onSend: (editor: Editor) => void | boolean\n /** Said in the empty box: words, and a `Kbd` where a key helps (\"type / for commands\"). */\n placeholder: ReactNode\n /** The tools under the text, left: `ToolbarButton`s (attach, highlight). One Tab stop. */\n tools?: ReactNode\n /** What is attached, under the text: `AttachmentCard pending`s. */\n attachments?: ReactNode\n /** Something to send even with no words \u2014 a file ready. */\n ready?: boolean\n /** Sending waits \u2014 a file still uploading. */\n holding?: boolean\n /** The bar down the text's left: an urgent mention or a highlight, as Peek draws it. */\n marked?: boolean\n /** The selection strip's buttons: its marks, Link, and the app's own (`actions`). */\n selection?: Pick<SelectionToolbarProps, 'marks' | 'link' | 'actions'>\n className?: string\n}\n\n/**\n * The send box: the frame with the selection strip over the text, the tools\n * and Send under it. Enter sends (`ComposeKeys`), and so does the button.\n */\nexport function SendBox({ editor, onSend, placeholder, tools, attachments, ready = false, holding = false, marked = false, selection, className }: SendBoxProps) {\n const [empty, setEmpty] = useState(true)\n const canSend = (!empty || ready) && !holding\n\n const send = useCallback((): boolean => {\n if (!editor || holding || (isEmptyDoc(editor) && !ready)) return true\n if (onSend(editor) === false) return true\n editor.commands.clearContent(true)\n editor.commands.focus()\n return true\n }, [editor, holding, ready, onSend])\n\n // Enter, through `ComposeKeys`, sends the way the button does.\n useEffect(() => {\n if (!editor) return\n const storage = (editor.storage as unknown as { composeKeys?: ComposeKeysStorage }).composeKeys\n if (!storage) return\n storage.send = send\n return () => {\n storage.send = null\n }\n }, [editor, send])\n\n useEffect(() => {\n if (!editor) return\n const read = () => setEmpty(isEmptyDoc(editor))\n read()\n editor.on('update', read)\n return () => {\n editor.off('update', read)\n }\n }, [editor])\n\n return (\n <div className={cn('relative', className)}>\n <BoxFrame\n editor={editor}\n marked={marked}\n selection={selection ?? {}}\n placeholder={placeholder}\n empty={empty}\n attachments={attachments}\n footer={\n // The tools are one strip \u2014 one Tab stop, arrows along it; Send, the answer rather than a tool, keeps its own.\n <div className=\"flex items-center justify-between\">\n {tools ? (\n <Toolbar aria-label=\"Compose tools\" surface={false} className=\"flex items-center gap-1\">\n {tools}\n </Toolbar>\n ) : (\n <span />\n )}\n <div className=\"flex items-center gap-2.5\">\n <span className={BOX_HINT_CLASSES}>Enter to send \u00B7 Shift+Enter new line</span>\n {/* Focus stays in the text: the press sends on its way down. A keyboard press is the click (`detail` 0), so a click never sends twice. */}\n <IconButton\n variant=\"primary\"\n onMouseDown={(e) => {\n e.preventDefault()\n send()\n }}\n onClick={(e) => {\n if (e.detail === 0) send()\n }}\n disabled={!canSend}\n aria-label=\"Send\"\n tooltip=\"Send\"\n tooltipShortcut=\"Enter\"\n glow={canSend}\n >\n <IconArrowUp size={16} stroke={1.5} />\n </IconButton>\n </div>\n </div>\n }\n />\n </div>\n )\n}\n", "/**\n * Looks two or more parts share, written once (UIG-25).\n *\n * A look typed again by hand draws the same today and drifts the day one of\n * them changes: nothing fails, one screen just looks slightly off. So a look\n * more than one part wears lives here, and each part takes it from here. The\n * lint that finds a copied look reads a class list wherever it is written; a\n * constant of classes ends in `_CLASSES`, so it is read as one.\n *\n * Only looks \u2014 colour, text, border, corner, shadow. Where a part sits and how\n * much room it takes stay in the part.\n */\n\n/**\n * A field's box: TextInput and Textarea. The hairline strengthens on hover \u2014 of the box, or of anywhere in the `Field` around it, label included, so the field is one thing under the pointer (Katerina, 28 September) \u2014 and not while switched off: a label passes its hover to its box, switched off or not (FIELD_DISABLED_CLASSES holds it back). Focus outranks it, so a focused field keeps its colour under the pointer.\n */\nexport const FIELD_BOX_CLASSES = 'bg-bg-field border border-border-field shadow-field hover:border-border-strong group-hover/field:border-border-strong focus:border-border-focus group-hover/field:focus:border-border-focus rounded-lg'\n\n/** What a field's words look like, typed or waiting: TextInput, Textarea and Select. */\nexport const FIELD_TEXT_CLASSES = 'text-text-primary placeholder:text-text-muted'\n\n/** A field that cannot be used: TextInput, Textarea and Select. */\nexport const FIELD_DISABLED_CLASSES = 'disabled:pointer-events-none disabled:bg-bg-disabled disabled:text-text-disabled disabled:border-border-field group-hover/field:disabled:border-border-field'\n\n/** The ring a focused field wears in Signal: TextInput and Textarea. */\nexport const FIELD_FOCUS_RING_CLASSES = 'signal:transition-shadow signal:focus:shadow-focus-ring'\n\n/** A field's two sizes, its padding and its words: TextInput, Textarea (default only) and Select. The small one is the small Select's trigger. */\nexport const FIELD_SIZE_CLASSES = {\n default: 'px-3 py-2 text-input-value',\n small: 'h-6 min-h-6 px-2 text-caption',\n} as const\n\n/** The box around an input that sits inside it, before its focus look: SearchInput and ChipInput. */\nexport const FIELD_SHELL_CLASSES = 'bg-bg-field border border-border-field shadow-field hover:border-border-strong group-hover/field:border-border-strong rounded-lg transition-colors'\n\n/** That box focused, while what is typed in it has the focus: the focus border, held under the pointer, and Signal's ring. ChipInput and DocumentField. */\nexport const FIELD_SHELL_FOCUS_CLASSES = 'focus-within:border-border-focus focus-within:hover:border-border-focus group-hover/field:focus-within:border-border-focus signal:transition-shadow signal:focus-within:shadow-focus-ring'\n\n/** A panel that floats over the page: Menu's panel and Tooltip. */\nexport const FLOATING_SURFACE_CLASSES = 'rounded-lg border border-border-default bg-bg-elevated shadow-lg'\n\n/** A count beside a label, in the muted colour: NavItem's number and SectionHeader's `count`. */\nexport const COUNT_TEXT_CLASSES = 'font-mono text-caption tabular-nums text-text-muted'\n\n/** A chip's words: Chip's label and Reaction's count. */\nexport const CHIP_TEXT_CLASSES = 'text-chip signal:font-mono signal:text-small signal:font-semibold signal:tabular-nums'\n\n/**\n * The time of something a person said: one line, and in Signal the mono micro-type with even digits, as Peek's\n * conversation draws a message's time (its MetaText). Only there: words a person wrote, and the latest conversation\n * (Katerina, 29 Oct); \"Updated\" and other times keep the text's own type.\n */\nexport const TIME_CLASSES = 'whitespace-nowrap signal:font-mono signal:text-small signal:tracking-wide signal:tabular-nums'\n\n/** Small secondary words that turn mono under signal: Kbd's key, CommandPalette's footer and MembersPill's count. */\nexport const MONO_CAPTION_CLASSES = 'text-caption text-text-secondary signal:font-mono signal:text-small'\n\n/** Words typed straight into an input with no box of its own: SearchInput and ChipInput. */\nexport const BARE_INPUT_CLASSES = 'bg-transparent text-text-primary placeholder:text-text-muted outline-none'\n\n/** A sidebar row's shape and its words at rest, brightening under the pointer: NavItem, and SectionHeader's `row` (a folder among rows). */\n// 8px corners, a MenuItem row's (Katerina, 2 October).\nexport const SIDEBAR_ROW_CLASSES = 'rounded-lg transition-colors'\nexport const SIDEBAR_ROW_TEXT_CLASSES = 'text-text-secondary hover:text-text-primary'\n\n/** A quiet icon control: secondary, brightening on a hover fill \u2014 IconButton's `muted`. */\nexport const MUTED_CONTROL_CLASSES = 'text-text-secondary hover:bg-bg-hover hover:text-text-primary'\n\n/** A control that opens a menu: a hover fill, held while its menu is up \u2014 PersonTrigger's row, and a ContainerHeader title with a menu. */\nexport const MENU_TRIGGER_CLASSES = 'cursor-pointer rounded-md transition-colors hover:bg-bg-hover data-[popup-open]:bg-bg-hover'\n\n/**\n * A column that folds sideways, as Peek's rail did (Katerina, 31 October: one fold in every app): 300ms, none under\n * prefers-reduced-motion. Folded, it fades and is then hidden, so nothing in it can be seen once it has gone; with\n * the `transition-[\u2026]` naming `opacity` and `visibility`. AppShell's navigation, and ListColumn closing with it.\n */\nexport const FOLD_MOTION_CLASSES = 'duration-300 ease-in-out motion-reduce:transition-none'\nexport const FOLDED_CLASSES = 'invisible opacity-0'\nexport const UNFOLDED_CLASSES = 'visible opacity-100'\n\n/**\n * A panel that slides open and shut on Base UI's Collapsible: Base UI measures\n * it and writes its height to a variable, `auto` again once the slide ends, and\n * the panel is 0 high on its opening and closing frames. None under\n * prefers-reduced-motion. CollapsibleSection's rows, and the rows under a NavItem.\n */\nexport const COLLAPSIBLE_PANEL_CLASSES = 'h-[var(--collapsible-panel-height)] overflow-hidden transition-[height] duration-150 ease-out motion-reduce:transition-none data-[starting-style]:h-0 data-[ending-style]:h-0'\n\n/**\n * The box a message or a comment is written in: Peek's writing box (its\n * `looks.ts`, Katerina 24 September), moved with the comment box. Inset, a hairline,\n * 12px in, 16px between the text and the row under it; the focus ring in Signal.\n */\n// A field's fill and edge, as every field has (Katerina, 31 October: the comment box is a field, and every field has its fill).\nexport const WRITING_BOX_CLASSES = 'relative bg-bg-field border border-border-field rounded-lg p-3 flex flex-col gap-4'\n\n/**\n * Selected words in an editor: the selected thing's fill, the colour the selection strip's kept selection paints\n * while its link field has the focus (`KeptSelection`), so the words look the same selected and kept. Peek's\n * composer rule (PEE-19), moved into every editor: the comment box, the document editor and InlineText.\n */\nexport const EDITOR_SELECTION_CLASSES = 'selection:bg-bg-selected'\n\n/** The keys under the send box, in words: \"Enter to send \u00B7 Shift+Enter new line\". One line, cut when the room runs out; no key caps. The edit box writes none (Katerina, 1 November). */\nexport const BOX_HINT_CLASSES = 'min-w-0 truncate select-none text-caption text-text-muted signal:font-mono signal:text-menu signal:font-normal signal:tracking-wider'\n\n/** Signal's focus ring (the glow) on the send box, as on every field. The edit box has no glow and no accent edge (Katerina, 31 October, 1 November). */\nexport const WRITING_RING_CLASSES = 'signal:transition-shadow signal:focus-within:border-border-focus signal:focus-within:shadow-focus-ring'\n\n/** The 36px tile a file's type sits in: AttachmentCard's, and a link's kind in LinkRow, LinkCard and PartCard (Katerina, 29 Oct). */\nexport const TYPE_TILE_CLASSES = 'size-9 rounded-md bg-bg-active flex items-center justify-center shrink-0 text-text-secondary'\n\n\n/** The bar down a quoted part's left edge: PartCard's blocks, and (proposal) a card's latest conversation. */\nexport const QUOTE_BAR_CLASSES = 'border-l-2 border-border-default pl-3'\n\n/**\n * A link in text: the link icon before its words, in the link's colour and at the text's size, and one underline\n * under the icon and the words together, as Slack draws one, so it never reads as a chip (Katerina, 29 Oct: \"icon\n * before but also underlined\", \"I want the icon to be underlined as well like Slack does\"). A chip of an Estiva thing\n * starts with its kind's icon instead and wears none of this.\n *\n * The browser's underline (`text-decoration`) skips an icon, so the line is the link's own background instead: 1px of\n * its colour along the bottom of each line it runs over. Tabler's `link` is drawn as a mask on `::before`, so it takes\n * the link's colour and nothing is added to what is saved or copied. `Link`'s `text` look is this, and so are the\n * editors' links (`LINK_CLASS`).\n */\n/** The line a link in text draws under everything in it, icon included: its own 1px background, since text-decoration skips an icon. */\nexport const LINK_UNDERLINE_CLASSES = 'no-underline bg-[linear-gradient(currentColor,currentColor)] bg-[length:100%_1px] bg-bottom bg-no-repeat'\n\nexport const WEB_LINK_CLASSES = `${LINK_UNDERLINE_CLASSES} before:content-[''] before:inline-block before:size-[1em] before:mr-0.5 before:align-[-0.125em] before:bg-current before:[mask:url(data:image/svg+xml,%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20viewBox%3D%270%200%2024%2024%27%20fill%3D%27none%27%20stroke%3D%27black%27%20stroke-width%3D%271.75%27%20stroke-linecap%3D%27round%27%20stroke-linejoin%3D%27round%27%3E%3Cpath%20d%3D%27M9%2015l6%20-6%27%2F%3E%3Cpath%20d%3D%27M11%206l.463%20-.536a5%205%200%200%201%207.071%207.072l-.534%20.464%27%2F%3E%3Cpath%20d%3D%27M13%2018l-.397%20.534a5.068%205.068%200%200%201%20-7.127%200a4.972%204.972%200%200%201%200%20-7.071l.524%20-.463%27%2F%3E%3C%2Fsvg%3E)_center/contain_no-repeat]`\n", "import type { ComponentType, MouseEvent, ReactNode } from 'react'\nimport { Extension, type Editor } from '@tiptap/core'\nimport { PluginKey } from '@tiptap/pm/state'\nimport Mention, { type MentionOptions } from '@tiptap/extension-mention'\nimport Suggestion from '@tiptap/suggestion'\nimport { NodeViewWrapper, ReactNodeViewRenderer, type ReactNodeViewProps } from '@tiptap/react'\nimport { Avatar } from './Avatar'\nimport type { ReferenceViewProps } from './BlockNodes'\nimport { EnterHint } from './Menu'\nimport { inlineChipClassName } from './InlineChip'\nimport { WithTooltip } from './Tooltip'\nimport type { SuggestionMenuRow } from './SuggestionMenu'\nimport { suggestionPopup, type SuggestionPopupOptions } from './suggestionPopup'\n\n/*\n * The four composer triggers every Estiva app shares \u2014 `@`, `!@`, `[` and `/`\n * (CON-26, Miky 2026-10-02). Peek built them first and they move here unchanged\n * (CON-27); an app passes in only its own data: its people, the things `[` can\n * reference, and the `/` rows it can perform beside the shared Format section.\n *\n * **What a pick writes is not here.** The text a chip becomes in the body and\n * the tags it earns are `@estiva-app/conversation`'s (`mentionText`,\n * `messageReference`, `urgentTagsFor`), so a client without React writes the\n * same bytes. A chip here carries what that needs: a person's `pubkey`, a\n * reference's `uri`.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/composer-triggers-are-one-shared-kit.md\n */\n\n// \u2500\u2500\u2500 @ and !@ \u2500\u2500\u2500\n\n/** A person `@` and `!@` offer. */\nexport interface MentionPerson {\n /** The app's own key for the person \u2014 the row's key and the chip's `id`. */\n id: string\n name: string\n /** The second line of the row: a role, a team. */\n description?: string\n /** Their Nostr key, when they have one \u2014 what the body is written with (SPEC \u00A713.1). */\n pubkey?: string | null\n /** The face at the row's start. Default: the package `Avatar` for the name. */\n avatar?: ReactNode\n /** An agent: its face is a robot, as Avatar's `bot`. */\n bot?: boolean\n}\n\n/** How many people the list shows. */\nexport const PEOPLE_LIMIT = 6\n\n/** The people whose name holds the query, the first {@link PEOPLE_LIMIT} of them. */\nexport function filterPeople(people: readonly MentionPerson[], query: string): MentionPerson[] {\n const q = query.toLowerCase()\n return people.filter((person) => q === '' || person.name.toLowerCase().includes(q)).slice(0, PEOPLE_LIMIT)\n}\n\n/**\n * The people list `@` and `!@` open: the face, the name, the second line, and\n * the Enter hint while highlighted \u2014 `MenuItem` at its tall size.\n */\nexport function peopleMenu(urgent: boolean): SuggestionPopupOptions<MentionPerson> {\n const section = urgent ? 'Urgent mention' : 'People'\n return {\n ariaLabel: section,\n // The people and the reference lists are the same box: 658px, capped at 360.\n width: 'w-[658px]',\n maxHeight: 'max-h-[360px]',\n sections: (people) => [{ label: section, items: people, className: 'px-3 py-1' }],\n itemKey: (person) => person.id,\n row: (person) => ({\n label: person.name,\n description: person.description,\n leading: person.avatar ?? <Avatar size={32} alt={person.name} bot={person.bot} />,\n hint: <EnterHint />,\n size: 'tall',\n }),\n }\n}\n\nexport interface PersonMentionOptions {\n /** Everyone the list can offer, asked each time the query changes. */\n people: () => readonly MentionPerson[]\n}\n\ntype Doc = { descendants: (cb: (node: { type: { name: string }; attrs: Record<string, unknown> }) => boolean | void) => void }\n\nfunction optionsOf<T>(editor: Editor, name: string): T | undefined {\n return editor.extensionManager.extensions.find((one) => one.name === name)?.options as T | undefined\n}\n\n/**\n * A list keeps listening across spaces, so a name or a title can be more than\n * one word (f586437a, Miky 2026-10-06). It stops at a new line, Escape, a pick\n * or the cursor leaving \u2014 Suggestion's own \u2014 and once the query holds `stop`:\n * `]` for `[`, so \"see [the notes] above\" ends as text. While nothing matches,\n * the list is hidden rather than closed, and comes back if the words match again.\n * A space straight after the key is prose (\"meet @ 5pm\", \"- [ ] task\"), not a\n * query: every two-word name holds a space.\n */\nconst listening = (stop: string) => ({\n allowSpaces: true,\n shouldShow: ({ query }: { query: string }) => !/^\\s/.test(query) && !query.includes(stop),\n})\n\n/** `@`'s list and pick, or `!@`'s, for the node `name` \u2014 the extension's own, so a renamed one still finds its people. */\nfunction personSuggestion(urgent: boolean, name: string) {\n return {\n ...(urgent ? { char: '!@' } : {}),\n // A second `@` starts another mention; the first one has ended.\n ...listening('@'),\n items: ({ query, editor }: { query: string; editor: Editor }) => filterPeople(optionsOf<PersonMentionOptions>(editor, name)?.people() ?? [], query),\n render: suggestionPopup(peopleMenu(urgent)),\n command: ({ editor, range, props: person }: { editor: Editor; range: { from: number; to: number }; props: MentionPerson }) => {\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n { type: name, attrs: { id: person.id, label: person.name, pubkey: person.pubkey ?? null } },\n { type: 'text', text: ' ' },\n ])\n .run()\n },\n }\n}\n\n/*\n What a chip keeps through HTML \u2014 a copy and paste, inside an editor or\n between two. The chip's own `renderHTML` writes each as a `data-*` attribute\n and these read them back. Until CON-27 none was written, so a pasted chip\n came back with every value null and was sent as `@null`. What is read is\n checked: a crafted `data-pubkey` that is not a key, or a `data-uri` that is\n not a `nostr:` reference, is dropped rather than written into the body.\n*/\nconst HEX_KEY = /^[0-9a-f]{64}$/\nconst NOSTR_URI = /^nostr:[a-z0-9]+$/i\nconst fromData = (name: string, valid?: RegExp) => ({\n parseHTML: (element: HTMLElement) => {\n const value = element.getAttribute(`data-${name}`)\n return value !== null && (!valid || valid.test(value)) ? value : null\n },\n // The node's own `renderHTML` writes it.\n renderHTML: () => ({}),\n})\n\nconst personAttributes = () => ({\n id: { default: null, ...fromData('id') },\n label: { default: null, ...fromData('label') },\n /**\n * The person's Nostr key, when they have one \u2014 SPEC \u00A713.1. `id` is the app's\n * own and means nothing to another app; this is what the body is written\n * with, so a mention survives a rename.\n */\n pubkey: { default: null, ...fromData('pubkey', HEX_KEY) },\n})\n\n/** The `data-*` a person chip is written with, so a paste reads it back. */\nfunction personData(attrs: Record<string, unknown>): Record<string, string> {\n return {\n 'data-id': String(attrs.id ?? ''),\n 'data-label': String(attrs.label ?? ''),\n ...(typeof attrs.pubkey === 'string' && attrs.pubkey ? { 'data-pubkey': attrs.pubkey } : {}),\n }\n}\n\n/**\n * `@` \u2014 a person, as a chip that writes their key (SPEC \u00A713.1).\n *\n * PersonMention.configure({ people: () => directory })\n *\n * Its `pubkey` and `label` are what `mentionText` takes.\n */\nexport const PersonMention = Mention.extend<MentionOptions<MentionPerson, MentionPerson> & PersonMentionOptions>({\n name: 'mention',\n addOptions() {\n return { ...this.parent!(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(false, this.name) }\n },\n addAttributes: personAttributes,\n renderHTML({ node }) {\n // No node view, so this spec is what the editor draws: the one chip.\n return ['span', { 'data-mention': 'true', ...personData(node.attrs), class: inlineChipClassName('person', 'cursor-default') }, `@${node.attrs.label}`]\n },\n parseHTML() {\n return [{ tag: 'span[data-mention]' }]\n },\n})\n\n/**\n * `!@` \u2014 a person, urgently: the same chip in the urgent tone. Its text is an\n * ordinary mention; the urgency travels as a tag (`urgentTagsFor`), so hand the\n * write {@link urgentPubkeys}.\n */\nexport const UrgentPersonMention = Mention.extend<MentionOptions<MentionPerson, MentionPerson> & PersonMentionOptions>({\n name: 'urgentMention',\n addOptions() {\n return { ...this.parent!(), HTMLAttributes: {}, people: () => [], suggestion: personSuggestion(true, this.name) }\n },\n addAttributes: personAttributes,\n renderHTML({ node }) {\n return [\n 'span',\n { 'data-urgent-mention': 'true', ...personData(node.attrs), class: inlineChipClassName('urgent', 'cursor-default') },\n `@${node.attrs.label}`,\n ]\n },\n parseHTML() {\n return [{ tag: 'span[data-urgent-mention]' }]\n },\n})\n\n/**\n * The keys the document's urgent mentions name \u2014 what the write turns into\n * `[\"urgent\", <pubkey>]` tags. A chip with no key has no tag to carry; its text\n * is the old `!@Name`.\n */\nexport function urgentPubkeys(editor: { state: { doc: Doc } }): string[] | undefined {\n const urgent: string[] = []\n editor.state.doc.descendants((node) => {\n if (node.type.name === 'urgentMention' && typeof node.attrs.pubkey === 'string' && node.attrs.pubkey) urgent.push(node.attrs.pubkey)\n })\n return urgent.length > 0 ? urgent : undefined\n}\n\nexport interface PersonReferenceOptions {\n /** Everyone `@` can offer, asked each time the query changes. */\n people: () => readonly MentionPerson[]\n /** The `nostr:npub\u2026` a person is written as; `null` for someone without one, who is not offered. */\n uriOf: (person: MentionPerson) => string | null\n /** The node a pick inserts. Default `reference`, `ReferenceNode`'s. */\n nodeName: string\n}\n\n/**\n * `@` in a document \u2014 a person, written as a reference to them: a\n * `ReferenceNode` whose `uri` is their `nostr:npub\u2026` (SPEC \u00A713.1, \u00A713.3). Not\n * {@link PersonMention}'s chip, which is a message's: a document names people\n * the way it names anything else, and a save that newly names someone is what\n * adds them (`@estiva-app/conversation`'s `mentionAddsFor`, which reads only\n * that uri).\n *\n * PersonReference.configure({ people: () => directory, uriOf: (person) => npubUri(person.pubkey) })\n *\n * The chip carries no name: the app's `ReferenceNode` view resolves the uri,\n * so a rename shows everywhere the person is named.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-mention-in-a-files-text-adds-the-person-with-no-unread.md\n */\nexport const PersonReference = Extension.create<PersonReferenceOptions>({\n name: 'personReference',\n addOptions() {\n return { people: () => [], uriOf: () => null, nodeName: 'reference' }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n Suggestion<MentionPerson>({\n editor: this.editor,\n char: '@',\n pluginKey: new PluginKey('personReference'),\n ...listening('@'),\n // As `[`'s: only where the chip may go.\n allow: ({ state, range }) => {\n const type = state.schema.nodes[options.nodeName]\n return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type)\n },\n items: ({ query }) =>\n filterPeople(\n options.people().filter((person) => options.uriOf(person) !== null),\n query,\n ),\n render: suggestionPopup(peopleMenu(false)),\n command: ({ editor, range, props: person }) => {\n const uri = options.uriOf(person)\n if (!uri) return\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n { type: options.nodeName, attrs: { uri } },\n { type: 'text', text: ' ' },\n ])\n .run()\n },\n }),\n ]\n },\n})\n\n// \u2500\u2500\u2500 [ \u2500\u2500\u2500\n\n/** Something `[` offers: a reference drawn as who said it and how it opens. */\nexport interface CaptionedItem {\n /** The referenced thing's id \u2014 the row's key and the chip's `id`. */\n id: string\n /** Who, as the list shows them. */\n label: string\n /** The opening words, marks stripped: the caption the row and the chip wear. */\n snippet: string\n /** `nostr:\u2026`, exactly as the body will carry it (`messageReference`). */\n uri: string\n /** What the query is matched against beside `label`. Default: `snippet`. */\n search?: string\n /** The row's second line, e.g. where the thing sits. The chip does not wear it. */\n description?: string\n /**\n * What the thing is about, in a line of plain text \u2014 a file's summary. When\n * set, it is the row's second line and `description` moves up after the\n * label, muted; absent, the row is as before. The chip does not wear it, and\n * the query is not matched against it.\n */\n summary?: string\n /**\n * This row's own 16px icon, in place of the list's `icon`: what the thing is,\n * when the list holds several kinds \u2014 a topic, a project, a message\n * (Katerina, 7 October). Absent, the list's icon.\n */\n icon?: ReactNode\n}\n\n/** One labelled group of `[`'s rows, in the order the list draws them. */\nexport interface ReferenceSection {\n label: string\n items: readonly CaptionedItem[]\n}\n\n/** How many references the list shows. */\nexport const REFERENCE_LIMIT = 6\n\n/**\n * The references whose label or text holds the query \u2014 the last\n * {@link REFERENCE_LIMIT}, in the order given: a thread is unbounded, and a\n * list that grew with it would be a hundred rows of prose.\n */\nexport function filterReferences(items: readonly CaptionedItem[], query: string): CaptionedItem[] {\n const q = query.toLowerCase()\n const shown = q ? items.filter((item) => (item.search ?? item.snippet).toLowerCase().includes(q) || item.label.toLowerCase().includes(q)) : [...items]\n return shown.slice(-REFERENCE_LIMIT)\n}\n\nconst captionOf = (label: string, snippet: string) => (snippet ? `${label}: ${snippet}` : label)\n\nexport interface CaptionedReferenceOptions {\n /** Drawn before the caption: a 14px icon. */\n icon: ReactNode\n /**\n * The chip's 14px icon from what it points at \u2014 its `uri` \u2014 when chips name\n * several kinds of thing; `undefined` from it, or no `iconFor`, draws `icon`.\n * The same answer the list's row gave (Katerina, 7 October).\n */\n iconFor?: (uri: string | null) => ReactNode | undefined\n /**\n * Draws the chip as the box's other links are drawn \u2014 the app's `referenceView`,\n * the kit's `LinkChip` \u2014 told it is being edited, so it shows no preview and a\n * click on it stays in the draft. Absent, or for a chip with no `uri`, the\n * caption with `icon`.\n */\n view?: ComponentType<ReferenceViewProps> | null\n}\n\n/** A click on a link inside a chip being written: the draft is not left for it (Katerina, 30 Oct). */\nfunction stayInDraft(event: MouseEvent) {\n if (event.target instanceof Element && event.target.closest('a[href]')) event.preventDefault()\n}\n\n/**\n * A reference mid-sentence, drawn as `label: snippet` and written as its `uri`\n * verbatim (SPEC \u00A713.1). The caption is the snapshot it was picked with \u2014 a\n * caption, never parsed. Inserted by {@link ReferenceTrigger}, a paste or a\n * draft; it opens no list of its own. With `view` it draws as the app draws\n * any other link in the box, so a `[` pick and a pasted link look alike.\n */\nexport const CaptionedReference = Mention.extend<MentionOptions & CaptionedReferenceOptions>({\n name: 'captionedReference',\n group: 'inline',\n inline: true,\n atom: true,\n addOptions() {\n return { ...this.parent!(), HTMLAttributes: {}, icon: null, iconFor: undefined, view: null, suggestion: { char: '\\0', items: () => [] } }\n },\n addAttributes() {\n return {\n id: { default: null, ...fromData('id') },\n label: { default: null, ...fromData('label') },\n snippet: { default: '', parseHTML: (element: HTMLElement) => element.getAttribute('data-snippet') ?? '', renderHTML: () => ({}) },\n uri: { default: null, ...fromData('uri', NOSTR_URI) },\n }\n },\n renderHTML({ node }) {\n return [\n 'span',\n { [`data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`]: 'true', 'data-id': String(node.attrs.id ?? ''), 'data-label': String(node.attrs.label ?? ''), 'data-snippet': String(node.attrs.snippet ?? ''), ...(node.attrs.uri ? { 'data-uri': String(node.attrs.uri) } : {}), class: inlineChipClassName('neutral', 'cursor-default') },\n captionOf(node.attrs.label, node.attrs.snippet),\n ]\n },\n parseHTML() {\n return [{ tag: `span[data-${this.name.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}]` }]\n },\n addNodeView() {\n const { icon, iconFor, view: View } = this.options\n return ReactNodeViewRenderer(\n ({ node }: ReactNodeViewProps) =>\n View && node.attrs.uri ? (\n <NodeViewWrapper as=\"span\" onClickCapture={stayInDraft}>\n <View uri={String(node.attrs.uri)} place=\"chip\" editing />\n </NodeViewWrapper>\n ) : (\n // The caption is cut at 24ch, so the whole of it is on hover, in the package's tooltip (UIG-14) \u2014 as Peek's sent chip has it.\n <NodeViewWrapper as=\"span\">\n <WithTooltip inline label={captionOf(node.attrs.label, node.attrs.snippet)}>\n <span className={inlineChipClassName('neutral', 'max-w-[24ch] cursor-default')}>\n <span className=\"flex items-center justify-center w-4 h-4 shrink-0 text-text-secondary\">{iconFor?.(node.attrs.uri ?? null) ?? icon}</span>\n <span className=\"truncate\">{captionOf(node.attrs.label, node.attrs.snippet)}</span>\n </span>\n </WithTooltip>\n </NodeViewWrapper>\n ),\n { as: 'span' },\n )\n },\n})\n\nexport interface ReferenceMenuOptions {\n /** Names the list, e.g. what can be referenced. */\n ariaLabel: string\n /** The section's heading. */\n sectionLabel: string\n /** At each row's start: a 16px icon \u2014 unless the row brings its own (`CaptionedItem.icon`), or `iconFor` answers. */\n icon: ReactNode\n /**\n * A row's 16px icon from what it points at \u2014 its `uri` \u2014 when the list holds\n * several kinds of thing; `undefined` from it draws `icon`. Give the chip the\n * same answer at 14px (`CaptionedReference`'s `iconFor`), so a pick keeps it.\n */\n iconFor?: (uri: string) => ReactNode | undefined\n}\n\n/** A row as the list holds it: which section it is drawn under, when the list has several. */\ntype ListedItem = CaptionedItem & { section?: string }\n\n/**\n * The list `[` opens: `label: snippet` rows, the same box as the people list.\n * One section headed `sectionLabel`, or \u2014 when the rows say which section they\n * are in \u2014 a heading for each, in the order the rows arrive.\n */\nexport function referenceMenu({ ariaLabel, sectionLabel, icon, iconFor }: ReferenceMenuOptions): SuggestionPopupOptions<CaptionedItem> {\n return {\n ariaLabel,\n width: 'w-[658px]',\n maxHeight: 'max-h-[360px]',\n sections: (items: ListedItem[]) => {\n const groups: { label: string; items: CaptionedItem[]; className: string }[] = []\n for (const item of items) {\n const label = item.section ?? sectionLabel\n const last = groups[groups.length - 1]\n if (last?.label === label) last.items.push(item)\n else groups.push({ label, items: [item], className: 'px-2' })\n }\n return groups\n },\n itemKey: (item) => `reference-${item.id}`,\n row: (item) => ({\n leading: item.icon ?? iconFor?.(item.uri) ?? icon,\n label: captionOf(item.label, item.snippet),\n // A summary is the second line, and where the thing sits moves up beside the label (SUM-7's story).\n ...(item.summary ? { description: item.summary, aside: item.description } : { description: item.description }),\n hint: <EnterHint />,\n }),\n }\n}\n\nexport interface ReferenceTriggerOptions extends ReferenceMenuOptions {\n /** Everything `[` can offer, asked each time the query changes. Narrowed by {@link filterReferences}. */\n items: () => readonly CaptionedItem[]\n /**\n * In place of `items`: the sections to draw for what was typed, already\n * narrowed and ordered by the app. Empty sections are not drawn.\n */\n sections?: (query: string) => readonly ReferenceSection[]\n /**\n * Called with a listener while the list is open; the app calls it when what\n * `sections` would answer has changed \u2014 a search landing \u2014 and the open list\n * is drawn again for the same query. Returns the unsubscribe.\n */\n subscribe?: (listener: () => void) => () => void\n /** The node a pick inserts. Default `captionedReference`. */\n nodeName: string\n}\n\nconst listed = (options: ReferenceTriggerOptions, query: string): ListedItem[] =>\n options.sections\n ? options.sections(query).flatMap((section) => section.items.map((item) => ({ ...item, section: section.label })))\n : filterReferences(options.items(), query)\n\n/**\n * `[` \u2014 reference something, inserted as a {@link CaptionedReference} chip.\n *\n * Its own extension rather than the chip's suggestion, so the chip's text (its\n * `renderText`) does not change with the key that summons the list.\n */\nexport const ReferenceTrigger = Extension.create<ReferenceTriggerOptions>({\n name: 'referenceTrigger',\n addOptions() {\n return { items: () => [], nodeName: 'captionedReference', ariaLabel: 'References', sectionLabel: 'References', icon: null }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n Suggestion<CaptionedItem>({\n editor: this.editor,\n char: '[',\n pluginKey: new PluginKey('referenceTrigger'),\n ...listening(']'),\n // As a mention's: only where the chip may go.\n allow: ({ state, range }) => {\n const type = state.schema.nodes[options.nodeName]\n return !!type && !!state.doc.resolve(range.from).parent.type.contentMatch.matchType(type)\n },\n items: ({ query }) => listed(options, query),\n render: suggestionPopup({ ...referenceMenu(options), subscribe: options.subscribe, refresh: (query) => listed(options, query) }),\n command: ({ editor, range, props: item }) => {\n editor\n .chain()\n .focus()\n .insertContentAt(range, [\n { type: options.nodeName, attrs: { id: item.id, label: item.label, snippet: item.snippet, uri: item.uri } },\n { type: 'text', text: ' ' },\n ])\n .run()\n },\n }),\n ]\n },\n})\n\n// \u2500\u2500\u2500 / \u2500\u2500\u2500\n\n/** A row of the `/` list, and what choosing it does. */\nexport interface SlashCommand {\n key: string\n row: SuggestionMenuRow\n /** Matched beside the row's label: an id, a trigger, a description. */\n keywords?: readonly string[]\n /** Runs once the `/query` that summoned the list has been removed. */\n run: (editor: Editor) => void\n /**\n * The extensions (by name) the row needs: an editor without one of them is\n * not offered the row, so no row makes something the editor cannot hold.\n */\n needs?: readonly string[]\n}\n\n/** Whether an editor has every extension a row needs. */\nconst offers = (editor: Editor, command: SlashCommand) =>\n !command.needs || command.needs.every((name) => editor.extensionManager.extensions.some((extension) => extension.name === name))\n\nexport interface SlashSection {\n label: string\n commands: readonly SlashCommand[]\n}\n\nexport type FormatId = 'paragraph' | 'heading' | 'subheading' | 'quote' | 'bulletList' | 'orderedList' | 'code' | 'checklist' | 'note' | 'warning'\n\nexport interface FormatDef {\n id: FormatId\n label: string\n /** What you type to get it \u2014 the input rule the extension registers. Blank when there is none. */\n trigger?: string\n /** The trigger when the format makes a block instead \u2014 Code's fence. Blank when it is the same. */\n blockTrigger?: string\n}\n\n/**\n * The formats `/` offers, in order. The hint is what you would type, not a key\n * chord. Bold, italic and underline are absent: they act on text already\n * written, so they are the selection toolbar's.\n */\nexport const FORMATS: readonly FormatDef[] = [\n { id: 'paragraph', label: 'Text' },\n { id: 'heading', label: 'Heading', trigger: '#' },\n { id: 'subheading', label: 'Subheading', trigger: '##' },\n { id: 'quote', label: 'Quote', trigger: '>' },\n { id: 'code', label: 'Code', trigger: '`', blockTrigger: '```' },\n { id: 'bulletList', label: 'Bulleted list', trigger: '-' },\n { id: 'orderedList', label: 'Numbered list', trigger: '1.' },\n]\n\n/**\n * What only a document holds \u2014 a checklist item and a callout (RIC-19) \u2014 so\n * only a block editor's `/` offers them (`formatSection('block')`): a\n * message's text has no spelling for either. They need the `Checklist` and\n * `Callout` extensions. Note and Warning are the two callouts offered (Miky,\n * 2026-10-13); the other tones are read and kept, not offered.\n */\nexport const DOCUMENT_FORMATS: readonly FormatDef[] = [\n { id: 'checklist', label: 'Checklist', trigger: '[]' },\n { id: 'note', label: 'Note' },\n { id: 'warning', label: 'Warning' },\n]\n\n/** Code as a mark inside the line, or as a block of its own. */\nexport type CodeFormat = 'inline' | 'block'\n\n/**\n * Apply one format to the current block. `set*` wherever Tiptap has one:\n * choosing Heading should make a heading, not turn one off. `false` means\n * nothing changed, not that anything failed.\n */\nexport function applyFormat(editor: Editor, id: FormatId, code: CodeFormat = 'inline'): boolean {\n /*\n The node's own command, called by name: StarterKit's extensions declare\n them, and this package builds without StarterKit. Its own command, rather\n than the core one it wraps, because a list's runs with the app's options\n (`keepMarks`, `itemTypeName`). An editor without that node changes nothing.\n A chain per call: a chain holds the state it was made from, and a quote\n first takes its line out of a list.\n */\n const run = (command: string, ...args: unknown[]): boolean => {\n const chain = editor.chain().focus()\n const named = (chain as unknown as Record<string, ((...a: unknown[]) => { run: () => boolean }) | undefined>)[command]\n return named ? named(...args).run() : false\n }\n /*\n A list item's first line cannot be wrapped where it is, so Quote, Note and\n Warning did nothing in a bulleted line once the `/` was gone (LFB-3). The\n line leaves its list first, as Heading's and Code's already do \u2014 only in\n an editor that has a quote to make. Whether it left one.\n */\n const leaveList = (): boolean => {\n if (!editor.schema.nodes.blockquote) return false\n let left = false\n while (editor.isActive('listItem') && run('liftListItem', 'listItem')) left = true\n return left\n }\n switch (id) {\n case 'paragraph':\n return run('setParagraph')\n case 'heading':\n return run('setHeading', { level: 1 })\n case 'subheading':\n return run('setHeading', { level: 2 })\n case 'quote':\n // A list inside a quote: the line, out of its list, is already quoted, and toggling would unquote it.\n if (leaveList() && editor.isActive('blockquote')) return true\n return run('toggleBlockquote')\n case 'bulletList':\n return run('toggleBulletList')\n case 'orderedList':\n return run('toggleOrderedList')\n case 'code':\n return run(code === 'block' ? 'toggleCodeBlock' : 'toggleCode')\n case 'checklist': {\n // In a list, that item becomes one; elsewhere, the line becomes a list of one.\n if (!editor.isActive('listItem') && !run('toggleBulletList')) return false\n // An item already a checklist item keeps its tick.\n if (typeof editor.getAttributes('listItem').checked === 'boolean') return true\n return editor.chain().updateAttributes('listItem', { checked: false }).run()\n }\n case 'note':\n case 'warning': {\n leaveList()\n if (!editor.isActive('blockquote') && !run('toggleBlockquote')) return false\n return editor.chain().updateAttributes('blockquote', { tone: id }).run()\n }\n default:\n return false\n }\n}\n\n/** Words a row is also found by, beyond its id. */\nconst KEYWORDS: Partial<Record<FormatId, string[]>> = {\n checklist: ['todo', 'task'],\n note: ['callout'],\n warning: ['callout'],\n}\n\n/** The extension a row's block needs: without it the row would make a plain bullet or a plain quote (Katerina, review of #170). */\nconst NEEDS: Partial<Record<FormatId, string[]>> = {\n checklist: ['checklist'],\n note: ['callout'],\n warning: ['callout'],\n}\n\n/**\n * The Format section every app's `/` opens with. A block editor's also offers\n * a checklist and the callouts \u2014 only where the editor has the `Checklist` and\n * `Callout` extensions (`SlashCommand.needs`).\n */\nexport function formatSection(code: CodeFormat = 'inline'): SlashSection {\n return {\n label: 'Format',\n commands: (code === 'block' ? [...FORMATS, ...DOCUMENT_FORMATS] : FORMATS).map((format) => ({\n key: `format-${format.id}`,\n row: { label: format.label, shortcut: (code === 'block' && format.blockTrigger) || format.trigger },\n keywords: [format.id, ...(KEYWORDS[format.id] ?? [])],\n ...(NEEDS[format.id] ? { needs: NEEDS[format.id] } : {}),\n run: (editor) => {\n applyFormat(editor, format.id, code)\n },\n })),\n }\n}\n\n/** A row that types another trigger, so its own list opens \u2014 `@` from `/`. */\nexport function typeTrigger(input: string): SlashCommand['run'] {\n // Deferred a frame: the delete of the `/query` has to land first, or the\n // trigger's plugin sees the character arrive inside a range still being removed.\n return (editor) => {\n requestAnimationFrame(() => editor.commands.insertContent(input))\n }\n}\n\nfunction matches(command: SlashCommand, q: string): boolean {\n return [command.row.label, ...(command.keywords ?? [])].some((text) => text.toLowerCase().includes(q))\n}\n\n/** The sections narrowed to a query \u2014 the text typed after the `/`. Empty sections stay. */\nexport function filterSlashSections(sections: readonly SlashSection[], query: string): SlashSection[] {\n const q = query.toLowerCase()\n return sections.map((section) => ({ ...section, commands: q ? section.commands.filter((command) => matches(command, q)) : section.commands }))\n}\n\nexport interface SlashCommandsOptions {\n /** The sections, in order: {@link formatSection} first, then the app's own. */\n sections: readonly SlashSection[]\n}\n\ntype SlashRow = SlashCommand & { section: number }\n\n/**\n * `/` \u2014 format the line or insert something, at the caret, mid-sentence too.\n * A `/` inside a word (`and/or`, a path) opens nothing: the plugin wants a\n * space or the line's start before it.\n */\nexport const SlashCommands = Extension.create<SlashCommandsOptions>({\n name: 'slashCommands',\n addOptions() {\n return { sections: [formatSection()] }\n },\n addProseMirrorPlugins() {\n const sections = this.options.sections\n return [\n Suggestion<SlashRow>({\n editor: this.editor,\n char: '/',\n startOfLine: false,\n pluginKey: new PluginKey('slashCommands'),\n items: ({ query, editor }) =>\n filterSlashSections(sections, query).flatMap((section, at) =>\n section.commands.filter((command) => offers(editor, command)).map((command) => ({ ...command, section: at })),\n ),\n command: ({ editor, range, props }) => {\n editor.chain().focus().deleteRange(range).run()\n props.run(editor)\n },\n render: suggestionPopup<SlashRow>({\n ariaLabel: 'Commands',\n width: 'w-[300px]',\n maxHeight: 'max-h-[400px]',\n sections: (rows) => sections.map((section, at) => ({ label: section.label, items: rows.filter((row) => row.section === at) })),\n itemKey: (row) => row.key,\n row: (row) => row.row,\n }),\n }),\n ]\n },\n})\n", "import { Extension, type Mark } from '@tiptap/core'\nimport { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\nimport StarterKit from '@tiptap/starter-kit'\nimport { WEB_LINK_CLASSES } from './looks'\n\n/*\n * Links in the kit's editors: a URL pasted over words, the link mark that holds\n * it, and a bare address drawn as a link. `CommentBox` and `DocumentEditor`\n * share the paste and the mark's end, so a link on words is made the same way\n * wherever it is written.\n */\n\n/** A link a message can carry on words, `[words](url)`: no `)` and no space in it (conversation's `composerText`). */\nconst LINK_ON_WORDS_TARGET = /^https?:\\/\\/[^\\s)]+$/\n\n/**\n * A URL pasted over words links them, as in Peek, when the message can carry\n * them as a link on words: plain words on one line, no chip, no line break, no\n * bracket, no code. Otherwise the words stay and the URL goes in after them,\n * so neither is lost. Ahead of StarterKit's own link-on-paste.\n */\nexport const PasteOverWords = Extension.create({\n name: 'commentBoxPasteOverWords',\n priority: 1001,\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('commentBoxPasteOverWords'),\n props: {\n handlePaste: (view, event) => {\n // A URL copied with the end of its sentence names what it names without it, as LinkChips reads one.\n const url = (event.clipboardData?.getData('text/plain').trim() ?? '').replace(/[.,;:!?]+$/, '')\n const { state } = view\n const { schema } = state\n if (state.selection.empty || !schema.marks.link || !/^https?:\\/\\/\\S+$/.test(url)) return false\n // Select-all spans the document itself: read it as the text it holds.\n const { $from, $to, from, to } = TextSelection.between(state.selection.$from, state.selection.$to)\n let plain = $from.sameParent($to) && $from.parent.isTextblock && !$from.parent.type.spec.code\n state.doc.nodesBetween(from, to, (node) => {\n // A quote or a list around the line holds it, and is not in the words: look inside.\n if (!node.isInline) return true\n if (!node.isText || node.marks.some((m) => m.type.spec.code || m.type.name === 'code')) plain = false\n return false\n })\n if (plain && LINK_ON_WORDS_TARGET.test(url) && !/[[\\]\\n]/.test(state.doc.textBetween(from, to))) {\n // The caret goes after the link: left selected, the words open the selection strip's Link field,\n // which takes focus and the next Enter, so a box needed two to send (COMM-8).\n const tr = state.tr.addMark(from, to, schema.marks.link.create({ href: url }))\n view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to)).removeStoredMark(schema.marks.link))\n return true\n }\n const before = state.doc.textBetween(Math.max(to - 1, $to.start()), to, '', '\uFFFC')\n const inserted = before && !/\\s/.test(before) ? ` ${url}` : url\n const tr = state.tr.insertText(inserted, to)\n view.dispatch(tr.setSelection(TextSelection.create(tr.doc, to + inserted.length)).scrollIntoView())\n return true\n },\n },\n }),\n ]\n },\n})\n\n/** StarterKit with a link that ends where its words end: what is typed after linked words is not linked (Peek's `inclusive: false`). */\nexport const BoxKit = StarterKit.extend({\n addExtensions() {\n return (this.parent?.() ?? []).map((extension) => (extension.name === 'link' ? extension.extend({ inclusive: () => false }) : extension))\n },\n})\n\n/**\n * {@link BoxKit} for a document: the same link, which also keeps `extra` \u2014\n * every key a saved link carries that this version does not know \u2014 so a save\n * writes it back. ProseMirror drops an attribute its schema does not name, and\n * the key with it. Protocol's `toEditorDocument(doc, { links: true })` fills it.\n */\nexport const DocumentKit = StarterKit.extend({\n addExtensions() {\n return (this.parent?.() ?? []).map((extension) =>\n extension.name === 'link'\n ? (extension as Mark).extend({\n inclusive: () => false,\n addAttributes() {\n return { ...this.parent?.(), extra: { default: null, rendered: false, parseHTML: () => null } }\n },\n })\n : extension,\n )\n },\n})\n\n/*\n * A bare address looks like a link while you write it, and a click opens it, as\n * a link in a read page does (Katerina, 30 September: the always-editable\n * description had made its links unclickable). Ship's `LinkDecoration`, moved\n * into the kit with the document editor.\n *\n * A decoration, not a mark: the address is saved as the text it is, byte for\n * byte. The patterns are `RichText`'s, so the editor marks what the reader links.\n */\nconst LINK_SPLIT = /\\[[^[\\]\\n]+\\]\\((?:https?:\\/\\/|mailto:)[^\\s)]+\\)|https?:\\/\\/[^\\s]+/g\n/** Punctuation after a bare address ends the sentence, not the address. */\nconst TRAILING = /[.,;:!?)\\]]+$/\n/** A link's look in an editor: the package `Link variant=\"text\"`, spelled out for a mark's element and a decoration's range, with the link icon and its underline as in `RichText`. */\nexport const LINK_CLASS = `text-info-default cursor-pointer ${WEB_LINK_CLASSES}`\n\n/** What a click may open: an address a reader may follow (SPEC \u00A713.1), never `javascript:` and the like. */\nconst OPENABLE = /^(https?:\\/\\/|mailto:)/i\n\n/** How a link mark is drawn in a document: the link look, a mark {@link BareLinks} recognises, and a new tab that cannot reach this one. */\nexport const LINK_MARK_ATTRIBUTES = { class: LINK_CLASS, 'data-link-mark': '', target: '_blank', rel: 'noopener noreferrer nofollow' }\n/** `[words](url)` names its address in the brackets; a bare address is its own. */\nconst LINK_TARGET = /\\]\\(([^\\s)]+)\\)$/\n\nexport const BareLinks = Extension.create({\n name: 'bareLinks',\n addProseMirrorPlugins() {\n return [\n new Plugin({\n key: new PluginKey('bareLinks'),\n props: {\n // The one way a click opens an address: a bare one's decoration, or, while editing, a link on words (read only,\n // the link is a plain anchor and opens itself). Only its own attributes are read \u2014 never a chip's \u2014 and only an\n // address a reader may follow opens, always without handing the new tab this window.\n handleClick: (view, _pos, event) => {\n if (event.button !== 0) return false\n const target = event.target as HTMLElement | null\n const bare = target?.closest?.('[data-bare-link]')?.getAttribute('data-bare-link')\n const onWords = view.editable ? target?.closest?.('a[data-link-mark]')?.getAttribute('href') : null\n const href = bare ?? onWords\n if (!href || !OPENABLE.test(href)) return false\n window.open(href, '_blank', 'noopener,noreferrer')\n return true\n },\n decorations: ({ doc }) => {\n const found: Decoration[] = []\n doc.descendants((node, pos) => {\n if (!node.isText || !node.text) return\n // A code run is literal, so an address quoted as an example is not a link; one already linked is the mark's.\n if (node.marks.some((mark) => mark.type.name === 'code' || mark.type.name === 'link')) return\n for (const match of node.text.matchAll(LINK_SPLIT)) {\n if (match.index === undefined) continue\n const text = match[0].startsWith('[') ? match[0] : match[0].replace(TRAILING, '')\n const href = text.startsWith('[') ? (LINK_TARGET.exec(text)?.[1] ?? '') : text\n found.push(Decoration.inline(pos + match.index, pos + match.index + text.length, { class: LINK_CLASS, ...(href ? { 'data-bare-link': href } : {}) }))\n }\n })\n return found.length ? DecorationSet.create(doc, found) : null\n },\n },\n }),\n ]\n },\n})\n", "import { Extension } from '@tiptap/core'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\n/** As much of a `DataTransfer` as the paste reads. */\nexport interface ClipboardSource {\n files?: ArrayLike<File> | null\n getData(format: string): string\n}\n\n/** MIME type \u2192 the extension a pasted picture is named with. */\nconst IMAGE_EXTENSIONS: Record<string, string> = {\n 'image/png': 'png',\n 'image/jpeg': 'jpg',\n 'image/gif': 'gif',\n 'image/webp': 'webp',\n 'image/heic': 'heic',\n 'image/heif': 'heif',\n 'image/svg+xml': 'svg',\n}\n\n/** Names a browser invents for a clipboard picture. A made-up one is better. */\nconst GENERIC_STEMS = new Set(['image', 'blob', 'unknown', 'untitled', 'screenshot'])\n\n/*\n An unlisted type keeps its own subtype rather than becoming `png`, so a\n picture the app does not accept is refused by the app's own message instead\n of arriving disguised as one it does.\n*/\nfunction extensionFor(contentType: string): string {\n const type = contentType.toLowerCase()\n return IMAGE_EXTENSIONS[type] ?? type.split('/')[1]?.split('+')[0] ?? 'png'\n}\n\n/** `'Screenshot 2026-09-07 14-32-05.png'`: sortable, and readable on a file card. */\nexport function pastedImageName(contentType: string, at: Date = new Date(), index = 0): string {\n const pad = (n: number) => String(n).padStart(2, '0')\n const stamp =\n `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())} ` +\n `${pad(at.getHours())}-${pad(at.getMinutes())}-${pad(at.getSeconds())}`\n const nth = index > 0 ? ` (${index + 1})` : ''\n return `Screenshot ${stamp}${nth}.${extensionFor(contentType)}`\n}\n\n/** A real filename is kept; `image.png`, `blob` and '' are not names. */\nfunction hasUsableName(name: string): boolean {\n const dot = name.lastIndexOf('.')\n if (dot <= 0 || dot === name.length - 1) return false\n return !GENERIC_STEMS.has(name.slice(0, dot).toLowerCase())\n}\n\n/**\n * The pictures on the clipboard, named \u2014 `[]` when there is nothing to attach.\n *\n * **Text wins.** A copy from a spreadsheet or a document puts a rendered\n * picture of the selection beside the text; attaching the picture instead of\n * pasting the text is wrong every time. So a clipboard holding text is left to\n * the editor, and a screenshot, which holds none, lands here. Pictures only:\n * any other file comes through the app's own file picker.\n */\nexport function pastedImages(source: ClipboardSource | null | undefined, at: Date = new Date()): File[] {\n if (!source) return []\n if (source.getData('text/plain').trim() !== '') return []\n const images = Array.from(source.files ?? []).filter((f) => f.type.toLowerCase().startsWith('image/'))\n let generated = 0\n return images.map((file) =>\n hasUsableName(file.name)\n ? file\n : new File([file], pastedImageName(file.type, at, generated++), { type: file.type, lastModified: file.lastModified }),\n )\n}\n\nexport interface PastedImagesOptions {\n /**\n * The pictures a paste carried, named. Return `true` when the app took them\n * (an upload started), `false` to let the editor paste as it would have \u2014\n * for a box that cannot upload right now.\n */\n onImages: (files: File[]) => boolean\n}\n\n/**\n * Pasting a picture attaches it: a screenshot pasted into the editor reaches\n * the app as named files, the way the app's own file picker would hand them.\n * Text on the clipboard wins (see {@link pastedImages}).\n */\nexport const PastedImages = Extension.create<PastedImagesOptions>({\n name: 'pastedImages',\n addOptions() {\n return { onImages: () => false }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n new Plugin({\n key: new PluginKey('pastedImages'),\n props: {\n handlePaste: (_view, event) => {\n const files = pastedImages(event.clipboardData)\n return files.length > 0 && options.onImages(files)\n },\n },\n }),\n ]\n },\n})\n", "import { useCallback, useEffect, useImperativeHandle, useRef, useState, type Ref } from 'react'\nimport { Extension, Node } from '@tiptap/core'\nimport { history, redo, undo } from '@tiptap/pm/history'\nimport { EditorContent, useEditor } from '@tiptap/react'\nimport { cn } from './cn'\nimport { EDITOR_SELECTION_CLASSES } from './looks'\n\n/**\n * A line of plain text on a page that you edit where it stands, as in a\n * document: a title, a summary. Ship's title editor (Katerina, 29 September,\n * findings E1 and E2), moved here for the summary (Miky, 16 October: \"it feels\n * like a document, not a form\") so every app's header edits the same way.\n *\n * - **No box**, on hover or on click, and nothing moves: the text is the\n * editor, in its own size and colour. The text cursor is the only sign.\n * - **The caret goes where you click**, and nothing is selected.\n * - **Enter saves and moves on** \u2014 `onEnter` says where: the title to the\n * summary, the summary to the description.\n * - **Escape stops editing and keeps the text**, saving it, as leaving does.\n * Nothing is thrown away; Ctrl+Z undoes.\n * - **An unchanged value is not a write.** Leaving it empty brings the saved\n * one back, unless `clearable`: then empty is saved, as nothing.\n * - **A refused save keeps your text where it is**, and the app says why\n * beside it; a change made elsewhere does not overwrite it until you have\n * saved, changed or emptied it.\n *\n * One paragraph and no marks, so pasted line breaks become spaces and it wraps\n * like text, which a one-line `<input>` cannot. A Tiptap editor rather than a\n * raw `contenteditable`, so it is the same kind of surface as the description\n * under it.\n */\nexport interface InlineTextProps {\n /** The saved text. A new value is loaded when you are not in the field and hold nothing unsaved. */\n value: string\n /** What it is for, muted, while it is empty: \"Untitled\", \"Add a summary\". */\n placeholder: string\n /** The accessible name: \"Title\", \"Summary\". */\n label: string\n /** Save it: resolve `true` when saved; `false` keeps your text in place. */\n onCommit: (value: string) => Promise<boolean> | boolean\n /** The text as it is being written, on focus and every change; `null` when you leave. For a count. */\n onText?: (text: string | null) => void\n /** Enter, after the save has started: where the caret goes next. */\n onEnter?: () => void\n /**\n * `title`: the page's heading. `heading`: a document's title, at the largest heading size (Leaf's file page).\n * `summary`: the line under either, quieter.\n */\n variant?: 'title' | 'heading' | 'summary'\n /** Empty is a value (a summary). Otherwise leaving it empty brings the saved one back (a title). */\n clearable?: boolean\n /** Text only, the same size and place: nobody can change it, or the editor is not ready. */\n readOnly?: boolean\n /** Placement only. */\n className?: string\n ref?: Ref<InlineTextHandle>\n}\n\ntype CaretAt = 'start' | 'end'\n\nexport interface InlineTextHandle {\n /** Put the caret in it, at the start or the end. */\n focus: (at?: CaretAt) => void\n}\n\n/** Size and tone, per variant: the same for the text at rest and while it is written. */\nconst VARIANT = {\n title: 'text-h2 text-text-primary',\n // A document's title: Leaf set text-h1 on InlineText from outside, which the gate refuses (Katerina, 29 Oct: \"I choose A\").\n heading: 'text-h1 text-text-primary',\n summary: 'text-body-1 text-text-secondary',\n} as const\n\n/** The room around the text: the caret has a little space at the edges, and the text still lines up with what is above and below it. */\nconst ROOM = '-mx-2 px-2 py-1'\n\n// The whole schema: one paragraph of text. Written with the core, so the\n// package's peers stay what they were.\nconst OneLine = Node.create({ name: 'doc', topNode: true, content: 'paragraph' })\nconst Paragraph = Node.create({\n name: 'paragraph',\n content: 'text*',\n parseHTML: () => [{ tag: 'p' }],\n renderHTML: () => ['p', 0],\n})\nconst Text = Node.create({ name: 'text' })\nconst Undo = Extension.create({\n name: 'inlineTextUndo',\n addProseMirrorPlugins: () => [history()],\n addKeyboardShortcuts() {\n const run = (command: typeof undo) => () => command(this.editor.state, this.editor.view.dispatch)\n return { 'Mod-z': run(undo), 'Shift-Mod-z': run(redo), 'Mod-y': run(redo) }\n },\n})\n\nconst doc = (text: string) => ({ type: 'doc', content: [{ type: 'paragraph', content: text ? [{ type: 'text', text }] : [] }] })\n\n/** One line: every run of white space, line breaks included, is one space. */\nconst oneLine = (text: string) => text.replace(/\\s+/g, ' ').trim()\n\nexport function InlineText({ value, placeholder, label, onCommit, onText, onEnter, variant = 'title', clearable = false, readOnly = false, className, ref }: InlineTextProps) {\n const saved = useRef(value)\n // The placeholder follows the text as it is typed or deleted, not the saved value.\n const [empty, setEmpty] = useState(!value)\n // Read at key time: the editor's handlers are built once, and a prop they\n // closed over would be the first render's.\n const latest = useRef({ onEnter, onText, onCommit, clearable, value })\n latest.current = { onEnter, onText, onCommit, clearable, value }\n // The text being saved right now: Enter moves on, and the leave that follows\n // must not send the same save a second time while the first is in flight.\n const pending = useRef<string | null>(null)\n\n const save = useCallback(async (text: string) => {\n const next = oneLine(text)\n if (next === saved.current || next === pending.current) return\n if (!next && !latest.current.clearable) return\n pending.current = next\n try {\n if (await latest.current.onCommit(next)) saved.current = next\n } finally {\n if (pending.current === next) pending.current = null\n }\n }, [])\n\n const editor = useEditor({\n extensions: [OneLine, Paragraph, Text, Undo],\n content: doc(value),\n editable: !readOnly,\n editorProps: {\n attributes: {\n 'aria-label': label,\n role: 'textbox',\n 'aria-multiline': 'false',\n 'aria-placeholder': placeholder,\n ...(readOnly ? { 'aria-readonly': 'true' } : {}),\n class: cn('outline-none', EDITOR_SELECTION_CLASSES),\n },\n handleKeyDown: (view, event) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n void save(view.state.doc.textContent)\n latest.current.onEnter?.()\n return true\n }\n if (event.key === 'Escape') {\n view.dom.blur()\n return true\n }\n return false\n },\n // A paste is its plain text on this one line, whatever it was copied from.\n handlePaste: (view, event) => {\n const text = event.clipboardData?.getData('text/plain')\n if (text == null) return false\n view.dispatch(view.state.tr.insertText(text.replace(/\\s+/g, ' ')))\n return true\n },\n },\n onFocus: ({ editor: e }) => latest.current.onText?.(e.getText()),\n onUpdate: ({ editor: e }) => {\n setEmpty(e.isEmpty)\n latest.current.onText?.(e.getText())\n },\n onBlur: ({ editor: e }) => {\n latest.current.onText?.(null)\n // Left empty where empty is not a value: the saved text comes back, so\n // the page never shows the placeholder while everyone else sees the text.\n if (e.isEmpty && saved.current && !latest.current.clearable) {\n e.commands.setContent(doc(saved.current), { emitUpdate: false })\n setEmpty(false)\n return\n }\n // Left unchanged while someone else changed it: their text comes in now,\n // as it would have had you not been in it.\n const { value: current } = latest.current\n if (oneLine(e.getText()) === saved.current && current !== saved.current && pending.current === null) {\n e.commands.setContent(doc(current), { emitUpdate: false })\n saved.current = current\n setEmpty(!current)\n return\n }\n void save(e.getText())\n },\n }, [readOnly])\n\n // A change made elsewhere is loaded while you are not in the field and hold\n // nothing unsaved; your own save coming back is left alone.\n useEffect(() => {\n if (!editor || editor.isDestroyed || value === saved.current || editor.isFocused) return\n if (oneLine(editor.getText()) !== saved.current) return\n editor.commands.setContent(doc(value), { emitUpdate: false })\n saved.current = value\n setEmpty(!value)\n }, [editor, value])\n\n useImperativeHandle(ref, () => ({\n focus: (at = 'start') => editor?.commands.focus(at),\n }), [editor])\n\n return (\n <div className={cn('relative', VARIANT[variant], className)}>\n <EditorContent editor={editor} className={cn(ROOM, !readOnly && 'cursor-text')} />\n {/* Empty \u2014 never saved, or just deleted \u2014 shows what it is for, muted,\n and is not part of the text. Drawn over the editor, where the text starts. */}\n {empty && !readOnly && (\n <span aria-hidden className=\"pointer-events-none absolute left-0 top-1 text-text-muted\">{placeholder}</span>\n )}\n </div>\n )\n}\n", "import type { Editor } from '@tiptap/react'\nimport { Extension } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\n/**\n * Comments on a selection, drawn where they are, from Katerina's Leaf prototype\n * (9 October), with a run, whole blocks and changed words added for LEAF-7.\n *\n * A comment's place is the one SPEC \u00A713.6 gives it: a run of blocks, and the\n * words where the selection starts and where it ends as a quote. Words inside\n * one block are quoted whole; a selection across blocks quotes its start in\n * the first block and its end in the last; a selection of whole blocks quotes\n * nothing and is about the blocks. Nothing is written into the document: the\n * highlight is a decoration, so a save never carries it.\n *\n * Three places a comment can be in, as `@estiva-app/protocol`'s\n * `resolveCommentAnchor` reads them:\n * - **resolved** \u2014 its words are found (drawn on them), or it quotes none\n * (drawn on its whole blocks);\n * - **reworded** \u2014 its blocks are there and its words are not: nothing is\n * drawn, and the comment stands beside its first block;\n * - **detached** \u2014 none of its blocks is left.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/a-comment-remembers-where-its-selection-starts-and-ends.md\n */\n\n/** The words a comment quotes: \u00A713.6's `quote` tag. */\nexport interface CommentQuote {\n /** The selection's words in one block, or its first words when it runs across blocks. */\n start: string\n /** Its last words, in the run's last block. Absent: `start` is the whole selection. */\n end?: string\n /** A few characters before `start`, only when the words repeat in their block. */\n prefix?: string\n /** A few characters after the end, only when the words repeat in their block. */\n suffix?: string\n}\n\n/** One comment's place: the blocks it is anchored to and the words it is about. */\nexport interface CommentAnchor {\n /** The thread's id. Clicks report it; `active` names it. */\n id: string\n /** The run: the \u00A713.3 block ids the comment's `block` tag lists, in order. */\n blocks: readonly string[]\n /** The words, as they were when the comment was written. Absent: the whole blocks. */\n quote?: CommentQuote\n}\n\n/** Where a comment is now, in document positions. */\nexport type CommentPlace =\n /** Drawn: on its words (`words`), or on its whole blocks. */\n | { state: 'resolved'; from: number; to: number; words: boolean }\n /** Its blocks (`from`\u2013`to`) are there, its words are not. Draw nothing; show the quote as the commenter's. */\n | { state: 'reworded'; from: number; to: number }\n /** None of its blocks is left. */\n | { state: 'detached' }\n\ninterface HighlightState {\n anchors: readonly CommentAnchor[]\n active: string | null\n}\n\nconst commentHighlightsKey = new PluginKey<HighlightState>('commentHighlights')\n\n/**\n * The highlight's two looks: every commented selection, and the one being\n * read. A block carries the same classes as words do: its underline reaches\n * every line of its text.\n */\nconst COMMENT_HIGHLIGHT_CLASSES = {\n rest: 'cursor-pointer rounded-sm bg-warning-muted',\n active: 'cursor-pointer rounded-sm bg-warning-muted underline decoration-warning-default decoration-2 underline-offset-4',\n} as const\n\n/** Up to this many characters, a selection in one block is quoted whole (\u00A713.6). */\nconst QUOTE_WHOLE_MAX = 1000\n/** Otherwise about this many at each end, cut at a word. */\nconst QUOTE_END_LENGTH = 150\n/** How much of the text around repeated words is kept to tell them apart. */\nconst QUOTE_CONTEXT_LENGTH = 32\n\n/** A block with an id: where it is, where its parent's content starts, and its index there. */\ninterface Place {\n node: ProseMirrorNode\n pos: number\n parent: number\n index: number\n}\n\n/** Every block carrying an id, by id. */\nfunction placesIn(doc: ProseMirrorNode): Map<string, Place> {\n const places = new Map<string, Place>()\n const walk = (parent: ProseMirrorNode, parentPos: number) => {\n parent.forEach((node, offset, index) => {\n const pos = parentPos + offset\n const id = node.attrs.blockId\n if (typeof id === 'string' && id && !places.has(id)) places.set(id, { node, pos, parent: parentPos, index })\n if (!node.isTextblock && !node.isLeaf) walk(node, pos + 1)\n })\n }\n walk(doc, 0)\n return places\n}\n\n/**\n * A block's text, and the document position where each of its characters\n * starts and ends. It is the text the protocol's `inlineTextOf` reads from the\n * same block on the wire, or a quote written here would not be found there: a\n * chip counts as the text it is on the wire (a URL chip its URL, any other its\n * `nostr:` reference), a line break as `\\n`, and the blocks inside a block (a\n * quote's lines, a list's items, a table's cells) are joined with `\\n`. A list\n * item is its own text: the list inside it is flat on the wire, its items\n * following it in the list.\n */\nfunction textOf(block: Place): { text: string; starts: number[]; ends: number[] } {\n let text = ''\n const starts: number[] = []\n const ends: number[] = []\n const add = (chars: string, start: number, end: number) => {\n for (let i = 0; i < chars.length; i++) (starts.push(start), ends.push(end))\n text += chars\n }\n const walk = (node: ProseMirrorNode, pos: number) => {\n if (node.isTextblock) {\n node.forEach((child, offset) => {\n const at = pos + 1 + offset\n if (child.isText && child.text) {\n for (let i = 0; i < child.text.length; i++) (starts.push(at + i), ends.push(at + i + 1))\n text += child.text\n } else if (child.type.name === 'hardBreak') add('\\n', at, at + child.nodeSize)\n else if (child.isInline && child.isLeaf) add(String(child.attrs.href || child.attrs.uri || ''), at, at + child.nodeSize)\n })\n return\n }\n // A list item's paragraphs are one run on the wire, with nothing between them.\n if (node.type.name === 'listItem') {\n node.forEach((child, offset) => void (LISTS.has(child.type.name) || walk(child, pos + 1 + offset)))\n return\n }\n const children = LISTS.has(node.type.name) ? itemsOf(node, pos) : childrenOf(node, pos)\n children.forEach(({ node: child, pos: at }, index) => {\n // Between two blocks: the boundary, where neither one's text is.\n if (index > 0) add('\\n', at, at)\n walk(child, at)\n })\n }\n walk(block.node, block.pos)\n return { text, starts, ends }\n}\n\n/** The lists whose nested items the wire holds flat, after the item they are in. */\nconst LISTS = new Set(['bulletList', 'orderedList'])\n\nfunction childrenOf(node: ProseMirrorNode, pos: number): { node: ProseMirrorNode; pos: number }[] {\n const out: { node: ProseMirrorNode; pos: number }[] = []\n node.forEach((child, offset) => void out.push({ node: child, pos: pos + 1 + offset }))\n return out\n}\n\n/** A list's items as the wire lists them: each one, then the items of a list inside it. */\nfunction itemsOf(list: ProseMirrorNode, pos: number): { node: ProseMirrorNode; pos: number }[] {\n return childrenOf(list, pos).flatMap((item) => [item, ...childrenOf(item.node, item.pos).flatMap((c) => (LISTS.has(c.node.type.name) ? itemsOf(c.node, c.pos) : []))])\n}\n\n/** Where `words` sits in `text` at or after `from`: the occurrence whose context matches, else the first. */\nfunction find(text: string, words: string, from: number, context: (at: number) => boolean): number {\n let first = -1\n for (let at = text.indexOf(words, from); at !== -1; at = text.indexOf(words, at + 1)) {\n if (first === -1) first = at\n if (context(at)) return at\n }\n return first\n}\n\n/**\n * The run as \u00A713.3 reads it: the parent holding most of its listed blocks, and\n * every block there from the earliest listed one to the latest. Null when none\n * is left.\n */\nfunction runIn(doc: ProseMirrorNode, places: Map<string, Place>, ids: readonly string[]): Place[] | null {\n const present = ids.map((id) => places.get(id)).filter((p): p is Place => !!p)\n if (present.length === 0) return null\n const byParent = new Map<number, Place[]>()\n for (const p of present) byParent.set(p.parent, [...(byParent.get(p.parent) ?? []), p])\n const group = [...byParent.values()].reduce((best, one) => (one.length > best.length ? one : best))\n const low = Math.min(...group.map((p) => p.index))\n const high = Math.max(...group.map((p) => p.index))\n // `parent` is where the parent's content starts: 0 for the document itself.\n const contentStart = group[0].parent\n const parent = contentStart === 0 ? doc : doc.nodeAt(contentStart - 1)\n if (!parent) return group\n const run: Place[] = []\n parent.forEach((node, offset, index) => {\n if (index >= low && index <= high) run.push({ node, pos: contentStart + offset, parent: contentStart, index })\n })\n return run\n}\n\n/** Where a comment is in this document. */\nfunction placeOf(doc: ProseMirrorNode, anchor: CommentAnchor, places = placesIn(doc)): CommentPlace {\n const run = runIn(doc, places, anchor.blocks)\n if (!run) return { state: 'detached' }\n const from = run[0].pos\n const to = run[run.length - 1].pos + run[run.length - 1].node.nodeSize\n const { quote } = anchor\n if (!quote) return { state: 'resolved', from, to, words: false }\n\n const reworded: CommentPlace = { state: 'reworded', from, to }\n const firstId = anchor.blocks[0]\n const lastId = anchor.blocks[anchor.blocks.length - 1]\n const first = run.findIndex((p) => p.node.attrs.blockId === firstId)\n const last = run.findIndex((p) => p.node.attrs.blockId === lastId)\n if (first === -1 || last === -1 || last < first) return reworded\n const a = textOf(run[first])\n const b = first === last ? a : textOf(run[last])\n // Context longer than a writer ever sends is a stranger's, and ignored, as the protocol's `resolveCommentAnchor` does.\n const prefix = quote.prefix && quote.prefix.length <= QUOTE_CONTEXT_LENGTH ? quote.prefix : undefined\n const suffix = quote.suffix && quote.suffix.length <= QUOTE_CONTEXT_LENGTH ? quote.suffix : undefined\n const before = (text: string, i: number) => !prefix || text.slice(Math.max(0, i - prefix.length), i) === prefix\n const after = (text: string, i: number) => !suffix || text.slice(i, i + suffix.length) === suffix\n\n if (quote.end === undefined) {\n const at = find(a.text, quote.start, 0, (i) => before(a.text, i) && after(a.text, i + quote.start.length))\n if (at === -1 || quote.start === '') return reworded\n return { state: 'resolved', from: a.starts[at], to: a.ends[at + quote.start.length - 1], words: true }\n }\n const startAt = find(a.text, quote.start, 0, (i) => before(a.text, i))\n if (startAt === -1 || quote.start === '') return reworded\n const endFrom = first === last ? startAt + quote.start.length : 0\n const endAt = find(b.text, quote.end, endFrom, (i) => after(b.text, i + quote.end!.length))\n if (endAt === -1 || quote.end === '') return reworded\n return { state: 'resolved', from: a.starts[startAt], to: b.ends[endAt + quote.end.length - 1], words: true }\n}\n\ndeclare module '@tiptap/core' {\n interface EditorEvents {\n /** A comment's highlight was clicked: `editor.on('commentSelect', ({ id }) => \u2026)`. */\n commentSelect: { id: string }\n }\n}\n\nexport interface CommentHighlightsOptions {\n /** A highlight was clicked: the thread to show. Or listen for the editor's `commentSelect`. */\n onSelect: ((id: string) => void) | null\n}\n\n/** The extension an editor registers to draw comments where they are. */\nexport const CommentHighlights = Extension.create<CommentHighlightsOptions>({\n name: 'commentHighlights',\n\n addOptions() {\n return { onSelect: null }\n },\n\n addProseMirrorPlugins() {\n const options = this.options\n const editor = this.editor\n return [\n new Plugin<HighlightState>({\n key: commentHighlightsKey,\n state: {\n init: () => ({ anchors: [], active: null }),\n apply(tr, previous) {\n const meta = tr.getMeta(commentHighlightsKey) as HighlightState | undefined\n return meta ?? previous\n },\n },\n props: {\n decorations(state) {\n const { anchors, active } = commentHighlightsKey.getState(state) ?? { anchors: [], active: null }\n const places = placesIn(state.doc)\n const drawn = anchors.flatMap((anchor) => {\n const place = placeOf(state.doc, anchor, places)\n if (place.state !== 'resolved') return []\n const attrs = { class: anchor.id === active ? COMMENT_HIGHLIGHT_CLASSES.active : COMMENT_HIGHLIGHT_CLASSES.rest, 'data-comment-id': anchor.id }\n if (place.words) return [Decoration.inline(place.from, place.to, attrs)]\n // Whole blocks: each block of the run carries the look itself.\n const blocks: Decoration[] = []\n state.doc.nodesBetween(place.from, place.to, (node, pos) => {\n if (pos < place.from || pos + node.nodeSize > place.to) return true\n blocks.push(Decoration.node(pos, pos + node.nodeSize, attrs))\n return false\n })\n return blocks\n })\n return drawn.length ? DecorationSet.create(state.doc, drawn) : null\n },\n handleClick(view, pos) {\n const { anchors } = commentHighlightsKey.getState(view.state) ?? { anchors: [] }\n const places = placesIn(view.state.doc)\n // The narrowest drawn comment under the click: words before the paragraph around them.\n let hit: { id: string; size: number } | null = null\n for (const anchor of anchors) {\n const place = placeOf(view.state.doc, anchor, places)\n if (place.state !== 'resolved' || pos < place.from || pos >= place.to) continue\n const size = place.to - place.from\n if (!hit || size < hit.size) hit = { id: anchor.id, size }\n }\n if (hit) {\n options.onSelect?.(hit.id)\n editor.emit('commentSelect', { id: hit.id })\n }\n return false\n },\n },\n }),\n ]\n },\n})\n\n/** Draw these comments, `active` the one being read. */\nexport function setCommentAnchors(editor: Editor, anchors: readonly CommentAnchor[], active: string | null = null) {\n if (editor.isDestroyed) return\n editor.view.dispatch(editor.state.tr.setMeta(commentHighlightsKey, { anchors, active }))\n}\n\n/** Where a comment is now: on its words or blocks, beside its blocks with its words gone, or detached. */\nexport function commentPlace(editor: Editor, anchor: CommentAnchor): CommentPlace {\n return placeOf(editor.state.doc, anchor)\n}\n\n/**\n * What a comment's card stands beside: its drawn highlight, or \u2014 its words\n * gone \u2014 its first block. Null when it is detached.\n */\nexport function commentElement(editor: Editor, anchor: CommentAnchor): HTMLElement | null {\n const drawn = editor.view.dom.querySelector<HTMLElement>(`[data-comment-id=\"${CSS.escape(anchor.id)}\"]`)\n if (drawn) return drawn\n const place = placeOf(editor.state.doc, anchor)\n if (place.state === 'detached') return null\n const dom = editor.view.nodeDOM(place.from)\n return dom instanceof HTMLElement ? dom : null\n}\n\n/** A quote in one line, as a card says it: its start and end words around an ellipsis. */\nexport function quoteText(quote: CommentQuote): string {\n return quote.end ? `${quote.start} \u2026 ${quote.end}` : quote.start\n}\n\n/** At most `length` characters from the front of `text`, cut back to a word when one is near. */\nfunction headOf(text: string, length: number): string {\n if (text.length <= length) return text\n const cut = text.lastIndexOf(' ', length)\n return text.slice(0, cut > length / 2 ? cut : length)\n}\n\n/** At most `length` characters from the back of `text`, cut forward to a word when one is near. */\nfunction tailOf(text: string, length: number): string {\n if (text.length <= length) return text\n const from = text.length - length\n const cut = text.indexOf(' ', from)\n return text.slice(cut !== -1 && cut < from + length / 2 ? cut + 1 : from)\n}\n\nfunction occurrences(text: string, words: string): number {\n let count = 0\n for (let at = text.indexOf(words); words && at !== -1; at = text.indexOf(words, at + 1)) count++\n return count\n}\n\n/** How many characters of `block`'s text come before document position `pos`. */\nfunction offsetIn(block: { starts: number[] }, pos: number): number {\n const at = block.starts.findIndex((start) => start >= pos)\n return at === -1 ? block.starts.length : at\n}\n\n/** What a comment on the selection would carry: its run, and its words unless it covers whole blocks. */\nexport interface SelectionAnchor {\n blocks: string[]\n quote?: CommentQuote\n}\n\n/**\n * The anchor a comment on the selection carries, as \u00A713.6 writes it: the\n * selected blocks, and the selected words in one block or the words where it\n * starts and ends across several. No quote when whole blocks are selected.\n * Null when nothing is selected or a selected block has no id.\n */\nexport function anchorOfSelection(editor: Editor): SelectionAnchor | null {\n const { doc, selection } = editor.state\n if (selection.empty) return null\n const { $from, $to } = selection\n const places = placesIn(doc)\n // The block with an id at or around `depth`: the lines of a quote or a list\n // item are paragraphs with no id of their own, and belong to it.\n const around = (depth: number): Place | undefined => {\n for (let d = depth; d > 0; d--) {\n const id = $from.node(d).attrs.blockId\n if (typeof id === 'string' && id && places.has(id)) return places.get(id)\n }\n return undefined\n }\n // The blocks the selection runs across: children of the deepest node holding\n // both ends, or \u2014 both ends in one textblock, or in blocks with no ids \u2014 the\n // block with an id around them.\n let run: Place[]\n if ($from.parent === $to.parent && $from.parent.isTextblock) {\n const found = around($from.depth)\n if (!found) return null\n run = [found]\n } else {\n const depth = $from.sharedDepth($to.pos)\n const low = $from.index(depth)\n const high = $to.pos >= $to.end(depth) ? $from.node(depth).childCount - 1 : $to.index(depth)\n run = []\n for (let i = low; i <= high; i++) {\n const id = $from.node(depth).child(i).attrs.blockId\n const place = typeof id === 'string' ? places.get(id) : undefined\n if (!place) {\n const found = around(depth)\n if (!found) return null\n run = [found]\n break\n }\n run.push(place)\n }\n }\n let firstText = textOf(run[0])\n let lastText = run.length === 1 ? firstText : textOf(run[run.length - 1])\n let start = offsetIn(firstText, selection.from)\n let end = offsetIn(lastText, selection.to)\n // A block the selection only touches at its edge holds none of it: it is not\n // in the run. The same rule as the protocol's `selectionAnchorTags`.\n if (run.length > 1 && start >= firstText.text.length) ((run = run.slice(1)), (firstText = textOf(run[0])), (start = 0))\n if (run.length > 1 && end <= 0) ((run = run.slice(0, -1)), (lastText = textOf(run[run.length - 1])), (end = lastText.text.length))\n if (run.length === 1) lastText = firstText\n // Between two blocks, with no character selected: nothing to comment on.\n if (run.length === 1 && firstText.text && start >= end) return null\n // Only a line break, or the edge between two lines of one block: no word to comment on either.\n if (run.length === 1 && firstText.text && !firstText.text.slice(start, end).replace(/\\n/g, '')) return null\n const blocks = run.map((p) => p.node.attrs.blockId as string)\n if (start === 0 && end >= lastText.text.length) return { blocks }\n\n const single = run.length === 1\n const quote: CommentQuote = { start: '' }\n if (single && end - start <= QUOTE_WHOLE_MAX) {\n quote.start = firstText.text.slice(start, end)\n } else {\n const startWords = single ? firstText.text.slice(start, end) : firstText.text.slice(start)\n const endWords = single ? startWords : lastText.text.slice(0, end)\n quote.start = headOf(startWords, QUOTE_END_LENGTH)\n quote.end = tailOf(endWords, QUOTE_END_LENGTH)\n }\n if (!quote.start || quote.end === '') return { blocks }\n const prefix = firstText.text.slice(Math.max(0, start - QUOTE_CONTEXT_LENGTH), start)\n const suffix = lastText.text.slice(end, end + QUOTE_CONTEXT_LENGTH)\n if (prefix && occurrences(firstText.text, quote.start) > 1) quote.prefix = prefix\n if (suffix && occurrences(lastText.text, quote.end ?? quote.start) > 1) quote.suffix = suffix\n return { blocks, quote }\n}\n", "import { Extension, type JSONContent } from '@tiptap/core'\nimport { Slice, type ResolvedPos } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\n\nexport interface PastedMarkdownOptions {\n /**\n * Plain text read as the blocks it spells, as editor JSON (`{ type: 'doc',\n * content }`), or `undefined` to paste it as text. The app passes its\n * protocol's reader \u2014 for a block document, `@estiva-app/protocol`'s\n * `descriptionTextToBlockDocument` through `toEditorDocument` \u2014 so a paste\n * reads text exactly as the agent's write of the same text does.\n */\n read: (text: string) => JSONContent | undefined\n}\n\n/** Inside a table cell: a pasted table there stays text, never a table in a table. */\nfunction inTableCell($context: ResolvedPos): boolean {\n for (let depth = $context.depth; depth > 0; depth--) {\n const role = $context.node(depth).type.spec.tableRole\n if (role === 'cell' || role === 'header_cell') return true\n }\n return false\n}\n\nconst hasTable = (blocks: JSONContent[]): boolean => blocks.some((block) => block.type === 'table' || hasTable(block.content ?? []))\n\n/**\n * Markdown pasted as plain text lands as what it spells: a heading, a list, a\n * checklist, a quote or callout, a table (LEAF-10; Miky, 2026-10-15). Only a\n * paste with no HTML on the clipboard is read \u2014 a copy from a web page already\n * pastes its own structure \u2014 and a paste that spells nothing but paragraphs\n * pastes exactly as before. Ctrl/Cmd+Shift+V, the plain-text paste, keeps the\n * text as typed, and so does a paste into code.\n *\n * For an editor that saves a block document. A message box leaves it out: a\n * message's text has no table (SPEC \u00A713.2), so a pasted table stays text there.\n */\nexport const PastedMarkdown = Extension.create<PastedMarkdownOptions>({\n name: 'pastedMarkdown',\n addOptions() {\n return { read: () => undefined }\n },\n addProseMirrorPlugins() {\n const options = this.options\n return [\n new Plugin({\n key: new PluginKey('pastedMarkdown'),\n props: {\n // Reached only for a text paste outside code; `plain` is the Shift paste.\n clipboardTextParser: (text, $context, plain, view) => {\n if (plain) return undefined as unknown as Slice\n try {\n const blocks = options.read(text.replace(/\\r\\n?/g, '\\n'))?.content ?? []\n // Paragraphs only: the editor's own paste keeps each line a paragraph, and its paste rules make `**bold**` bold.\n if (blocks.every((block) => block.type === 'paragraph')) return undefined as unknown as Slice\n if (inTableCell($context) && hasTable(blocks)) return undefined as unknown as Slice\n return Slice.maxOpen(view.state.schema.nodeFromJSON({ type: 'doc', content: blocks }).content)\n } catch {\n // A reader that throws, or a block this editor's schema does not\n // hold (a table without TableKit): paste the text.\n return undefined as unknown as Slice\n }\n },\n },\n }),\n ]\n },\n})\n", "/** The editor's code block, coloured by language like RichText's (`@estiva-app/ui/editor`). */\nimport { CodeBlockLowlight } from '@tiptap/extension-code-block-lowlight'\nimport { lowlight } from './codeColours'\n\n/*\n The editor library guesses a language for a block that names none, or names\n one it does not know, and colours it by the guess. RichText never guesses, so\n that block was coloured while written and plain once read. A block is\n coloured only by the language it names, while written and when read\n (Katerina, 9 October: never guess).\n*/\nconst namedOnly = {\n highlight: (language: string, value: string) => lowlight().highlight(language, value),\n highlightAuto: (value: string) => ({ type: 'root' as const, children: [{ type: 'text' as const, value }], data: { language: undefined, relevance: 0 } }),\n listLanguages: () => lowlight().listLanguages(),\n registered: (language: string) => lowlight().registered(language),\n}\n\n/**\n * A code block in the editor, with the colours RichText reads it in (Katerina,\n * 9 October): the same highlight.js languages, the same classes, and the\n * editor's root wears `richTextClassName`, which colours them.\n *\n * It replaces the starter kit's code block: `StarterKit.configure({ codeBlock: false })`,\n * then add `CodeBlockColours`. The block keeps its name, `codeBlock`, and its\n * `language` attribute, so nothing already written changes.\n */\nexport const CodeBlockColours = CodeBlockLowlight.configure({ lowlight: namedOnly })\n", "import { createElement, type ReactNode } from 'react'\nimport { common, createLowlight } from 'lowlight'\n\n/**\n * Colours inside a code block, by language (Katerina, 9 October).\n *\n * highlight.js reads the code and names each word (a keyword, a string, a\n * comment); RichText's class list gives each name its colour from the theme's\n * `syntax-*` tokens. The same instance colours the editor's code block\n * (`CodeBlockColours`), so what is written looks the same as what is read.\n *\n * `common` is highlight.js's 37 everyday languages. A language outside them, or\n * none, leaves the code in one colour.\n *\n * Made the first time code is coloured, not when the package loads: a call at\n * the top of the file is kept by every app's bundler, so an app that never draws\n * code carried highlight.js too (measured: an app importing only `Link` was\n * 55 KB gzipped).\n */\nlet instance: ReturnType<typeof createLowlight> | undefined\nexport function lowlight() {\n return (instance ??= createLowlight(common))\n}\n\ninterface HastNode {\n type: string\n value?: string\n properties?: { className?: string[] }\n children?: HastNode[]\n}\n\nfunction draw(node: HastNode, key: number): ReactNode {\n if (node.type === 'text') return node.value\n return createElement('span', { key, className: node.properties?.className?.join(' ') }, (node.children ?? []).map(draw))\n}\n\n/** The code, its words wrapped in highlight.js's classes; the text as it is when the language is unknown. */\nexport function codeColours(text: string, language?: string): ReactNode {\n if (!language || !lowlight().registered(language)) return text\n return (lowlight().highlight(language, text).children as HastNode[]).map(draw)\n}\n", "import { useMemo, type ReactNode } from 'react'\nimport type { Editor } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport type { EditorView } from '@tiptap/pm/view'\nimport { IconCopy, IconTrash } from '@tabler/icons-react'\nimport { BlockHandle, blockAtY, type BlockHandleEditing, type HandleBlock } from './BlockHandle'\nimport { Selection } from '@tiptap/pm/state'\nimport { MenuItem, MenuSub } from './Menu'\nimport { DOCUMENT_FORMATS, FORMATS, applyFormat, type FormatId } from './ComposerTriggers'\n\n/** A row of the block menu's Turn into: what the block becomes. */\nexport interface BlockTurnInto {\n label: string\n /**\n * Turns the block. The handle puts the caret in a block of text first, so a\n * row for one can act at the caret; `pos` is where the block starts, for a\n * list or a quote, whose row acts on the whole block.\n */\n run: (editor: Editor, pos: number) => void\n /** Whether the block already is this \u2014 drawn as the selected row. */\n active?: (node: ProseMirrorNode) => boolean\n}\n\nexport interface EditorBlockHandleProps {\n /** The editor. Not editable, or not there yet, and the handle reads: the caller's rows only. */\n editor: Editor | null\n /**\n * Turn into's rows for a block. By default `turnIntoRows`, the same in every\n * app: a block of text, a list and a quote each get theirs. A list of rows\n * instead is offered for a block of text only; `[]` offers none.\n */\n turnInto?: readonly BlockTurnInto[] | ((node: ProseMirrorNode, editor: Editor) => readonly BlockTurnInto[])\n /** The caller's own rows, after the editing ones. */\n actions?: (block: HandleBlock) => ReactNode\n /** The `EditorContent`. */\n children: ReactNode\n className?: string\n}\n\n/** The editor's top-level blocks, where each starts and what it is. */\nfunction editorBlocks(view: EditorView): HandleBlock[] {\n const out: HandleBlock[] = []\n view.state.doc.forEach((node, pos) => {\n const element = view.nodeDOM(pos)\n if (element instanceof HTMLElement) out.push({ id: (node.attrs.blockId as string | null) || undefined, element, pos })\n })\n return out\n}\n\n/*\n Duplicate and Delete leave the editor focused, as Turn into and a drop do: the\n person is still in the field, so an editor that saves when they leave it saves\n these too \u2014 and one that loads someone else's edit while unfocused does not\n load it over them.\n*/\n\n/** A copy of the block straight after it, the caret in the copy. `BlockId` gives the copy a fresh id; the original keeps its own. */\nexport function duplicateBlock(editor: Editor, pos: number): boolean {\n const node = editor.state.doc.nodeAt(pos)\n if (!node) return false\n editor.view.dispatch(editor.state.tr.insert(pos + node.nodeSize, node).scrollIntoView())\n editor.commands.focus(pos + node.nodeSize + 1)\n return true\n}\n\n/** Removes the block, the caret where it was. The last block of a document becomes an empty paragraph, since a document holds at least one. */\nexport function deleteBlock(editor: Editor, pos: number): boolean {\n const { state } = editor\n const node = state.doc.nodeAt(pos)\n if (!node) return false\n const tr = state.doc.childCount === 1 ? state.tr.replaceWith(pos, pos + node.nodeSize, state.schema.nodes.paragraph.create()) : state.tr.delete(pos, pos + node.nodeSize)\n editor.view.dispatch(tr)\n editor.commands.focus(Math.min(pos + 1, editor.state.doc.content.size))\n return true\n}\n\n/**\n * Moves the block at `from` to `to` (a position between top-level blocks), the\n * caret in it: what a drop in the gutter does, where the editor has no drop of\n * its own. The node moves whole, attributes and all, so it keeps its id, as\n * ProseMirror's drop keeps it.\n */\nexport function moveBlock(editor: Editor, from: number, to: number): boolean {\n const node = editor.state.doc.nodeAt(from)\n if (!node || (to >= from && to <= from + node.nodeSize)) return false\n const tr = editor.state.tr.delete(from, from + node.nodeSize)\n const at = tr.mapping.map(to)\n editor.view.dispatch(tr.insert(at, node).scrollIntoView())\n editor.commands.focus(at + 1)\n return true\n}\n\n/**\n * Starts the browser's own drag of the block, as ProseMirror starts one of a\n * selected node: the block selected, its slice on `view.dragging` with `move`,\n * and its HTML on the transfer. ProseMirror's drop then deletes the selection\n * and inserts the slice with its attributes \u2014 so the block arrives with the\n * id it left with, and every comment anchored to it still finds it.\n */\nexport function startBlockDrag(editor: Editor, pos: number, event: Pick<globalThis.DragEvent, 'dataTransfer'>, image?: Element) {\n editor.commands.setNodeSelection(pos)\n const { view } = editor\n const slice = view.state.selection.content()\n const { dom, text } = view.serializeForClipboard(slice)\n const transfer = event.dataTransfer\n if (transfer) {\n transfer.clearData()\n transfer.setData('text/html', dom.innerHTML)\n transfer.setData('text/plain', text)\n transfer.effectAllowed = 'copyMove'\n if (image) transfer.setDragImage(image, 0, 0)\n }\n view.dragging = { slice, move: true }\n}\n\n/**\n * The drop line a dragged block shows, in the package's accent instead of the\n * editor's default (the text's colour). Give it to the editor's StarterKit:\n * `StarterKit.configure({ dropcursor: blockDropCursor })`.\n */\nexport const blockDropCursor = { color: false, class: 'bg-accent-primary' } as const\n\nconst NOTHING_YET: BlockHandleEditing = { find: () => null, rows: () => null, startDrag: () => {}, drop: () => {}, endDrag: () => {}, onChange: () => () => {} }\n\n/**\n * `BlockHandle` in an editor: drag the handle to move the block, and the menu\n * gains Turn into, Duplicate and Delete before the caller's rows.\n */\nexport function EditorBlockHandle({ editor, turnInto = turnIntoRows, actions, children, className }: EditorBlockHandleProps) {\n const editing = useMemo<BlockHandleEditing>(() => {\n // Before the editor exists there is no block to find \u2014 not the editor's whole element read as one.\n if (!editor) return NOTHING_YET\n // Where the block being dragged starts.\n let dragged: number | undefined\n return {\n find: (y) => blockAtY(editorBlocks(editor.view), y),\n rows: (block) => {\n const pos = block.pos\n // Not editable: the caller's rows only, and no drag.\n if (!editor.isEditable) return null\n const node = pos === undefined ? null : editor.state.doc.nodeAt(pos)\n if (pos === undefined || !node) return null\n const turnRows = typeof turnInto === 'function' ? turnInto(node, editor) : node.isTextblock ? turnInto : []\n return (\n <>\n {turnRows.length > 0 && (\n <MenuSub label=\"Turn into\">\n {turnRows.map((row) => (\n <MenuItem\n key={row.label}\n label={row.label}\n selected={row.active?.(node) ?? false}\n onClick={() => {\n // Inside a block of text, so a row's command at the caret turns this block and no other.\n if (node.isTextblock) editor.chain().focus().setTextSelection(pos + 1).run()\n row.run(editor, pos)\n }}\n />\n ))}\n </MenuSub>\n )}\n <MenuItem label=\"Duplicate\" leading={<IconCopy size={16} stroke={1.5} className=\"text-text-secondary\" />} onClick={() => duplicateBlock(editor, pos)} />\n <MenuItem label=\"Delete\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={() => deleteBlock(editor, pos)} />\n </>\n )\n },\n startDrag: (block, event) => {\n dragged = block.pos\n if (block.pos !== undefined) startBlockDrag(editor, block.pos, event, block.element)\n },\n drop: (target, after) => {\n const node = target.pos === undefined ? null : editor.state.doc.nodeAt(target.pos)\n if (dragged === undefined || target.pos === undefined || !node) return\n moveBlock(editor, dragged, after ? target.pos + node.nodeSize : target.pos)\n },\n // ProseMirror clears `dragging` on its own dragend, which a drag started outside its element never reaches.\n endDrag: () => setTimeout(() => (editor.view.dragging = null), 50),\n onChange: (changed) => {\n editor.on('update', changed)\n return () => {\n editor.off('update', changed)\n }\n },\n }\n }, [editor, turnInto])\n\n return (\n <BlockHandle editing={editing} actions={actions} className={className}>\n {children}\n </BlockHandle>\n )\n}\n\nconst LISTS = ['bulletList', 'orderedList']\nconst isList = (node: ProseMirrorNode) => LISTS.includes(node.type.name)\n\n/** Every item of a list, the ones nested under an item too \u2014 the editor nests what \u00A713.3 keeps flat (MAN-13). */\nfunction listItems(list: ProseMirrorNode, at: number): { node: ProseMirrorNode; pos: number }[] {\n const out: { node: ProseMirrorNode; pos: number }[] = []\n list.descendants((node, pos) => {\n if (node.type.name === 'listItem') out.push({ node, pos: at + 1 + pos })\n })\n return out\n}\n\nconst isChecklistItem = ({ node }: { node: ProseMirrorNode }) => typeof node.attrs.checked === 'boolean'\n/** Whether every item of the list is a checklist item. */\nconst isChecklist = (list: ProseMirrorNode) => listItems(list, 0).every(isChecklistItem)\n/** A list of that type with no checklist item in it \u2014 a list partly ticked is neither, so no row reads as \"nothing changes\". */\nconst isPlainList = (list: ProseMirrorNode, type: string) => list.type.name === type && !listItems(list, 0).some(isChecklistItem)\n\nconst hasExtension = (editor: Editor, name: string) => editor.extensionManager.extensions.some((e) => e.name === name)\n\n/** The caret back in the block, the editor still focused \u2014 as Duplicate and Delete leave it, so a save on leaving saves this too. */\nfunction caretInto(editor: Editor, pos: number) {\n const { state } = editor\n editor.view.dispatch(state.tr.setSelection(Selection.near(state.doc.resolve(Math.min(pos + 1, state.doc.content.size)))))\n editor.commands.focus()\n}\n\nexport type ListKind = 'bulletList' | 'orderedList' | 'checklist' | 'text'\n\n/**\n * Turns the whole list at `pos`, every item, the nested ones too.\n *\n * - **Bulleted, Numbered:** the list's own type changes and its attributes\n * stay, so it keeps its id; every item's tick goes. Not Tiptap's\n * `toggleList`, which makes the list anew \u2014 a fresh id, detaching every\n * comment anchored to it \u2014 and then joins it into a list of that type next\n * to it.\n * - **Checklist:** every item a checklist item, the list's type as it was; an\n * item already one keeps its tick.\n *\n * The kind it already is changes nothing \u2014 no edit, no undo step.\n * - **Text:** each item becomes a paragraph that takes the item's id, as\n * lifting an item out does (MAN-12). The list's own id goes with the list.\n *\n * `false` when there is no list at `pos`.\n */\nexport function turnListInto(editor: Editor, pos: number, kind: ListKind): boolean {\n const { state } = editor\n const list = state.doc.nodeAt(pos)\n if (!list || !isList(list)) return false\n const tr = state.tr\n if (kind === 'text') {\n const blocks: ProseMirrorNode[] = []\n for (const { node: item } of listItems(list, pos)) {\n item.forEach((child, _offset, index) => {\n // Its nested list's items are in `listItems` already.\n if (isList(child)) return\n // The item's first block takes its id; any other gets one of its own from `BlockId`.\n blocks.push(child.type.create({ ...child.attrs, blockId: index === 0 ? item.attrs.blockId : null }, child.content, child.marks))\n })\n }\n tr.replaceWith(pos, pos + list.nodeSize, blocks)\n } else {\n // A checklist stays the list type it is: \u00A713.3 ticks items of either.\n const type = kind === 'checklist' ? list.type : state.schema.nodes[kind]\n // The list and the lists nested in it, one type throughout: \u00A713.3's indented items are their list's type.\n if (list.type !== type) tr.setNodeMarkup(pos, type, list.attrs)\n list.descendants((node, at) => {\n if (isList(node) && node.type !== type) tr.setNodeMarkup(pos + 1 + at, type, node.attrs)\n })\n for (const { node, pos: at } of listItems(list, pos)) {\n const checked = kind === 'checklist' ? (typeof node.attrs.checked === 'boolean' ? node.attrs.checked : false) : null\n if (node.attrs.checked !== checked) tr.setNodeAttribute(at, 'checked', checked)\n }\n }\n // The row it already is changes nothing: no edit to save, no step to undo.\n if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView())\n caretInto(editor, pos)\n return true\n}\n\nexport type QuoteKind = 'quote' | 'note' | 'warning' | 'text'\n\n/**\n * Turns the quote at `pos`: a plain quote, a Note or Warning callout (the\n * tone changes, the id stays), or its text, whose first paragraph takes the\n * quote's id, as lifting it out does (MAN-12). `false` when there is no quote\n * at `pos`.\n */\nexport function turnQuoteInto(editor: Editor, pos: number, kind: QuoteKind): boolean {\n const { state } = editor\n const quote = state.doc.nodeAt(pos)\n if (!quote || quote.type.name !== 'blockquote') return false\n const tr = state.tr\n if (kind === 'text') {\n const blocks: ProseMirrorNode[] = []\n quote.forEach((child) => blocks.push(blocks.length === 0 ? child.type.create({ ...child.attrs, blockId: quote.attrs.blockId }, child.content, child.marks) : child))\n tr.replaceWith(pos, pos + quote.nodeSize, blocks)\n } else {\n const tone = kind === 'quote' ? null : kind\n if ((quote.attrs.tone ?? null) !== tone) tr.setNodeAttribute(pos, 'tone', tone)\n }\n if (tr.docChanged) editor.view.dispatch(tr.scrollIntoView())\n caretInto(editor, pos)\n return true\n}\n\nfunction isFormat(node: ProseMirrorNode, id: FormatId): boolean {\n if (id === 'paragraph') return node.type.name === 'paragraph'\n if (id === 'heading') return node.type.name === 'heading' && node.attrs.level === 1\n if (id === 'subheading') return node.type.name === 'heading' && node.attrs.level === 2\n if (id === 'code') return node.type.name === 'codeBlock'\n return false\n}\n\n/**\n * The block menu's Turn into for one block, the same in every app (Miky,\n * LEAF-11's kickoff, 15 October):\n *\n * - **A block of text** \u2014 a paragraph, a heading, code: the `/` menu's Format\n * rows, code as a block, and Checklist, Note and Warning where the editor\n * has `Checklist` and `Callout`.\n * - **A list:** Bulleted list, Numbered list, Checklist (with `Checklist`), Text.\n * - **A quote:** Quote, Note, Warning (with `Callout`), Text.\n *\n * Anything else \u2014 a table, an attachment \u2014 none. Each keeps the block's text\n * and its id, and so the comments anchored to it.\n */\nexport function turnIntoRows(node: ProseMirrorNode, editor: Editor): readonly BlockTurnInto[] {\n const checklist = hasExtension(editor, 'checklist')\n const callout = hasExtension(editor, 'callout')\n if (node.isTextblock) {\n const document = DOCUMENT_FORMATS.filter((f) => (f.id === 'checklist' ? checklist : callout))\n return [...FORMATS, ...document].map((format) => ({\n label: format.label,\n run: (e) => void applyFormat(e, format.id, 'block'),\n active: (n) => isFormat(n, format.id),\n }))\n }\n if (isList(node)) {\n const rows: BlockTurnInto[] = [\n { label: 'Bulleted list', run: (e, pos) => void turnListInto(e, pos, 'bulletList'), active: (n) => isPlainList(n, 'bulletList') },\n { label: 'Numbered list', run: (e, pos) => void turnListInto(e, pos, 'orderedList'), active: (n) => isPlainList(n, 'orderedList') },\n ]\n if (checklist) rows.push({ label: 'Checklist', run: (e, pos) => void turnListInto(e, pos, 'checklist'), active: isChecklist })\n rows.push({ label: 'Text', run: (e, pos) => void turnListInto(e, pos, 'text') })\n return rows\n }\n if (node.type.name === 'blockquote') {\n const rows: BlockTurnInto[] = [{ label: 'Quote', run: (e, pos) => void turnQuoteInto(e, pos, 'quote'), active: (n) => !n.attrs.tone }]\n if (callout) {\n rows.push({ label: 'Note', run: (e, pos) => void turnQuoteInto(e, pos, 'note'), active: (n) => n.attrs.tone === 'note' })\n rows.push({ label: 'Warning', run: (e, pos) => void turnQuoteInto(e, pos, 'warning'), active: (n) => n.attrs.tone === 'warning' })\n }\n rows.push({ label: 'Text', run: (e, pos) => void turnQuoteInto(e, pos, 'text') })\n return rows\n }\n return []\n}\n", "import { useCallback, useEffect, useRef, useState, type MouseEvent, type ReactNode } from 'react'\nimport type { Editor } from '@tiptap/core'\nimport { TextSelection, type Command } from '@tiptap/pm/state'\nimport { addColumnAfter, addColumnBefore, addRowAfter, addRowBefore, deleteColumn, deleteRow, deleteTable, toggleHeader } from '@tiptap/pm/tables'\nimport { IconCheck, IconColumnInsertLeft, IconColumnInsertRight, IconGripHorizontal, IconGripVertical, IconPlus, IconRowInsertBottom, IconRowInsertTop, IconTableRow, IconTrash } from '@tabler/icons-react'\nimport { cn } from './cn'\nimport { IconButton } from './IconButton'\nimport { FLOATING_SURFACE_CLASSES } from './looks'\nimport { Menu, MenuItem, MenuSeparator } from './Menu'\n\nexport interface EditorTableControlsProps {\n /** The editor, with TableKit (`@tiptap/extension-table`) in its extensions. Not editable, or not there yet: no controls. */\n editor: Editor | null\n /** The `EditorContent`. */\n children: ReactNode\n className?: string\n}\n\n/** The cell the pointer is on, and the table and row it is in. */\ninterface Hovered {\n table: HTMLTableElement\n row: HTMLTableRowElement\n cell: HTMLTableCellElement\n}\n\n/** Where the controls go, measured from the frame: they depend on the document, not on a size of ours. */\ninterface Placed {\n tableBox: { top: number; left: number; width: number; height: number }\n rowBox: { top: number; height: number }\n columnBox: { left: number; width: number }\n}\n\n/*\n Every row runs the table command with the caret in a cell, as the command\n expects \u2014 the hovered cell's, or for a \u2795 bar the last row's or the last\n column's \u2014 and leaves the editor focused there, as the block menu does: the\n person is still in the field, so an editor that saves when they leave it\n saves this too.\n*/\n\n/** Puts the caret in `cell` and runs `command` there. */\nfunction inCell(editor: Editor, cell: HTMLTableCellElement, command: Command): boolean {\n const { view } = editor\n if (!view.dom.contains(cell)) return false\n const at = view.posAtDOM(cell, 0)\n view.dispatch(view.state.tr.setSelection(TextSelection.near(view.state.doc.resolve(at))))\n const done = command(view.state, view.dispatch, view)\n editor.commands.focus()\n return done\n}\n\n/** A row of header cells only: the table's header row. */\nfunction isHeaderRow(row: HTMLTableRowElement): boolean {\n return row.cells.length > 0 && Array.from(row.cells).every((c) => c.tagName === 'TH')\n}\n\n/**\n * The cell's row, or the whole table when it is its only one: a table holds at\n * least one row (prosemirror-tables refuses to delete it). Deleting the header\n * row makes the next row the header, so the table still opens with one.\n */\nexport function deleteTableRow(editor: Editor, cell: HTMLTableCellElement): boolean {\n const row = cell.closest('tr')\n const table = cell.closest('table')\n if (!row || !table || table.rows.length <= 1) return inCell(editor, cell, deleteTable)\n const header = isHeaderRow(row)\n return inCell(editor, cell, header ? (state, dispatch, view) => deleteRow(state, dispatch) && (!view || toggleHeader('row')(view.state, view.dispatch)) : deleteRow)\n}\n\n/**\n * The table's first row becomes its header row, or an ordinary row again:\n * whichever cell of the table `cell` is. A table with no header row has no\n * text spelling, so the agent keeps it as written (SPEC \u00A713.3, \"No spelling\").\n */\nexport function toggleTableHeaderRow(editor: Editor, cell: HTMLTableCellElement): boolean {\n return inCell(editor, cell, toggleHeader('row'))\n}\n\n/** The same for a column: the last one deletes the table. */\nexport function deleteTableColumn(editor: Editor, cell: HTMLTableCellElement): boolean {\n const row = cell.closest('tr')\n return inCell(editor, cell, row && row.cells.length > 1 ? deleteColumn : deleteTable)\n}\n\n/** A row after the last one: the \u2795 under the table. */\nexport function appendTableRow(editor: Editor, table: HTMLTableElement): boolean {\n const last = table.rows[table.rows.length - 1]?.cells[0]\n return !!last && inCell(editor, last, addRowAfter)\n}\n\n/** A column after the last one: the \u2795 right of the table. */\nexport function appendTableColumn(editor: Editor, table: HTMLTableElement): boolean {\n const first = table.rows[0]\n const last = first?.cells[first.cells.length - 1]\n return !!last && inCell(editor, last, addColumnAfter)\n}\n\nfunction place(frame: HTMLElement, { table, row, cell }: Hovered): Placed {\n const at = frame.getBoundingClientRect()\n const t = table.getBoundingClientRect()\n const r = row.getBoundingClientRect()\n const c = cell.getBoundingClientRect()\n return {\n tableBox: { top: t.top - at.top, left: t.left - at.left, width: t.width, height: t.height },\n rowBox: { top: r.top - at.top, height: r.height },\n columnBox: { left: c.left - at.left, width: c.width },\n }\n}\n\nconst ICON = { size: 16, stroke: 1.5, className: 'text-text-secondary' } as const\n\n/**\n * A \u2795 press keeps the focus where it is, as the selection toolbar's buttons do:\n * the person never left the field, so an editor that saves when they leave it\n * does not save half-way, and History gets one line for the edit, not one per\n * press. (A handle's menu takes the focus, as every menu does.)\n */\nconst keepFocus = (e: MouseEvent) => e.preventDefault()\n\n/** What a handle and a \u2795 bar sit in: the elevated surface's border and fill, opaque over the table's lines, with no shadow at this size. */\nconst HANDLE_BOX = cn(FLOATING_SURFACE_CLASSES, 'shadow-none')\n\n/**\n * A table's own controls in an editor, as in Notion: point at a cell and a\n * handle sits on its row's left edge and on its column's top edge; press one\n * for Insert above and below (left and right), Delete, and Delete table. The\n * first row's menu also turns the header row on and off (Header row, ticked\n * while it is on); with it off, the first row is an ordinary row. On\n * the last row a \u2795 bar under the table adds a row, and on the last column one\n * right of it adds a column. Tab in\n * the last cell adds a row too \u2014 that is TableKit's own.\n *\n * Deleting a table's only row or only column deletes the table, which cannot\n * be left with none.\n *\n * Built on the editor library's own table commands; the controls are ours.\n * Wrap the `EditorContent` in it, inside an `EditorBlockHandle` if there is\n * one: the block handle stays the table's, in the gutter.\n */\nexport function EditorTableControls({ editor, children, className }: EditorTableControlsProps) {\n const frame = useRef<HTMLDivElement>(null)\n // The cell pointed at and where its controls go, as one: the boxes mean nothing without their elements.\n const [hovered, setHovered] = useState<(Hovered & Placed) | null>(null)\n // A menu that is up keeps its row and column, wherever the pointer goes.\n const [menu, setMenu] = useState<'row' | 'column' | null>(null)\n const editable = !!editor && editor.isEditable\n\n const follow = useCallback(\n (target: EventTarget | null) => {\n if (!editor || !frame.current || !(target instanceof Element)) return\n // On a control of ours: keep what it was drawn for.\n if (target.closest('[data-table-control]')) return\n const cell = target.closest<HTMLTableCellElement>('td, th')\n const row = cell?.closest('tr')\n const table = row?.closest('table')\n if (!cell || !row || !table || !editor.view.dom.contains(table)) {\n setHovered(null)\n return\n }\n // Measured on every move, the same cell too: a panel resized or a cell's text wrapping moves the edges under a still pointer.\n const next = { table, row, cell, ...place(frame.current, { table, row, cell }) }\n setHovered((was) => (was && was.cell === cell && JSON.stringify([was.tableBox, was.rowBox, was.columnBox]) === JSON.stringify([next.tableBox, next.rowBox, next.columnBox]) ? was : next))\n },\n [editor],\n )\n\n /*\n Any change to the document moves everything under the controls, so they go\n until the pointer moves again: a row added or deleted here, and someone\n else's edit loaded into the field \u2014 which an app does without an `update`\n (`emitUpdate: false`), and which redraws the cells the controls point at.\n */\n useEffect(() => {\n if (!editor) return\n const changed = ({ transaction }: { transaction: { docChanged: boolean } }) => {\n if (transaction.docChanged && !menu) setHovered(null)\n }\n editor.on('transaction', changed)\n return () => {\n editor.off('transaction', changed)\n }\n }, [editor, menu])\n\n const shown = editable ? hovered : null\n const run = (act: () => boolean) => () => {\n if (editor) act()\n setMenu(null)\n setHovered(null)\n }\n\n return (\n <div\n ref={frame}\n className={cn('relative', className)}\n onMouseMove={(e) => {\n if (!menu) follow(e.target)\n }}\n onMouseLeave={() => {\n if (!menu) setHovered(null)\n }}\n >\n {children}\n {shown && editor && (\n <>\n {/* The row's handle, centred on the table's left edge: the box is ours, so the table's line does not show through it. */}\n <div data-table-control className={cn(HANDLE_BOX, 'absolute -translate-x-1/2 -translate-y-1/2')} style={{ left: shown.tableBox.left, top: shown.rowBox.top + shown.rowBox.height / 2 }}>\n <Menu\n open={menu === 'row'}\n onOpenChange={(open) => setMenu(open ? 'row' : null)}\n trigger={\n <IconButton aria-label=\"Row menu\" tooltip=\"Row\" className=\"h-6 w-4 p-0\">\n <IconGripVertical size={16} stroke={1.5} />\n </IconButton>\n }\n >\n {/* The header row is switched where it lives: on the first row's menu, ticked while that row is the header. */}\n {shown.row.rowIndex === 0 && (\n <>\n <MenuItem\n label=\"Header row\"\n leading={<IconTableRow {...ICON} />}\n trailing={isHeaderRow(shown.row) ? <IconCheck {...ICON} aria-hidden /> : undefined}\n onClick={run(() => toggleTableHeaderRow(editor, shown.cell))}\n />\n <MenuSeparator />\n </>\n )}\n {/* Nothing goes above a header row: it is the table's first row, and a header anywhere else is no header (RichText, the agent's text). */}\n {!isHeaderRow(shown.row) && <MenuItem label=\"Insert above\" leading={<IconRowInsertTop {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addRowBefore))} />}\n <MenuItem label=\"Insert below\" leading={<IconRowInsertBottom {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addRowAfter))} />\n <MenuSeparator />\n <MenuItem label=\"Delete\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => deleteTableRow(editor, shown.cell))} />\n <MenuItem label=\"Delete table\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => inCell(editor, shown.cell, deleteTable))} />\n </Menu>\n </div>\n {/* The column's handle, centred on the table's top edge. */}\n <div data-table-control className={cn(HANDLE_BOX, 'absolute -translate-x-1/2 -translate-y-1/2')} style={{ left: shown.columnBox.left + shown.columnBox.width / 2, top: shown.tableBox.top }}>\n <Menu\n open={menu === 'column'}\n onOpenChange={(open) => setMenu(open ? 'column' : null)}\n trigger={\n <IconButton aria-label=\"Column menu\" tooltip=\"Column\" className=\"h-4 w-6 p-0\">\n <IconGripHorizontal size={16} stroke={1.5} />\n </IconButton>\n }\n >\n <MenuItem label=\"Insert left\" leading={<IconColumnInsertLeft {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addColumnBefore))} />\n <MenuItem label=\"Insert right\" leading={<IconColumnInsertRight {...ICON} />} onClick={run(() => inCell(editor, shown.cell, addColumnAfter))} />\n <MenuSeparator />\n <MenuItem label=\"Delete\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => deleteTableColumn(editor, shown.cell))} />\n <MenuItem label=\"Delete table\" destructive leading={<IconTrash size={16} stroke={1.5} className=\"text-error-default\" />} onClick={run(() => inCell(editor, shown.cell, deleteTable))} />\n </Menu>\n </div>\n {/*\n The \u2795 bars, flush with the table so the pointer reaches them from a\n cell without leaving it \u2014 the row's from the last row, the column's\n from the last column. Anywhere else the one under the table would\n lie over the top of the next block for nothing.\n */}\n {shown.row === shown.table.rows[shown.table.rows.length - 1] && (\n <div data-table-control className={cn(HANDLE_BOX, 'absolute flex h-4')} style={{ left: shown.tableBox.left, top: shown.tableBox.top + shown.tableBox.height, width: shown.tableBox.width }}>\n <IconButton aria-label=\"Add row\" tooltip=\"Add row\" className=\"h-full w-full p-0\" onMouseDown={keepFocus} onClick={run(() => appendTableRow(editor, shown.table))}>\n <IconPlus size={12} stroke={1.5} />\n </IconButton>\n </div>\n )}\n {shown.cell === shown.row.cells[shown.row.cells.length - 1] && (\n <div data-table-control className={cn(HANDLE_BOX, 'absolute flex w-4')} style={{ left: shown.tableBox.left + shown.tableBox.width, top: shown.tableBox.top, height: shown.tableBox.height }}>\n <IconButton aria-label=\"Add column\" tooltip=\"Add column\" className=\"h-full w-full p-0\" onMouseDown={keepFocus} onClick={run(() => appendTableColumn(editor, shown.table))}>\n <IconPlus size={12} stroke={1.5} />\n </IconButton>\n </div>\n )}\n </>\n )}\n </div>\n )\n}\n", "import { useCallback, useEffect, useRef, useState, type ComponentType, type ReactNode } from 'react'\n// @estiva-escape(estiva/no-hand-rolled-behaviour): \"Your version\" is drawn into the text, in the slot ProseMirror's decoration places at its block's end; nothing floats, so no Base UI part has it.\nimport { createPortal } from 'react-dom'\nimport type { AnyExtension } from '@tiptap/core'\nimport { TextSelection } from '@tiptap/pm/state'\nimport { EditorContent, useEditor, useEditorState, type Editor, type JSONContent } from '@tiptap/react'\nimport { TableKit } from '@tiptap/extension-table'\nimport { IconCheck, IconCopy, IconMessagePlus } from '@tabler/icons-react'\nimport { ASKED_BLOCK_CLASSES, AskedBlocks, blockAt, setAskedBlocks, type AskedSlot } from './AskedBlocks'\nimport type { HandleBlock } from './BlockHandle'\nimport { AttachmentNode, BlockId, Callout, Checklist, ReferenceNode, UnknownBlock, isChecklistTick, type AttachmentViewProps, type ReferenceViewProps } from './BlockNodes'\nimport { Button } from './Button'\nimport { Card } from './Card'\nimport { cn } from './cn'\nimport { CodeBlockColours } from './CodeBlockColours'\nimport { CommentHighlights, anchorOfSelection, type SelectionAnchor } from './CommentHighlights'\nimport { PersonReference, ReferenceTrigger, SlashCommands, formatSection, typeTrigger, type MentionPerson, type ReferenceSection, type SlashCommand, type SlashSection } from './ComposerTriggers'\nimport { EditorBlockHandle, blockDropCursor } from './EditorBlockHandle'\nimport { EditorTableControls } from './EditorTableControls'\nimport { FieldLine } from './Field'\nimport { FilePicker } from './FilePicker'\nimport { LinkChips, type LinkChipsOptions } from './LinkChips'\nimport { BareLinks, DocumentKit, LINK_MARK_ATTRIBUTES, PasteOverWords } from './links'\nimport { PastedImages } from './PastedImages'\nimport { PastedMarkdown } from './PastedMarkdown'\nimport { LinkPlaces } from './LinkPlaces'\nimport { EDITOR_SELECTION_CLASSES } from './looks'\nimport { ReferenceMenu, ReferenceMenuView, isReferenceMenuOpen } from './ReferenceMenu'\nimport { richTextClassName } from './RichText'\nimport { SectionLabel } from './SectionLabel'\nimport { KeptSelection, SelectionToolbar } from './SelectionToolbar'\nimport { isSuggestionOpen } from './suggestionPopup'\n\n/**\n * How the app's saved text and the editor's document turn into each other. The\n * package speaks only the editor's document; the translation is\n * `@estiva-app/protocol`'s, which the package does not depend on (the record\n * below):\n *\n * { read: (value, format) => toEditorDocument(documentForEditing(value, format), { links: true }),\n * write: (doc) => publishableFromEditor(doc) }\n */\nexport interface DocumentCodec {\n /** The saved text, in its format, as the editor's document. */\n read: (value: string, format: string) => JSONContent\n /** The editor's document as the text to save, and the format it is in. */\n write: (doc: JSONContent) => { value: string; contentFormat?: string }\n}\n\n/**\n * Where text typed when the sign-in ends is kept through the passkey trip, and\n * put back, unsaved, after it. The app's own store, by key.\n */\nexport interface HeldTyping {\n /** What is held for `key` from the last ending, or `undefined`. */\n text: (key: string) => string | undefined\n /** Forget what is held for `key`: it was saved. */\n release: (key: string) => void\n /** While the editor is open, let an ending read its unsaved text. Returns what stops that, as the editor closes. */\n register: (key: string, read: () => string | undefined) => () => void\n /** Whether the sign-in has ended: nothing is saved then, and the text is held instead. */\n ended: () => boolean\n}\n\n/** What `[` lists, and how. Without it `[` is a bracket. */\nexport interface DocumentReferences {\n /** The sections for what was typed after `[`, already narrowed and in the app's order. */\n sections: (query: string) => readonly ReferenceSection[]\n /** Called with a listener while the list is open; call it when `sections` would answer differently (a search landed). */\n subscribe?: (listener: () => void) => () => void\n /** Names the list. */\n ariaLabel: string\n /** The heading of rows that bring no section of their own. */\n sectionLabel: string\n /** A row's 16px icon, unless the row brings its own. Default none. */\n icon?: ReactNode\n}\n\n/** Whom `@` offers. Without it `@` is an at sign. */\nexport interface DocumentMentions {\n /** Everyone `@` can offer, asked as the query changes. */\n people: () => readonly MentionPerson[]\n /** The `nostr:npub\u2026` a person is written as; `null` for someone without one, who is not offered. */\n uriOf: (person: MentionPerson) => string | null\n}\n\nexport interface DocumentEditorProps {\n /** The saved text. A new value while the editor is open is somebody else's save, or your own coming back. */\n value: string\n /** The format `value` is in, handed to `codec.read`. */\n format: string\n codec: DocumentCodec\n /**\n * Save. Called when you leave, never while typing, with the text, its format,\n * and the saved text this edit started from \u2014 so the app can tell whom the\n * save names anew. Answer whether it was saved, or, when someone changed a\n * block you changed too, what asks ({@link DocumentAsks}).\n */\n onCommit: (value: string, contentFormat: string | undefined, editedFrom: string) => Promise<boolean | DocumentAsks> | boolean | DocumentAsks\n /**\n * Your saves are merged with someone else's (the app merges them by blocks):\n * a newer save arriving while you are in the editor waits with no line, and\n * leaving saves yours merged onto it. Without it, the line with Load it.\n */\n merges?: boolean\n /** The editor's accessible name. */\n label: string\n /** Muted words over an empty editor. */\n placeholder?: ReactNode\n /** For reading: nothing is typed or saved; chips open, and comments on a selection work when on. */\n readOnly?: boolean\n /** Who saved the text last, when it was not you: named in \"\u2026 saved a newer version\". */\n changedBy?: { name: string } | null\n /**\n * A save refused after the editor closed, with nothing left on screen to say it. Closed while blocks ask, it is\n * handed the text with your version of each, in the saved format, for the app to keep.\n */\n onLeftUnsaved?: (unsaved?: string) => void\n /** Where text typed when the sign-in ends is held, under `holdKey`. */\n hold?: HeldTyping\n holdKey?: string\n /** `[` and `/` \u2192 File. */\n references?: DocumentReferences\n /** `@` and `/` \u2192 Mention. */\n mentions?: DocumentMentions\n /** A pasted app URL drawn as the chip of what it names (`LinkChips`). */\n linkChips?: LinkChipsOptions\n /** `/` \u2192 Upload, and a pasted picture: upload one file and answer the attachment's attributes (its `imeta` fields). */\n upload?: (file: File) => Promise<Record<string, unknown>>\n /** Plain text pasted as the blocks it spells: the app's reader of markdown, as the editor's document. */\n readMarkdown?: (text: string) => JSONContent | undefined\n /** `/` \u2192 Table. Default on. */\n table?: boolean\n /** Comment on what is selected: the selection strip's Comment, and the comment highlights. Without it, neither. */\n onCommentOnSelection?: (anchor: SelectionAnchor) => void\n /** The app's rows in a block's handle menu, after the editing ones: Copy link, Comment. */\n blockRows?: (block: HandleBlock) => ReactNode\n /**\n * Draws a link: the app's own, which resolves what it names \u2014 its chip, its\n * row or its card in the row's place, as `place` says (\u00A713.3).\n */\n referenceView?: ComponentType<ReferenceViewProps>\n /** Draws a placed file: the app's own card. */\n attachmentView?: ComponentType<AttachmentViewProps>\n /** Around everything the editor draws: the app's providers, which may read the editor. */\n wrap?: (children: ReactNode, editor: Editor | null) => ReactNode\n /** The editor, once it is there, and `null` as it goes. */\n onEditor?: (editor: Editor | null) => void\n /** More of the app's own extensions. */\n extensions?: readonly AnyExtension[]\n}\n\n/**\n * A save refused because someone changed a block you changed too, merged as far\n * as it goes. Nothing of yours is saved until every block that asks is chosen.\n */\nexport interface DocumentAsks {\n /** The text to hold now, unsaved: theirs, with every change of yours that did not clash in it, and their words in each block that asks. */\n value: string\n /** Their saved text, which `value` follows: the next save's `editedFrom`. */\n theirs: string\n /** Your text as you saved it: \"Your version\" of each block is read from it. */\n mine: string\n /** The ids of the blocks that ask: changed by both, or changed by one and deleted by the other. */\n blocks: readonly string[]\n /** The text changed since this page was opened, and the app could not merge it: said above the text. */\n sinceOpened?: boolean\n}\n\nconst isAsks = (answer: boolean | DocumentAsks): answer is DocumentAsks => typeof answer === 'object' && answer !== null\n\n/** The node of the block with this id in a document of the editor's, or `null` when it holds none. */\nfunction blockOf(doc: JSONContent, id: string): JSONContent | null {\n if (doc.attrs?.blockId === id) return doc\n for (const child of doc.content ?? []) {\n const found = blockOf(child, id)\n if (found) return found\n }\n return null\n}\n\n/** The words of a block of the editor's document, as \"Your version\" shows them: a line per block inside it (a list's items). */\nconst wordsOf = (node: JSONContent): string => {\n const children = node.content ?? []\n const inline = children.every((child) => child.text !== undefined || !child.content)\n return (node.text ?? '') + children.map(wordsOf).join(inline ? '' : '\\n')\n}\n\n/** A document with each of these blocks as `from` has it, or taken out where `from` has none: your text with your version of each block that asks. */\nfunction withBlocksFrom(doc: JSONContent, ids: readonly string[], from: JSONContent): JSONContent {\n if (!doc.content) return doc\n return {\n ...doc,\n content: doc.content.flatMap((child) => {\n const id = child.attrs?.blockId as string | undefined\n if (id && ids.includes(id)) return blockOf(from, id) ?? []\n return [withBlocksFrom(child, ids, from)]\n }),\n }\n}\n\n/** The top-level blocks `to` has changed, added or taken out since `from`. */\nfunction blocksChanged(from: JSONContent, to: JSONContent): string[] {\n if (from === to) return []\n const before = new Map((from.content ?? []).map((child) => [child.attrs?.blockId as string | undefined, JSON.stringify(child)]))\n const after = new Set<string>()\n const changed: string[] = []\n for (const child of to.content ?? []) {\n const id = child.attrs?.blockId as string | undefined\n if (!id) continue\n after.add(id)\n if (before.get(id) !== JSON.stringify(child)) changed.push(id)\n }\n for (const id of before.keys()) if (id && !after.has(id)) changed.push(id)\n return changed\n}\n\n/**\n * The merge with these blocks as you typed them since the save went: changed in place, taken out where you took them\n * out, and a new one after the nearest block before it in your text that the merge still holds.\n */\nfunction withTypedSince(merged: JSONContent, typedNow: JSONContent, ids: readonly string[]): JSONContent {\n if (ids.length === 0) return merged\n const yours = typedNow.content ?? []\n const content = (merged.content ?? []).flatMap((child) => {\n const id = child.attrs?.blockId as string | undefined\n return id && ids.includes(id) ? (yours.find((block) => block.attrs?.blockId === id) ?? []) : [child]\n })\n yours.forEach((block, i) => {\n const id = block.attrs?.blockId as string | undefined\n if (!id || !ids.includes(id) || content.some((child) => child.attrs?.blockId === id)) return\n let at = 0\n for (let j = i - 1; j >= 0 && at === 0; j--) {\n const before = yours[j].attrs?.blockId as string | undefined\n at = content.findIndex((child) => child.attrs?.blockId === before) + 1\n }\n content.splice(at, 0, block)\n })\n return { ...merged, content }\n}\n\n/** Whose version of a block that asks is chosen. */\ntype Side = 'mine' | 'theirs'\n\n/** What the editor holds while blocks ask. */\ninterface Asking {\n blocks: readonly string[]\n mine: JSONContent\n theirs: JSONContent\n sinceOpened: boolean\n}\n\n/**\n * Your version, beside the block you both changed. Use mine puts yours in its place; Copy puts yours on the clipboard\n * and keeps it here, so you can paste it and still choose; Dismiss keeps theirs. None of them takes focus from the text.\n */\nfunction YourVersion({ words, onUseMine, onDismiss }: { words: string; onUseMine: () => void; onDismiss: () => void }) {\n const [copied, setCopied] = useState(false)\n const keep = (event: { preventDefault: () => void }) => event.preventDefault()\n return (\n <Card fill=\"inset\" className=\"flex flex-col gap-2 p-3\" data-your-version=\"\">\n <SectionLabel>Your version</SectionLabel>\n <p className=\"whitespace-pre-wrap text-body-2 text-text-primary\">{words}</p>\n <div className=\"flex flex-wrap items-center gap-1\">\n <Button variant=\"outlined\" size=\"small\" onMouseDown={keep} onClick={onUseMine}>\n Use mine\n </Button>\n <Button\n variant=\"muted\"\n size=\"small\"\n leadingIcon={copied ? <IconCheck size={14} stroke={1.5} /> : <IconCopy size={14} stroke={1.5} />}\n onMouseDown={keep}\n onClick={() => {\n void navigator.clipboard?.writeText(words).catch(() => undefined)\n setCopied(true)\n }}\n >\n {copied ? 'Copied' : 'Copy'}\n </Button>\n <Button variant=\"muted\" size=\"small\" onMouseDown={keep} onClick={onDismiss}>\n Dismiss\n </Button>\n </div>\n </Card>\n )\n}\n\n/** The editor's own document held for this place when the sign-in ended, block ids and all; `null` when none. */\nfunction heldDocument(hold: HeldTyping | undefined, key: string | undefined): JSONContent | null {\n const text = hold && key ? hold.text(key) : undefined\n if (!text) return null\n try {\n const doc = JSON.parse(text) as JSONContent\n return doc?.type === 'doc' ? doc : null\n } catch {\n return null\n }\n}\n\n/**\n * One document's text as one surface that is always an editor \u2014 Leaf's page,\n * Ship's description and Peek's panel, which each had their own until this.\n * Every app's document can do the same things, wherever it is written.\n *\n * - **Saves when you leave:** on blur, on unmount and on a checklist tick.\n * Never while typing. Escape leaves and keeps the text. A refused save keeps\n * the text and says so; one refused after the editor closed goes to\n * `onLeftUnsaved`.\n * - **Someone else's save arrives** while you are not in it: it is loaded.\n * While you are in it, it waits, and a line says who saved a newer version,\n * with \"Load it\"; leaving with a change saves yours over it \u2014 the later save\n * wins (Miky, LEAF-3's kickoff and 13 October). Your own save coming back is\n * never mistaken for someone else's. With `merges`, no line: leaving merges\n * yours onto theirs.\n * - **A block you both changed asks** (`onCommit` answers {@link DocumentAsks}):\n * their words are in the text, marked at the block's edge, and yours sit\n * beside it with Use mine, Copy and Dismiss. Nothing is saved until every\n * block is chosen; the last choice saves. Leaving before that saves nothing\n * and goes to `onLeftUnsaved`.\n * - **The sign-in ending** holds what was typed (`hold`), and the editor opens\n * with it, unsaved, after the passkey tap.\n *\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/every-app-edits-a-document-with-one-shared-editor.md\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/the-block-editor-kit-lives-in-protocol-and-ui.md\n * why: https://github.com/estiva-app/estiva-docs/blob/main/decisions/merging-two-changes-to-one-text-never-loses-words.md\n */\nexport function DocumentEditor({\n value,\n format,\n codec,\n onCommit,\n merges = false,\n label,\n placeholder,\n readOnly = false,\n changedBy = null,\n onLeftUnsaved,\n hold,\n holdKey,\n references,\n mentions,\n linkChips,\n upload,\n readMarkdown,\n table = true,\n onCommentOnSelection,\n blockRows,\n referenceView,\n attachmentView,\n wrap,\n onEditor,\n extensions = [],\n}: DocumentEditorProps) {\n const [failed, setFailed] = useState(false)\n const [focused, setFocused] = useState(false)\n const [uploadError, setUploadError] = useState<string | null>(null)\n // The latest props, for the editor's callbacks, which are made once.\n const latest = useRef({ value, format, codec, hold, references, mentions, upload, readMarkdown, onLeftUnsaved })\n useEffect(() => {\n latest.current = { value, format, codec, hold, references, mentions, upload, readMarkdown, onLeftUnsaved }\n })\n const ended = () => latest.current.hold?.ended() ?? false\n /*\n The text the editor holds as saved or loaded. A value that differs is\n someone else's save: loaded at once while you are not in it, waiting with a\n line while you are. `saved` is the same, for the editor's callbacks.\n */\n const [base, setBase] = useState(value)\n const saved = useRef(value)\n // The value your own save replaced: until your save comes back, the value still holds it, and it is not someone else's.\n const [superseded, setSuperseded] = useState<string | null>(null)\n // Every text your own saves wrote since someone else's last loaded: an echo of an earlier one can arrive after a later save.\n const own = useRef(new Set<string>())\n // A save out: nothing is loaded over the text it carries until it is answered.\n const [saving, setSaving] = useState(false)\n const committing = useRef(false)\n // What was typed here when the sign-in last ended, back after the passkey tap and not yet saved.\n // Not when it is what the value already holds (a save out as the sign-in ended went through), or nothing would\n // ever take later changes: only a save clears `restored`, and a save of what is saved sends nothing.\n const [held] = useState(() => {\n const doc = heldDocument(hold, holdKey)\n // A held document the codec cannot write (another version's, or cut short) is not text anyone can keep.\n try {\n return doc && codec.write(doc).value !== value ? doc : null\n } catch {\n return null\n }\n })\n // Until it is saved it is your unsaved text: someone else's save waits behind it, as behind a refused one.\n const [restored, setRestored] = useState(held !== null)\n // The text as last typed. Saving on the way out reads this, not the editor, which may already be torn down.\n const typed = useRef<JSONContent | null>(held)\n const again = useRef(false)\n const left = useRef(false)\n /*\n True from the moment the file dialog is asked for until the window has focus\n again: the dialog takes focus, and that blur must not save and leave.\n */\n const picking = useRef(false)\n const picker = useRef<HTMLInputElement>(null)\n // Blocks a refused save asks about: nothing is saved until each is chosen. The ref is for the callbacks.\n const [asking, setAsking] = useState<Asking | null>(null)\n const askingNow = useRef<Asking | null>(null)\n const ask = (next: Asking | null) => {\n askingNow.current = next\n setAsking(next)\n }\n // While blocks ask, what is lost if the text goes now: the text with your version of each. Otherwise `null`.\n const asked = (): JSONContent | null => {\n const now = askingNow.current\n return now && typed.current ? withBlocksFrom(typed.current, now.blocks, now.mine) : null\n }\n // The editor, for the callbacks made before it is.\n const current = useRef<Editor | null>(null)\n // Where each asking block's \"Your version\" is drawn: elements the editor's decorations place beside and under the block.\n const slots = useRef(new Map<string, HTMLElement>())\n const slotOf = useCallback((id: string, where: AskedSlot) => {\n const key = `${id} ${where}`\n let slot = slots.current.get(key)\n if (!slot) {\n slot = document.createElement('span')\n slot.className = ASKED_BLOCK_CLASSES[where]\n slot.contentEditable = 'false'\n slots.current.set(key, slot)\n }\n return slot\n }, [])\n\n /*\n The save asked: theirs is the saved text now, and the editor holds the\n merge, unsaved, with their words in each block that asks. A value still\n holding what this save replaced is not someone else's. `sent` is the text\n that save carried: what was typed since is kept, in the merge or as your\n version of a block that asks, and a block they changed too asks as well.\n */\n const askAbout = (answer: DocumentAsks, replaced: string, sent: JSONContent) => {\n const { codec: words, format: written } = latest.current\n // Both read back through the codec, so they compare with what the app answers.\n const asRead = (doc: JSONContent) => words.read(words.write(doc).value, written)\n const before = asRead(sent)\n const now = typed.current && typed.current !== sent ? asRead(typed.current) : before\n const since = blocksChanged(before, now)\n const mine = withBlocksFrom(words.read(answer.mine, written), since, now)\n const value = words.read(answer.value, written)\n const theirsToo = (id: string) => !!blockOf(before, id) && JSON.stringify(blockOf(value, id)) !== JSON.stringify(blockOf(before, id))\n const asks = [...answer.blocks, ...since.filter((id) => !answer.blocks.includes(id) && theirsToo(id))]\n // A block that asks must be in the text to be chosen: one they deleted that you changed is held as yours, at the end.\n const missing = asks.flatMap((id) => (blockOf(value, id) ? [] : (blockOf(mine, id) ?? [])))\n const merged = missing.length ? { ...value, content: [...(value.content ?? []), ...missing] } : value\n const held = withTypedSince(merged, now, since.filter((id) => !asks.includes(id)))\n const blocks = asks.filter((id) => blockOf(held, id))\n saved.current = answer.theirs\n shown.current = answer.theirs\n setSuperseded(replaced)\n setBase(answer.theirs)\n const editor = current.current\n if (editor && !editor.isDestroyed) editor.commands.setContent(held, { emitUpdate: false })\n typed.current = held\n ask(blocks.length ? { blocks, mine, theirs: words.read(answer.theirs, written), sinceOpened: !!answer.sinceOpened } : null)\n }\n\n const save = useCallback(\n async (doc: JSONContent | null) => {\n // Read only: a box ticked in a node view is not a save. After an ending the text is held, and a save would be refused.\n if (!doc || readOnly || ended()) return\n // Blocks ask: nothing of yours is saved until each is chosen.\n if (askingNow.current) return\n // A change made while a save is out goes next, not nowhere.\n if (committing.current) {\n again.current = true\n return\n }\n const next = latest.current.codec.write(doc)\n if (next.value === saved.current) return\n committing.current = true\n setSaving(true)\n // The later save wins: whatever the value holds as you save is replaced by yours.\n const replaced = latest.current.value\n const editedFrom = saved.current\n try {\n const answer = await onCommit(next.value, next.contentFormat, editedFrom)\n if (isAsks(answer)) {\n // Closed meanwhile: there is no text left to choose in, and nothing was saved. The app keeps what was sent.\n if (left.current) {\n if (!ended()) latest.current.onLeftUnsaved?.(next.value)\n } else {\n askAbout(answer, replaced, doc)\n setFailed(false)\n }\n return\n }\n const ok = answer\n if (ok) {\n // The editor already shows it, and may hold more typed since: `shown` keeps the effect below from setting it.\n saved.current = next.value\n shown.current = next.value\n own.current.add(next.value)\n setSuperseded(replaced)\n setBase(next.value)\n setRestored(false)\n // A save out as the sign-in ended: what was held then may hold more than this, typed since.\n const store = latest.current.hold\n if (store && holdKey && !store.ended()) store.release(holdKey)\n }\n if (left.current) {\n // Refused because the sign-in ended: the text is held for after the tap, not lost.\n if (!ok && !ended()) latest.current.onLeftUnsaved?.()\n } else setFailed(!ok)\n } catch {\n // A save that throws is a refusal: the text stays, and says so.\n if (left.current) {\n if (!ended()) latest.current.onLeftUnsaved?.()\n } else setFailed(true)\n } finally {\n committing.current = false\n setSaving(false)\n if (again.current && !askingNow.current) {\n again.current = false\n // After an ending it is held for after the tap, and a save would only be refused. Only a change: leaving\n // while a blur's save is out asks again for the same text, and a refused one would be sent and said twice.\n const waiting = typed.current\n if (!ended() && waiting && latest.current.codec.write(waiting).value !== next.value) void latestSave.current(waiting)\n }\n }\n },\n [onCommit, holdKey, readOnly],\n )\n\n // While open, an ending reads the unsaved text. Keyed on the key and on there being a store, not on the store object:\n // a new `hold` each render must not unregister, since the app's unregister forgets what was held unless an ending is under way.\n const holds = !!hold\n useEffect(() => {\n const store = latest.current.hold\n if (!holds || !store || !holdKey) return\n return store.register(holdKey, () => {\n // While blocks ask, your version of each is held: the ask itself does not outlive the passkey trip.\n const doc = asked() ?? typed.current\n return doc && latest.current.codec.write(doc).value !== saved.current ? JSON.stringify(doc) : undefined\n })\n }, [holdKey, holds])\n\n // The latest `save`, for the editor's `onBlur` (made once) and the unmount below.\n const latestSave = useRef(save)\n useEffect(() => {\n latestSave.current = save\n }, [save])\n // The text the editor was last set to, so a `base` it already shows is not set again under the caret.\n const shown = useRef(value)\n\n const openPicker = () => {\n picking.current = true\n const released = () => {\n picking.current = false\n window.removeEventListener('focus', released)\n }\n window.addEventListener('focus', released)\n picker.current?.click()\n }\n const pickFile = useRef(openPicker)\n pickFile.current = openPicker\n\n /* `/` File and a pasted picture: the upload first, then the block \u2014 its attributes are the upload's answer. */\n const attach = async (chosen: File[]) => {\n const uploadOne = latest.current.upload\n if (!uploadOne) return\n setUploadError(null)\n try {\n for (const file of chosen) {\n const attrs = await uploadOne(file)\n if (!editor || editor.isDestroyed) return\n editor.chain().focus().insertContent({ type: 'attachment', attrs }).run()\n }\n } catch (error) {\n setUploadError(error instanceof Error ? error.message : String(error))\n }\n }\n const attachTo = useRef(attach)\n attachTo.current = attach\n\n const editor = useEditor(\n {\n extensions: documentExtensions({\n latest,\n references,\n mentions,\n linkChips,\n table,\n upload: !!upload,\n readMarkdown: !!readMarkdown,\n comments: !!onCommentOnSelection,\n referenceView,\n attachmentView,\n pickFile,\n attach: attachTo,\n extensions,\n }),\n // Made once. A value coming back must not rebuild the editor under the caret; see the effect below.\n content: held ?? codec.read(value, format),\n editable: !readOnly,\n editorProps: {\n // Focusable when read only too: the selection strip, and so Comment on its words, shows only in a focused view.\n attributes: {\n 'aria-label': label,\n role: 'textbox',\n 'aria-multiline': 'true',\n tabindex: '0',\n // A row or a card is its whole line (`LinkPlaces`), drawn on that line: a block inside it would push the\n // separator and trailing break ProseMirror puts beside it onto empty lines of their own (code review).\n class: richTextClassName('default', cn('outline-none [&_[data-link-place]]:inline-block [&_[data-link-place]]:w-full [&_[data-link-place]]:align-top', EDITOR_SELECTION_CLASSES)),\n },\n handleKeyDown: (view, event) => {\n if (event.key !== 'Escape') return false\n // An open list or chip menu closes first; the next Escape leaves.\n if (isSuggestionOpen() || isReferenceMenuOpen(view.state)) return false\n const { selection, tr } = view.state\n // Words selected: the first Escape lets go of them, which also closes the strip.\n if (!selection.empty) {\n view.dispatch(tr.setSelection(TextSelection.create(tr.doc, selection.to)))\n return true\n }\n view.dom.blur()\n return true\n },\n },\n onUpdate: ({ editor: e, transaction }) => {\n typed.current = e.getJSON()\n // A click on a box does not focus the field, so no blur will save it.\n if (isChecklistTick(transaction)) void latestSave.current(typed.current)\n },\n onFocus: () => setFocused(true),\n onBlur: () => {\n setFocused(false)\n // The file dialog took focus: the person has not left.\n if (picking.current) return\n // Yours, if you changed anything: it replaces what waited. If not, what waited is loaded as you leave (below).\n void latestSave.current(typed.current)\n },\n },\n [],\n )\n\n /*\n Someone else's save. Not in the editor: theirs is the text now. In it, or\n with your own text unsaved after a refusal or an ending: it waits, and the\n line below says so. Never over a save that is still out.\n */\n const arrived = value !== base && value !== superseded && !own.current.has(value)\n // Read only, there is nothing of yours to keep: theirs loads even while you select words to comment on.\n if (arrived && (readOnly || (!focused && !saving && !failed && !restored && !asking))) {\n own.current.clear()\n setBase(value)\n }\n const waiting = arrived && !readOnly && (focused || failed || restored || !!asking)\n\n // The text the editor should hold, set into it when it changes \u2014 never under your own typing, which `shown` already holds.\n useEffect(() => {\n saved.current = base\n if (!editor || editor.isDestroyed || base === shown.current) return\n editor.commands.setContent(latest.current.codec.read(base, latest.current.format), { emitUpdate: false })\n shown.current = base\n typed.current = null\n }, [editor, base])\n\n // Made read only or editable while open: the editor follows, without being made again.\n useEffect(() => {\n if (editor && !editor.isDestroyed && editor.isEditable === readOnly) editor.setEditable(!readOnly, false)\n }, [editor, readOnly])\n\n const empty = useEditorState({ editor, selector: ({ editor: ed }) => !ed || ed.isEmpty })\n\n // \"Load it\": theirs replaces what you have not saved.\n const load = () => {\n setBase(latest.current.value)\n setFailed(false)\n setRestored(false)\n // Theirs replaces yours whole, so nothing is left to choose.\n ask(null)\n slots.current.clear()\n }\n\n // Closing saves on the way out. Not when the sign-in ended: the save would be refused and reported as lost over\n // the passkey screen, and the text is held on the device instead. Not while blocks ask: nothing is saved until chosen.\n useEffect(\n () => () => {\n left.current = true\n if (ended()) return\n const draft = asked()\n if (draft) latest.current.onLeftUnsaved?.(latest.current.codec.write(draft).value)\n else void latestSave.current(typed.current)\n },\n [],\n )\n\n useEffect(() => {\n current.current = editor\n onEditor?.(editor)\n return () => onEditor?.(null)\n }, [editor, onEditor])\n\n // The blocks that ask, drawn in the text; none once every one is chosen.\n const askedIds = asking?.blocks\n useEffect(() => {\n if (editor && !editor.isDestroyed) setAskedBlocks(editor, askedIds ?? [], slotOf)\n }, [editor, askedIds, slotOf])\n\n /*\n One block chosen: yours or theirs in its place, or the block gone when the\n one chosen deleted it. The last choice saves, after their text.\n */\n const choose = (id: string, side: Side) => {\n const now = askingNow.current\n if (!editor || editor.isDestroyed || !now) return\n const chosen = blockOf(side === 'mine' ? now.mine : now.theirs, id)\n const at = blockAt(editor.state.doc, id)\n if (at) {\n const end = at.pos + at.node.nodeSize\n const tr = chosen ? editor.state.tr.replaceWith(at.pos, end, editor.schema.nodeFromJSON(chosen)) : editor.state.tr.delete(at.pos, end)\n editor.view.dispatch(tr)\n }\n typed.current = editor.getJSON()\n const rest = now.blocks.filter((block) => block !== id)\n if (rest.length > 0) {\n ask({ ...now, blocks: rest })\n return\n }\n ask(null)\n slots.current.clear()\n void latestSave.current(typed.current)\n }\n\n const who = changedBy?.name ?? 'Someone'\n const drawn = (\n <div className=\"flex flex-col gap-1\">\n {asking?.sinceOpened && <FieldLine tone=\"helper\">This page changed since you opened it.</FieldLine>}\n <EditorBlockHandle editor={editor} actions={blockRows}>\n {/* A table's handles and \u2795 bars while you point at it; the block handle stays the table's. */}\n <EditorTableControls editor={editor}>\n <EditorContent editor={editor} className=\"-mx-2 cursor-text px-2 py-1\" data-document-editor=\"\" />\n </EditorTableControls>\n {empty && !readOnly && placeholder && (\n <span aria-hidden className=\"pointer-events-none absolute left-0 top-1 text-body-2 text-text-muted\">\n {placeholder}\n </span>\n )}\n </EditorBlockHandle>\n {/* Read only with comments off, the strip would have nothing in it: no strip. */}\n {(!readOnly || onCommentOnSelection) && <SelectionToolbar\n editor={editor}\n marks={readOnly ? [] : ['bold', 'italic', 'underline', 'code']}\n link={!readOnly}\n actions={\n onCommentOnSelection\n ? [\n {\n label: 'Comment',\n icon: <IconMessagePlus size={16} stroke={1.5} />,\n run: (ed) => {\n const anchor = anchorOfSelection(ed)\n if (!anchor) return\n // The draft's highlight keeps what is selected marked; the selection itself can go.\n ed.commands.setTextSelection(ed.state.selection.to)\n onCommentOnSelection(anchor)\n },\n },\n ]\n : []\n }\n />}\n <ReferenceMenuView editor={editor} />\n {/* Always there, so `/` \u2192 File, made as the editor opened, has a dialog to open even if `upload` came and went. */}\n <FilePicker ref={picker} multiple onPick={(files) => void attach(files)} />\n {asking?.blocks.flatMap((id) => {\n const mine = blockOf(asking.mine, id)\n const card = <YourVersion words={mine ? wordsOf(mine) : 'You deleted this block.'} onUseMine={() => choose(id, 'mine')} onDismiss={() => choose(id, 'theirs')} />\n // Beside the words, and under the block at phone width: one is shown at a time (`ASKED_BLOCK_CLASSES`).\n // @estiva-escape(estiva/no-hand-rolled-behaviour): into the block's slot in the text (AskedBlocks), not a floating panel.\n return (['beside', 'under'] as const).map((where) => createPortal(card, slotOf(id, where), `${id} ${where}`))\n })}\n {waiting && !merges && (\n <FieldLine tone=\"helper\">\n {`${who} saved a newer version.`}{' '}\n {/* Pressing it must not take focus from the editor: that blur would save yours over theirs first. */}\n <Button variant=\"muted\" size=\"small\" onMouseDown={(event) => event.preventDefault()} onClick={load}>\n Load it\n </Button>{' '}\n {/* What Load it costs, said where it is pressed (Miky, WBD-3's /land, 20 October). */}\n (replaces your changes)\n </FieldLine>\n )}\n {uploadError && <FieldLine tone=\"error\">{uploadError}</FieldLine>}\n {failed && <FieldLine tone=\"error\">Could not save. Your text is still here.</FieldLine>}\n </div>\n )\n return <>{wrap ? wrap(drawn, editor) : drawn}</>\n}\n\n/** What a document's editor is built from: the app's parts, and its latest handlers, read through `latest` (the editor is made once). */\nexport interface DocumentGrammar {\n latest: {\n current: {\n references?: DocumentReferences\n mentions?: DocumentMentions\n upload?: unknown\n readMarkdown?: (text: string) => JSONContent | undefined\n }\n }\n references?: DocumentReferences\n mentions?: DocumentMentions\n linkChips?: LinkChipsOptions\n /** `/` \u2192 Table. */\n table: boolean\n /** `/` \u2192 Upload, and a pasted picture placed. */\n upload: boolean\n /** Markdown pasted as plain text lands as blocks. */\n readMarkdown: boolean\n /** The comment highlights. */\n comments: boolean\n referenceView?: ComponentType<ReferenceViewProps>\n attachmentView?: ComponentType<AttachmentViewProps>\n /** Opens the file dialog, for `/` \u2192 Upload. */\n pickFile: { current: () => void }\n /** Uploads and places pasted pictures. */\n attach: { current: (files: File[]) => Promise<void> }\n extensions: readonly AnyExtension[]\n}\n\n/**\n * A document's grammar, one list for every editor of a document (`DocumentEditor`, `DocumentField`): the blocks, the\n * marks, links where they sit, `/`, and `[` and `@` when the app gives them.\n */\nexport function documentExtensions({ latest, references, mentions, linkChips, table, upload, readMarkdown, comments, referenceView, attachmentView, pickFile, attach, extensions }: DocumentGrammar): AnyExtension[] {\n return [\n DocumentKit.configure({\n strike: false,\n heading: { levels: [1, 2, 3] },\n dropcursor: blockDropCursor,\n codeBlock: false,\n // A link on words is made by pasting a URL over them or by the strip's Link, and opens on a click, as a bare\n // address does \u2014 through `BareLinks`, which opens only a followable address and never hands the tab this window;\n // Tiptap's own click opens without that. A bare address stays text: a link made on it by typing would change what is saved.\n link: { openOnClick: false, shouldAutoLink: () => false, HTMLAttributes: LINK_MARK_ATTRIBUTES },\n }),\n PasteOverWords,\n KeptSelection,\n BareLinks,\n CodeBlockColours,\n TableKit.configure({ table: { resizable: false } }),\n BlockId,\n // A block a refused save asks about, drawn so a save never carries it.\n AskedBlocks,\n Checklist,\n Callout,\n // A link is being edited only while the caret is on its line: anywhere else on the page it previews on hover.\n ReferenceNode.configure({ view: referenceView ?? null, editingLine: true }),\n // A link's chip in a sentence, its row alone on its line, its card in the row's place (SPEC \u00A713.3).\n LinkPlaces,\n // A click on a link offers Open, and alone on its line Show as Row or Card.\n ReferenceMenu,\n UnknownBlock,\n AttachmentNode.configure({ view: attachmentView ?? null }),\n SlashCommands.configure({ sections: slashSections({ table, upload, pickFile }) }),\n ...(references\n ? [\n ReferenceTrigger.configure({\n items: () => [],\n sections: (query) => latest.current.references?.sections(query) ?? [],\n subscribe: (listener) => latest.current.references?.subscribe?.(listener) ?? (() => {}),\n nodeName: 'reference',\n ariaLabel: references.ariaLabel,\n sectionLabel: references.sectionLabel,\n icon: references.icon ?? null,\n }),\n ]\n : []),\n ...(mentions\n ? [PersonReference.configure({ people: () => latest.current.mentions?.people() ?? [], uriOf: (person) => latest.current.mentions?.uriOf(person) ?? null })]\n : []),\n ...(linkChips ? [LinkChips.configure(linkChips)] : []),\n ...(upload\n ? [\n // A pasted picture is placed as `/` File places one; text on the clipboard stays text.\n PastedImages.configure({\n onImages: (pasted) => {\n if (!latest.current.upload) return false\n void attach.current(pasted)\n return true\n },\n }),\n ]\n : []),\n // Markdown pasted as plain text lands as the blocks it spells, tables included.\n ...(readMarkdown ? [PastedMarkdown.configure({ read: (text) => latest.current.readMarkdown?.(text) })] : []),\n // Where each comment is, drawn as a decoration, so a save never carries it.\n ...(comments ? [CommentHighlights] : []),\n ...extensions,\n ]\n}\n\n/**\n * `/`: the shared Format section with a document's checklist and callouts,\n * then Insert with what this editor can do. File and Mention type `[` and `@`,\n * so their lists open; Upload picks a file from the computer (Miky, 15 October\n * QA and 20 October at the Storybook: \"File\" for `[`, a Mention row, \"Upload\").\n */\nfunction slashSections({ table, upload, pickFile }: { table: boolean; upload: boolean; pickFile: { current: () => void } }): SlashSection[] {\n const insert: SlashCommand[] = [\n // Three by three with a header row, as every app's Insert \u2192 Table makes it.\n ...(table ? [{ key: 'insert-table', row: { label: 'Table' }, run: (editor: Editor) => void editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() }] : []),\n // Offered only where the editor has the list the row opens.\n { key: 'insert-link', row: { label: 'File', shortcut: '[' }, keywords: ['[', 'link', 'reference'], needs: ['referenceTrigger'], run: typeTrigger('[') },\n ...(upload ? [{ key: 'insert-upload', row: { label: 'Upload' }, keywords: ['attach', 'file', 'picture'], run: () => pickFile.current() }] : []),\n { key: 'insert-mention', row: { label: 'Mention', shortcut: '@' }, keywords: ['@', 'person', 'people'], needs: ['personReference'], run: typeTrigger('@') },\n ]\n return [formatSection('block'), ...(insert.length > 0 ? [{ label: 'Insert', commands: insert }] : [])]\n}\n", "import { Extension, type Editor } from '@tiptap/core'\nimport type { Node as ProseMirrorNode } from '@tiptap/pm/model'\nimport { Plugin, PluginKey } from '@tiptap/pm/state'\nimport { Decoration, DecorationSet } from '@tiptap/pm/view'\n\n/** Where an asked block's card is drawn: beside its words, or under them at phone width. */\nexport type AskedSlot = 'beside' | 'under'\n\n/** The blocks that ask, and where each one's card is drawn. */\ninterface AskedState {\n ids: readonly string[]\n /** The element one asked block's card is drawn into, there: the editor's, kept for as long as it asks. */\n slot: ((id: string, where: AskedSlot) => HTMLElement) | null\n}\n\nconst askedBlocksKey = new PluginKey<AskedState>('askedBlocks')\n\n/**\n * A block both people changed: marked by a bar in the accent colour at its edge, as long as its words and no longer,\n * with the card that holds your version beside them; its words wrap beside the card, and the next block starts below\n * both. At phone width the card sits under the block, outside the bar (the story `Project changes`, approved 2 November).\n * The block holds the card (the editor's blocks are a flex column's), so the bar is an element of its own, as tall as\n * the block's words as the plugin measures them: a widget, whose changes the editor leaves alone.\n */\nexport const ASKED_BLOCK_CLASSES = {\n block: 'relative -ml-3 pl-3',\n bar: 'absolute left-0 top-0 h-full w-0.5 bg-accent-primary',\n beside: 'hidden md:float-right md:ml-3 md:block md:w-64',\n under: 'mt-2 block md:hidden',\n} as const\n\nconst newBar = () => {\n const bar = document.createElement('span')\n bar.className = ASKED_BLOCK_CLASSES.bar\n bar.dataset.askedBar = ''\n bar.contentEditable = 'false'\n return bar\n}\n\n/**\n * How far down a block its words reach, to the foot of their last line, leaving out the card drawn in it; `null` when\n * it has none to measure.\n */\nfunction wordsHeight(block: HTMLElement): number | null {\n const top = block.getBoundingClientRect().top\n let bottom: number | null = null\n let glyphs = 0\n const range = document.createRange()\n const walker = document.createTreeWalker(block, NodeFilter.SHOW_TEXT)\n for (let text = walker.nextNode(); text; text = walker.nextNode()) {\n if (text.parentElement?.closest('.ProseMirror-widget')) continue\n range.selectNodeContents(text)\n for (const box of range.getClientRects()) {\n if (box.height > 0 && (bottom === null || box.bottom > bottom)) [bottom, glyphs] = [box.bottom, box.height]\n }\n }\n if (bottom === null) return null\n // A line is taller than its letters: half the difference is below them, as half is above the first.\n const line = parseFloat(getComputedStyle(block).lineHeight)\n return bottom - top + (line > glyphs ? (line - glyphs) / 2 : 0)\n}\n\n/** Each asked block's bar as tall as its words; where nothing can be measured, as tall as the block. */\nfunction measureWords(root: HTMLElement) {\n for (const block of root.querySelectorAll<HTMLElement>('[data-asked-block]')) {\n const bar = block.querySelector<HTMLElement>('[data-asked-bar]')\n if (!bar) continue\n const height = typeof document.createRange().getClientRects === 'function' ? wordsHeight(block) : null\n const next = height === null ? '' : `${height}px`\n if (bar.style.height !== next) bar.style.height = next\n }\n}\n\n/** Each block with a `blockId` the editor holds, and where it is. */\nexport function blockAt(doc: ProseMirrorNode, id: string): { node: ProseMirrorNode; pos: number } | null {\n let found: { node: ProseMirrorNode; pos: number } | null = null\n doc.descendants((node, pos) => {\n if (found) return false\n if (node.attrs.blockId === id) {\n found = { node, pos }\n return false\n }\n return true\n })\n return found\n}\n\n/**\n * The blocks a refused save asks about (`DocumentEditor`'s `DocumentAsks`), drawn as decorations so a save never\n * carries them: the bar at the block's edge, and a slot at its end that the editor draws \"Your version\" into.\n */\nexport const AskedBlocks = Extension.create({\n name: 'askedBlocks',\n\n addProseMirrorPlugins() {\n return [\n new Plugin<AskedState>({\n key: askedBlocksKey,\n state: {\n init: () => ({ ids: [], slot: null }),\n apply(tr, previous) {\n return (tr.getMeta(askedBlocksKey) as AskedState | undefined) ?? previous\n },\n },\n props: {\n decorations(state) {\n const { ids, slot } = askedBlocksKey.getState(state) ?? { ids: [], slot: null }\n if (!slot || ids.length === 0) return null\n const drawn: Decoration[] = []\n for (const id of ids) {\n const at = blockAt(state.doc, id)\n if (!at) continue\n const end = at.pos + at.node.nodeSize\n drawn.push(Decoration.node(at.pos, end, { class: ASKED_BLOCK_CLASSES.block, 'data-asked-block': id }))\n // The same element each time, so the card drawn into it stays as the text around it changes. Beside: first in\n // the block, so its words wrap from its top; under: after the block, outside the bar.\n const widget = { ignoreSelection: true, stopEvent: () => true }\n const widgetAt = (pos: number, where: AskedSlot, side: number) =>\n Decoration.widget(pos, () => slot(id, where), { ...widget, key: `asked-${id}-${where}`, side })\n drawn.push(\n Decoration.widget(at.pos + 1, newBar, { ...widget, key: `asked-${id}-bar`, side: -2 }),\n widgetAt(at.pos + 1, 'beside', -1),\n widgetAt(end, 'under', 1),\n )\n }\n return drawn.length ? DecorationSet.create(state.doc, drawn) : null\n },\n },\n // The bar's height, again whenever the text, the editor's width or a card (drawn after the block) changes it.\n // Nothing is watched or measured while no block asks: typing costs what it did.\n view(view) {\n const measure = () => measureWords(view.dom)\n const resized = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(measure)\n let watched: readonly Element[] = []\n return {\n update() {\n const asking = (askedBlocksKey.getState(view.state)?.ids.length ?? 0) > 0\n const blocks = asking ? [...view.dom.querySelectorAll('[data-asked-block]')] : []\n if (resized && (blocks.length !== watched.length || blocks.some((block, i) => block !== watched[i]))) {\n resized.disconnect()\n if (blocks.length) for (const element of [view.dom, ...blocks]) resized.observe(element)\n watched = blocks\n }\n if (asking) measure()\n },\n destroy: () => resized?.disconnect(),\n }\n },\n }),\n ]\n },\n})\n\n/** Draw these blocks as asking, with their cards in `slot`; none, to draw nothing. */\nexport function setAskedBlocks(editor: Editor, ids: readonly string[], slot: (id: string, where: AskedSlot) => HTMLElement) {\n if (editor.isDestroyed) return\n editor.view.dispatch(editor.state.tr.setMeta(askedBlocksKey, { ids, slot }))\n}\n", "import { useEffect, useLayoutEffect, useRef, useState, type ComponentType, type MouseEvent, type ReactNode } from 'react'\nimport type { AnyExtension, Editor } from '@tiptap/core'\nimport { EditorContent, useEditor, useEditorState, type JSONContent } from '@tiptap/react'\nimport type { AttachmentViewProps, ReferenceViewProps } from './BlockNodes'\nimport { cn } from './cn'\nimport { documentExtensions, type DocumentCodec, type DocumentMentions, type DocumentReferences } from './DocumentEditor'\nimport { useFormBusy } from './formBusy'\nimport type { LinkChipsOptions } from './LinkChips'\nimport { EDITOR_SELECTION_CLASSES, FIELD_SHELL_CLASSES, FIELD_SHELL_FOCUS_CLASSES } from './looks'\nimport { ReferenceMenuView } from './ReferenceMenu'\nimport { richTextClassName } from './RichText'\nimport { SelectionToolbar } from './SelectionToolbar'\nimport { isSuggestionOpen } from './suggestionPopup'\n\nexport interface DocumentFieldProps {\n /** What the field holds, in `format`; `''` when nothing is written. A value that is not its own edit coming back is loaded into it. */\n value: string\n /** The format `value` is in, handed to `codec.read`. */\n format: string\n /** How the app's text and the editor's document turn into each other: `DocumentEditor`'s. */\n codec: DocumentCodec\n /** Every edit, as it is typed: the text and its format, or `''` once it is emptied or holds only spaces and blank lines. Nothing is saved: the form around it sends. */\n onChange: (value: string, contentFormat: string | undefined) => void\n /** The editor's accessible name: the label of the `Field` around it. */\n label: string\n /** Muted words in the empty field. */\n placeholder?: ReactNode\n /** `[` and `/` \u2192 File. */\n references?: DocumentReferences\n /** `@` and `/` \u2192 Mention. */\n mentions?: DocumentMentions\n /** A pasted app URL drawn as the chip of what it names (`LinkChips`). */\n linkChips?: LinkChipsOptions\n /** Plain text pasted as the blocks it spells: the app's reader of markdown, as the editor's document. */\n readMarkdown?: (text: string) => JSONContent | undefined\n /** Draws a link: the app's own, which resolves what it names. */\n referenceView?: ComponentType<ReferenceViewProps>\n /** Draws a placed file: the app's own card. */\n attachmentView?: ComponentType<AttachmentViewProps>\n /** More of the app's own extensions. */\n extensions?: readonly AnyExtension[]\n /** Set by a required `Field` around it, for a screen reader. */\n 'aria-required'?: boolean | 'true' | 'false'\n}\n\nconst NONE: readonly AnyExtension[] = []\nconst nothing = () => {}\n\n/** Nothing but spaces and blank lines: no word, and no link, card or picture (any part of it that is not text or a line break). */\nconst isBlank = (editor: Editor) => {\n let blank = true\n editor.state.doc.descendants((node) => {\n if (node.isText ? /\\S/.test(node.text ?? '') : node.isLeaf && node.type.name !== 'hardBreak') blank = false\n return blank\n })\n return blank\n}\n\n/**\n * A form's field that holds a document: a description written in the form that files it. The document editor's\n * grammar (`DocumentEditor`'s blocks, marks, `[`, `@` and `/`) in a field's box, as a Textarea's beside it. It is the\n * form's: every edit goes back as it is typed, nothing is saved on leaving, Ctrl/Cmd+Enter sends the form, and while\n * the form sends nothing can be written in it.\n *\n * **Told apart by everything it has handed back, not only the last** (Peek's `ProseField`, RIC-13). Keys pressed faster\n * than React renders reach the editor before the value from the previous one comes back. Compared with the last edit\n * alone, that older value looked like one from outside and was loaded over the newer text. A value this field wrote is\n * never an outside value, however late it arrives; each is dropped once the value has shown it, so the queue holds only\n * the edits still in flight. A queue, not a set: `a`, `ab`, `a` (a key and its Backspace) repeats a value.\n */\nexport function DocumentField({\n value,\n format,\n codec,\n onChange,\n label,\n placeholder,\n references,\n mentions,\n linkChips,\n readMarkdown,\n referenceView,\n attachmentView,\n extensions = NONE,\n 'aria-required': required,\n}: DocumentFieldProps) {\n // The latest props, for the editor's callbacks, which are made once.\n const latest = useRef({ value, format, codec, onChange, references, mentions, readMarkdown })\n useEffect(() => {\n latest.current = { value, format, codec, onChange, references, mentions, readMarkdown }\n })\n // What this field has handed back and the value has not shown yet, oldest first.\n const inFlight = useRef<string[]>([value])\n // `''` too is the codec's to read, as the document editor reads it: a block typed into it then gets its id.\n const read = (text: string) => latest.current.codec.read(text, latest.current.format)\n // No upload in a field: `/` has no Upload, and a pasted picture stays the browser's.\n const pickFile = useRef(nothing)\n const attach = useRef(async () => {})\n const [initial] = useState(() => read(value))\n\n const editor = useEditor(\n {\n extensions: documentExtensions({\n latest,\n references,\n mentions,\n linkChips,\n table: false,\n upload: false,\n readMarkdown: !!readMarkdown,\n comments: false,\n referenceView,\n attachmentView,\n pickFile,\n attach,\n extensions,\n }),\n // Made once: a value coming back must not rebuild the editor under the caret; see the effect below.\n content: initial,\n editorProps: {\n attributes: {\n 'aria-label': label,\n role: 'textbox',\n 'aria-multiline': 'true',\n ...(required !== undefined && required !== false ? { 'aria-required': 'true' } : {}),\n // Three lines tall at rest, as a Textarea of three rows beside it. A row or a card is its whole line (`LinkPlaces`).\n // eslint-disable-next-line token-spacing/no-restricted-classes -- @estiva-escape: three lines of the field's own text (140% of 14px each), the height of a Textarea of three rows\n class: richTextClassName('default', cn('outline-none min-h-[4.2em] [&_[data-link-place]]:inline-block [&_[data-link-place]]:w-full [&_[data-link-place]]:align-top', EDITOR_SELECTION_CLASSES)),\n },\n /*\n Ctrl/Cmd+Enter sends the form around it, as from any of its fields. The field asks the form itself: the\n editor marks every Enter it is given as handled (a browser's Enter would otherwise change the text), and the\n form leaves a handled key alone \u2014 measured in Chrome, the form never heard it. An open list keeps its keys.\n */\n handleKeyDown: (view, event) => {\n if (event.key !== 'Enter' || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || isSuggestionOpen()) return false\n const form = view.dom.closest('form')\n if (!form) return false\n form.requestSubmit()\n return true\n },\n },\n onUpdate: ({ editor: ed }) => {\n // Emptied, or only spaces and blank lines, it holds nothing: `''`, so a required field is missing again (Peek's ProseField).\n const next = isBlank(ed) ? { value: '' } : latest.current.codec.write(ed.getJSON())\n inFlight.current.push(next.value)\n latest.current.onChange(next.value, next.contentFormat)\n },\n },\n [],\n )\n\n useEffect(() => {\n if (!editor || editor.isDestroyed) return\n const at = inFlight.current.indexOf(value)\n if (at !== -1) {\n // Its own edit coming round, possibly late. Values render in order, so nothing handed back before it can still\n // arrive: drop those, keep the rest.\n inFlight.current = inFlight.current.slice(at + 1)\n return\n }\n inFlight.current = []\n // `read` takes the latest codec and format, set by the effect above, which runs first.\n editor.commands.setContent(read(value), { emitUpdate: false })\n }, [editor, value])\n\n /*\n While its form sends it waits, as the fields beside it do. The form's disabled fieldset switches off every native\n control in it, and a document's box is not one: it is told here, before the paint, with no edit handed back.\n */\n const busy = useFormBusy()\n useLayoutEffect(() => {\n if (editor && !editor.isDestroyed && editor.isEditable === busy) editor.setEditable(!busy, false)\n }, [editor, busy])\n\n const empty = useEditorState({ editor, selector: ({ editor: ed }) => !ed || ed.isEmpty })\n\n // A press on the box's padding puts the caret in, as a Textarea's does.\n const into = (event: MouseEvent<HTMLDivElement>) => {\n if (event.target !== event.currentTarget || !editor) return\n event.preventDefault()\n editor.commands.focus('end')\n }\n\n return (\n <>\n <div className={cn(FIELD_SHELL_CLASSES, FIELD_SHELL_FOCUS_CLASSES, 'relative cursor-text px-3 py-2')} onMouseDown={into}>\n <EditorContent editor={editor} />\n {empty && placeholder && (\n <span aria-hidden className=\"pointer-events-none absolute left-3 top-2 text-body-2 text-text-muted\">\n {placeholder}\n </span>\n )}\n </div>\n <SelectionToolbar editor={editor} marks={['bold', 'italic', 'underline', 'code']} link />\n <ReferenceMenuView editor={editor} />\n </>\n )\n}\n"],
5
+ "mappings": ";AAAA,SAAS,aAAa,WAAW,QAAQ,gBAAgC;AAEzE,SAAS,iBAAiB;AAC1B,SAAS,QAAQ,iBAAiB;AAClC,SAAS,YAAY,qBAAqB;AAC1C,SAAS,UAAU,UAAU,YAAY,UAAU,qBAAqB;AACxE,SAAS,YAAY;AACrB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,SAAS,eAAe,wBAAwB;AACzD,SAAS,qBAAqB;AA8btB,cAqBA,YArBA;AApaD,IAAM,mBAAmB,IAAI,UAA4B,eAAe;AAGxE,IAAM,gBAAgB,UAAU,OAAO;AAAA,EAC5C,MAAM;AAAA,EAEN,wBAAwB;AACtB,WAAO;AAAA,MACL,IAAI,OAAyB;AAAA,QAC3B,KAAK;AAAA,QACL,OAAO;AAAA,UACL,MAAM,MAAM;AAAA,UACZ,MAAM,IAAI,UAAU;AAClB,kBAAM,OAAO,GAAG,QAAQ,gBAAgB;AACxC,gBAAI,SAAS,OAAW,QAAO;AAC/B,gBAAI,CAAC,SAAU,QAAO;AAGtB,mBAAO,EAAE,MAAM,GAAG,QAAQ,IAAI,SAAS,IAAI,GAAG,IAAI,GAAG,QAAQ,IAAI,SAAS,EAAE,EAAE;AAAA,UAChF;AAAA,QACF;AAAA,QACA,OAAO;AAAA,UACL,YAAY,OAAO;AACjB,kBAAM,QAAQ,iBAAiB,SAAS,KAAK;AAC7C,gBAAI,CAAC,SAAS,MAAM,SAAS,MAAM,GAAI,QAAO;AAC9C,mBAAO,cAAc,OAAO,MAAM,KAAK;AAAA,cACrC,WAAW,OAAO,MAAM,MAAM,MAAM,IAAI,EAAE,OAAO,gCAAgC,CAAC;AAAA,YACpF,CAAC;AAAA,UACH;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF,CAAC;AAGM,SAAS,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,SAAS,eACR,gBAAAV,MAAC,UAAK,eAAW,MAAC,WAAU,yEACzB,uBACH;AAAA,OAEJ;AAAA,IACA,gBAAAA,MAAC,oBAAiB,QAAgB,OAAO,CAAC,QAAQ,UAAU,aAAa,MAAM,GAAG,MAAI,MAAC;AAAA,IACvF,gBAAAA,MAAC,qBAAkB,QAAgB;AAAA,KACrC;AAEJ;",
6
6
  "names": ["Fragment", "useCallback", "useEffect", "useRef", "useState", "Extension", "key", "Extension", "Node", "Plugin", "PluginKey", "Decoration", "DecorationSet", "ReactRenderer", "Extension", "Plugin", "PluginKey", "Decoration", "DecorationSet", "doc", "place", "useCallback", "useEffect", "Extension", "NodeSelection", "Plugin", "PluginKey", "Extension", "Plugin", "PluginKey", "key", "doc", "Popover", "doc", "node", "pos", "jsx", "jsxs", "key", "PluginKey", "Extension", "Plugin", "NodeSelection", "keepFocus", "useCallback", "useEffect", "Popover", "useRef", "jsx", "Popup", "jsx", "doc", "at", "Extension", "Plugin", "PluginKey", "tr", "Node", "DecorationSet", "Decoration", "place", "key", "ReactRenderer", "listed", "cn", "useCallback", "useEffect", "useState", "Extension", "Toolbar", "jsx", "jsxs", "Extension", "doc", "useState", "useCallback", "useEffect", "Toolbar", "Extension", "PluginKey", "NodeViewWrapper", "ReactNodeViewRenderer", "jsx", "jsxs", "Extension", "PluginKey", "ReactNodeViewRenderer", "NodeViewWrapper", "named", "IconButton", "Extension", "Plugin", "PluginKey", "TextSelection", "Decoration", "DecorationSet", "Extension", "Plugin", "PluginKey", "TextSelection", "tr", "TRAILING", "doc", "Decoration", "DecorationSet", "Extension", "Plugin", "PluginKey", "ToolbarButton", "Fragment", "jsx", "jsxs", "Extension", "useRef", "useState", "useEffect", "cn", "useCallback", "card", "failed", "IconButton", "useCallback", "useEffect", "useImperativeHandle", "useRef", "useState", "Extension", "Node", "EditorContent", "cn", "jsx", "jsxs", "Node", "Extension", "useRef", "useState", "useCallback", "cn", "useEffect", "useImperativeHandle", "EditorContent", "Extension", "Plugin", "PluginKey", "Decoration", "DecorationSet", "doc", "textOf", "LISTS", "placeOf", "place", "Extension", "Plugin", "PluginKey", "MenuItem", "Fragment", "jsx", "jsxs", "MenuItem", "LISTS", "document", "useCallback", "useEffect", "useRef", "useState", "TextSelection", "IconCheck", "IconTrash", "cn", "IconButton", "MenuItem", "MenuSeparator", "Fragment", "jsx", "jsxs", "TextSelection", "cn", "useRef", "useState", "useCallback", "useEffect", "IconButton", "IconCheck", "IconTrash", "useCallback", "useEffect", "useRef", "useState", "TextSelection", "EditorContent", "useEditor", "useEditorState", "IconCheck", "IconCopy", "Extension", "Plugin", "PluginKey", "Decoration", "DecorationSet", "doc", "Button", "Card", "cn", "FieldLine", "FilePicker", "richTextClassName", "Fragment", "jsx", "jsxs", "doc", "useState", "Card", "Button", "IconCheck", "IconCopy", "key", "useRef", "useEffect", "useCallback", "value", "held", "editor", "waiting", "useEditor", "richTextClassName", "cn", "TextSelection", "useEditorState", "choose", "FieldLine", "EditorContent", "FilePicker", "useEffect", "useLayoutEffect", "useRef", "useState", "EditorContent", "useEditor", "useEditorState", "cn", "richTextClassName", "Fragment", "jsx", "jsxs", "useRef", "useEffect", "useState", "useEditor", "richTextClassName", "cn", "useLayoutEffect", "useEditorState", "EditorContent"]
7
7
  }