// The document editor: one TipTap document for all sections and blocks, // hosted in light DOM (so the host's stylesheet reaches it), with the bubble // menu, the "/", "@" and "[" menus, the block menu on the drag handle, the // accept/reject pair in the margin beside a clicked suggestion, comments as // notes in the margin beside their text (clamped; in full when the caret is // in the text or the note is clicked), the link / reference / comment / // math popovers drawn by Lit next to it, and the count of words and // characters as a note at the bottom left of the screen. The asks made on // the document show here too: the section at work gets a moving ink line, // the margin says who is at it and for how long (with Stop), each ask's // proposals get a group head (what, who, how long, take all, drop all) // before the first of them and its reply and receipt in the margin, and the // keyboard steps through proposals: ⇥ ⇧⇥ between them, ⌘⏎ takes, ⌘⌫ drops, // Esc leaves them. import { LitElement, html, nothing, type PropertyValues } from 'lit'; import { SignalWatcher } from '@lit-labs/signals'; import { Editor, Extension, posToDOMRect } from '@tiptap/core'; import type { Node as PMNode } from '@tiptap/pm/model'; import { BubbleMenu } from '@tiptap/extension-bubble-menu'; import Suggestion, { type SuggestionProps, type SuggestionKeyDownProps } from '@tiptap/suggestion'; import { Plugin, PluginKey, TextSelection } from '@tiptap/pm/state'; import { Decoration, DecorationSet } from '@tiptap/pm/view'; import { bodyExtensions } from '../schema/extensions.ts'; import { refreshSectionViews } from '../schema/views.ts'; import { dfnsIn, emptySectionNode, refsIn, findBlock } from '../doc.ts'; import { slugify } from '../text.ts'; import { countNode, formatLine, percentOf, type CountLine } from '../count.ts'; import { fillBubble, FULL_FEATURES, type InlineFeature } from './bubble.ts'; import type { Ask, CommentView, Draft } from '../draft.ts'; import { seconds, summariseActivity } from '../activity.ts'; import { describeAsk, shortWho } from '../asks.ts'; import type { SuggestionItem } from '../suggestions/list.ts'; import { ALL_BLOCKS, type BlockKind, type PMJson } from '../types.ts'; type MenuItem = { id: string; label: string; hint?: string; data?: Record }; type Menu = { items: MenuItem[]; index: number; x: number; y: number; select: (item: MenuItem) => void }; type Prompt = { kind: 'link' | 'ref' | 'comment'; fields: Record; x: number; y: number; apply: (fields: Record) => void }; type MathEdit = { pos: number; latex: string; x: number; y: number; block: boolean }; type BlockMenu = { x: number; y: number; pos: number; node: PMNode }; /** A suggestion clicked in the text: its id, and where its first line sits. */ type MarginActions = { id: string; y: number; kind: string; who?: string; note?: string }; const SUGGESTION_SELECTOR = 'ins[data-id], del[data-id], span[data-type="modification"][data-id]'; /** Less room than this beside the text (px) and only the comment in full is drawn, over the text. */ const NOTES_MIN = 64; /** Space between stacked notes (px). */ const NOTES_GAP = 6; /** Under this much room (px) the clamped notes are slim and get a third line. */ const NOTES_SLIM = 192; const when = (iso: string): string => new Date(iso).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }); export const SLASH_ITEMS: (MenuItem & { needs?: BlockKind })[] = [ { id: 'paragraph', label: 'Paragraph', hint: 'plain prose' }, { id: 'outline', label: 'Outline note', hint: 'what this section will say' }, { id: 'list', label: 'Bulleted list', needs: 'list' }, { id: 'ordered', label: 'Numbered list', needs: 'ordered' }, { id: 'definitionList', label: 'Definitions', hint: 'term / definition pairs', needs: 'definitionList' }, { id: 'code', label: 'Code block', needs: 'code' }, { id: 'math', label: 'Math block', hint: 'TeX, rendered with KaTeX', needs: 'math' }, { id: 'figure', label: 'Image', needs: 'figure' }, { id: 'section', label: 'New section', hint: 'after this one', needs: 'section' }, { id: 'subsection', label: 'New subsection', hint: 'inside this one', needs: 'section' }, ]; export class DraftEditor extends SignalWatcher(LitElement) { static properties = { kindOf: { attribute: false }, draft: { attribute: false }, content: { attribute: false }, menu: { state: true }, prompt: { state: true }, mathEdit: { state: true }, blockMenu: { state: true }, marginActions: { state: true }, activeComment: { state: true }, replying: { state: true }, focused: { state: true }, openReceipt: { state: true }, now: { state: true }, }; declare draft: Draft | null; /** The document to start from (ProseMirror JSON); later changes reset the editor only when it is a different document. */ declare content: PMJson | null; declare menu: Menu | null; declare prompt: Prompt | null; declare mathEdit: MathEdit | null; declare blockMenu: BlockMenu | null; declare marginActions: MarginActions | null; /** The comment shown in full: the one the caret is in, or the note last clicked. */ declare activeComment: string | null; /** The comment whose note has its reply box open. */ declare replying: string | null; /** The proposal the keyboard is on (a suggestion id): outlined in the text, take and drop beside it. */ declare focused: string | null; /** The ask whose receipt in the margin is unfolded. */ declare openReceipt: string | null; /** Ticks once a second while an ask is out, so the margin can say how long. */ declare now: number; /** The kind of a vault note, by its title, when the host knows (the colour of the square before it). */ declare kindOf: (title: string) => string | undefined; /** The asks whose landing was seen (so the focus goes to a fresh one's first proposal once). */ #landed = new Set(); #groupsKey = ''; #ticker: ReturnType | null = null; #editor: Editor | null = null; #lastEmitted: string | null = null; #bubble: { update: () => void } | null = null; #handleNode: { node: PMNode | null; pos: number } = { node: null, pos: -1 }; /** Room to the right of the text for the notes, in px. */ #room = 0; #resize: ResizeObserver | null = null; constructor() { super(); this.draft = null; this.content = null; this.menu = null; this.prompt = null; this.mathEdit = null; this.blockMenu = null; this.marginActions = null; this.activeComment = null; this.replying = null; this.focused = null; this.openReceipt = null; this.now = 0; this.kindOf = () => undefined; } protected override createRenderRoot() { return this; } get editor(): Editor | null { return this.#editor; } #blocks(): Set { return new Set(this.draft?.config.blocks ?? ALL_BLOCKS); } override firstUpdated(): void { const draft = this.draft; if (!draft) throw new Error(' needs a .draft'); const cfg = draft.config; const surface = this.querySelector('.surface') as HTMLElement; const bubbleEl = document.createElement('div'); const editor = new Editor({ element: surface, extensions: [ ...bodyExtensions({ blocks: cfg.blocks, hooks: { onMathClick: (node, pos) => this.#openMath(node, pos), newId: draft.newId, ...(cfg.upload ? { upload: cfg.upload } : {}), ...(cfg.blobUrl ? { blobUrl: cfg.blobUrl } : {}), }, extensions: cfg.extensions, collaboration: cfg.collaboration, onHandleNode: (info) => (this.#handleNode = info), }), BubbleMenu.configure({ element: bubbleEl, appendTo: () => this.querySelector('.chrome') as HTMLElement, shouldShow: ({ editor: e, state, from, to }) => { if (from === to || !e.isEditable) return false; const $from = state.selection.$from; return $from.parent.type.name !== 'codeBlock' && !('node' in state.selection); }, options: { placement: 'top-start' }, }), this.#suggestions(), this.#groups(), ], ...(cfg.collaboration ? {} : { content: (this.content ?? { type: 'doc', content: [] }) as never }), editorProps: { attributes: { class: 'body', spellcheck: 'true' }, handleKeyDown: (_view, e) => { if (this.#focusKey(e)) return true; if ((e.metaKey || e.ctrlKey) && !e.altKey) { const k = e.key.toLowerCase(); if (k === 'k') { e.preventDefault(); this.#linkPrompt(); return true; } if (k === 'r' && e.shiftKey) { e.preventDefault(); this.#refPrompt(); return true; } if (k === 'm' && e.shiftKey) { e.preventDefault(); this.#commentPrompt(); return true; } if (k === 'm') { e.preventDefault(); const { from, to } = editor.state.selection; const latex = editor.state.doc.textBetween(from, to, ' '); if (latex) editor.chain().focus().deleteRange({ from, to }).insertInlineMath({ latex }).run(); return true; } } if (e.key === 'Escape' && (this.prompt || this.mathEdit || this.blockMenu || this.marginActions)) { this.prompt = null; this.mathEdit = null; this.blockMenu = null; this.marginActions = null; return true; } return false; }, }, onUpdate: ({ editor: e }) => { const json = e.getJSON() as PMJson; this.#lastEmitted = JSON.stringify(json); cfg.onChange?.(json); this.dispatchEvent(new CustomEvent('change', { detail: json })); }, onTransaction: () => { refreshSectionViews(); this.#syncActiveComment(); }, onSelectionUpdate: () => { this.#bubble?.update(); this.#syncActiveComment(); }, }); this.#editor = editor; // the BubbleMenu plugin owns bubbleEl (it appends and shows it over a selection): fill it, start hidden const kinds: InlineFeature[] = [...FULL_FEATURES, 'comment']; this.#bubble = fillBubble(bubbleEl, editor, kinds, { onLink: () => this.#linkPrompt(), onRef: () => this.#refPrompt(), onComment: () => this.#commentPrompt() }); bubbleEl.style.visibility = 'hidden'; this.#lastEmitted = JSON.stringify(editor.getJSON()); // the drag handle doubles as the block menu's button; a suggestion // clicked in the text gets accept/reject in the margin beside it this.addEventListener('click', (e) => { const t = e.target as HTMLElement; if (t.closest('.drag-handle')) { e.preventDefault(); this.#openBlockMenu(t.closest('.drag-handle') as HTMLElement); } else if (!t.closest('.block-menu')) this.blockMenu = null; const sug = t.closest(SUGGESTION_SELECTOR) as HTMLElement | null; if (sug && surface.contains(sug)) this.#openMarginActions(sug); else if (!t.closest('.margin-actions')) this.marginActions = null; }); draft.attach(editor); for (const a of draft.asks.get()) if (a.status !== 'queued' && a.status !== 'working') this.#landed.add(a.id); refreshSectionViews(); // the notes beside the text need to know how much margin there is this.#resize = new ResizeObserver(() => this.#measureRoom()); this.#resize.observe(this); this.#resize.observe(document.documentElement); this.#measureRoom(); } override updated(changed: PropertyValues): void { this.#layoutNotes(); this.#highlightActiveComment(); this.#syncAsks(); if (changed.has('replying') && this.replying) requestAnimationFrame(() => (this.querySelector('.margin-note.on .reply-form input') as HTMLInputElement | null)?.focus()); if (changed.has('content') && this.#editor && this.content && !this.draft?.config.collaboration) { // an external replacement of the document (a fresh load): reset the editor const json = this.content; if (JSON.stringify(json) !== this.#lastEmitted && this.#lastEmitted !== null && changed.get('content') !== undefined && this.#isForeign(json)) { this.draft?.setContent(json); this.#lastEmitted = JSON.stringify(this.#editor.getJSON()); refreshSectionViews(); } } // after the editor's own refocus settles if (changed.has('prompt') && this.prompt) requestAnimationFrame(() => (this.querySelector('.prompt input, .prompt textarea') as HTMLInputElement | null)?.focus()); if (changed.has('mathEdit') && this.mathEdit) requestAnimationFrame(() => (this.querySelector('.math-edit textarea') as HTMLTextAreaElement | null)?.focus()); } /** Does this document come from somewhere other than our own last emit? Sections and their blocks decide; nested nodes may carry ids of their own. */ #isForeign(json: PMJson): boolean { const ids = (n: PMJson): string => { const kids = (n.content ?? []).filter((c) => c.type !== 'text' && c.type !== 'sectionTitle'); return `${n.type}:${String(n.attrs?.id ?? '')}(${kids.map((c) => (c.type === 'section' || n.type === 'doc' ? ids(c) : `${c.type}:${String(c.attrs?.id ?? '')}`)).join(',')})`; }; return ids(this.#editor?.getJSON() as PMJson) !== ids(json); } override disconnectedCallback(): void { super.disconnectedCallback(); if (this.#ticker) clearInterval(this.#ticker); this.#ticker = null; this.#resize?.disconnect(); this.#resize = null; this.draft?.detach(); this.#editor?.destroy(); this.#editor = null; } focusStart(): void { this.#editor?.chain().focus('start').run(); } /** The very first section of an empty document. */ addFirstSection(): void { const e = this.#editor; const d = this.draft; if (!e || !d) return; const json = emptySectionNode(d.newId(), d.newId()); e.chain() .command(({ tr, state, dispatch }) => { tr.insert(0, state.schema.nodeFromJSON(json)); tr.setSelection(TextSelection.create(tr.doc, 2)); dispatch?.(tr.scrollIntoView()); return true; }) .focus() .run(); } // --- positions --------------------------------------------------------------------------------- #local(rect: DOMRect | null | undefined): { x: number; y: number } { const host = this.getBoundingClientRect(); if (!rect) return { x: 0, y: 0 }; return { x: Math.max(0, rect.left - host.left), y: rect.bottom - host.top }; } #selectionPos(): { x: number; y: number } { const e = this.#editor!; const { from, to } = e.state.selection; return this.#local(posToDOMRect(e.view, from, to)); } // --- prompts ------------------------------------------------------------------------------------ #linkPrompt(): void { const e = this.#editor; if (!e || e.state.selection.empty) return; const href = (e.getAttributes('link').href as string | undefined) ?? ''; this.prompt = { kind: 'link', fields: { uri: href }, ...this.#selectionPos(), apply: (f) => { const uri = f.uri?.trim(); if (uri) e.chain().focus().extendMarkRange('link').setLink({ href: uri }).run(); else e.chain().focus().extendMarkRange('link').unsetLink().run(); }, }; } #refPrompt(range?: { from: number; to: number }, key?: string): void { const e = this.#editor; if (!e) return; const sel = range ?? { from: e.state.selection.from, to: e.state.selection.to }; if (sel.from === sel.to) return; const cur = e.getAttributes('ref'); this.prompt = { kind: 'ref', fields: { key: key ?? (cur.key as string | undefined) ?? e.state.doc.textBetween(sel.from, sel.to, ' ').trim(), title: (cur.title as string) ?? '', uri: (cur.uri as string) ?? '' }, ...this.#local(posToDOMRect(e.view, sel.from, sel.to)), apply: (f) => { const k = f.key?.trim(); if (!k) return; e.chain().focus().setTextSelection(sel).setMark('ref', { key: k, title: f.title?.trim() || null, uri: f.uri?.trim() || null }).run(); }, }; } /** Comment on the selection, or on a whole block. */ #commentPrompt(block?: { pos: number; node: PMNode }): void { const e = this.#editor; const d = this.draft; if (!e || !d) return; const sel = block ? { from: block.pos + 1, to: block.pos + block.node.nodeSize - 1 } : { from: e.state.selection.from, to: e.state.selection.to }; const at = block ? this.#local(posToDOMRect(e.view, block.pos, block.pos + 1)) : this.#selectionPos(); this.prompt = { kind: 'comment', fields: { text: '' }, ...at, apply: (f) => { const text = f.text?.trim(); if (!text) return; d.comment(text, sel.to > sel.from ? sel : undefined, block ? String(block.node.attrs.id ?? '') : undefined); e.commands.focus(); }, }; } #openMath(node: PMNode, pos: number): void { const e = this.#editor; if (!e) return; const rect = posToDOMRect(e.view, pos, pos + node.nodeSize); this.mathEdit = { pos, latex: String(node.attrs.latex ?? ''), block: node.type.name === 'blockMath', ...this.#local(rect) }; } #setMath(latex: string): void { const e = this.#editor; const m = this.mathEdit; if (!e || !m) return; e.commands.command(({ tr, dispatch }) => { const node = tr.doc.nodeAt(m.pos); if (!node || !node.type.name.endsWith('Math')) return false; tr.setNodeMarkup(m.pos, undefined, { ...node.attrs, latex }); dispatch?.(tr); return true; }); this.mathEdit = { ...m, latex }; } // --- the margin: accept / reject beside a clicked suggestion ------------------------------- #openMarginActions(el: HTMLElement): void { const d = this.draft; if (!d) return; let id: string; try { id = String(JSON.parse(el.dataset.id ?? '') as string | number); } catch { id = el.dataset.id ?? ''; } const item = d.suggestions.get().find((s) => s.id === id); if (!item) return; // the first line the suggestion is on, in the editor's own coordinates const rect = el.getClientRects()[0] ?? el.getBoundingClientRect(); const host = this.getBoundingClientRect(); const who = item.meta?.author; this.marginActions = { id, y: rect.top - host.top, kind: item.kind, ...(who ? { who: who.name } : {}), ...(item.meta?.note ? { note: item.meta.note } : {}) }; this.focused = id; } #marginAction(accept: boolean): void { const m = this.marginActions; this.marginActions = null; if (!m || !this.draft) return; if (accept) this.draft.accept(m.id); else this.draft.reject(m.id); this.#editor?.commands.focus(); } // --- the margin: comments beside their text --------------------------------------------------- /** The comment the caret is in (or touches) is the one shown in full. */ #syncActiveComment(): void { const e = this.#editor; if (!e) return; const { $head, empty } = e.state.selection; const marks = empty ? [...$head.marks(), ...($head.nodeAfter?.marks ?? [])] : $head.marks(); const m = marks.find((mk) => mk.type.name === 'comment'); const id = m ? String(m.attrs.id) : null; if (id !== this.activeComment) { this.activeComment = id; this.replying = null; } } /** How far the notes may reach: to the next thing beside the text (a sidebar), else the window's edge. */ #measureRoom(): void { const host = this.getBoundingClientRect(); if (!host.width) return; // not shown // the text may stop short of the host's edge (blocks keep to the measure): the notes start where it stops const block = this.querySelector('.ProseMirror p') as HTMLElement | null; const textRight = block ? Math.min(host.right, block.getBoundingClientRect().right) : host.right; this.style.setProperty('--notes-left', `${Math.round(textRight - host.left)}px`); let limit = document.documentElement.clientWidth; for (let el: HTMLElement | null = this; el && el !== document.body; el = el.parentElement) { const next = el.nextElementSibling as HTMLElement | null; if (!next) continue; const r = next.getBoundingClientRect(); if (r.width > 0 && r.left >= host.right - 1 && r.bottom > host.top && r.top < host.bottom) { limit = Math.min(limit, r.left); break; } } const room = Math.max(0, Math.round(limit - textRight)); if (room !== this.#room) { this.#room = room; this.style.setProperty('--notes-room', `${room}px`); // slim notes (a column under 12rem) get a third line, so a short comment still reads whole this.dataset.notes = room < NOTES_SLIM ? 'slim' : 'wide'; } this.style.setProperty('--notes-host', `${Math.round(host.width)}px`); this.requestUpdate(); } /** Notes start beside their text and move down so none overlaps; the one in full stays at its text, the ones above it make way. */ #layoutNotes(): void { const notes = [...this.querySelectorAll('.margin-notes:not(.narrow) .margin-note')] as HTMLElement[]; if (!notes.length) return; const items = notes.map((el) => ({ el, y: Number(el.dataset.y ?? 0), h: el.offsetHeight, top: 0 })); let floor = -Infinity; for (const it of items) { it.top = Math.max(it.y, floor); floor = it.top + it.h + NOTES_GAP; } const on = items.findIndex((it) => it.el.classList.contains('on')); if (on > 0 && items[on]!.top > items[on]!.y) { // lift the run of notes pressing on it, as far as the top allows let first = on; while (first > 0 && items[first - 1]!.top + items[first - 1]!.h + NOTES_GAP >= items[first]!.top) first--; const lift = Math.min(items[on]!.top - items[on]!.y, Math.max(0, items[first]!.top)); for (let i = first; i <= on; i++) items[i]!.top -= lift; } for (const it of items) it.el.style.top = `${it.top}px`; } #highlightActiveComment(): void { for (const el of this.querySelectorAll('mark.comment.on')) el.classList.remove('on'); if (this.activeComment) for (const el of this.querySelectorAll(`mark[data-comment="${CSS.escape(this.activeComment)}"]`)) el.classList.add('on'); } // --- the asks: the section at work, the proposals stepped through, the group heads --------------- /** The proposals in the document, in document order. */ #pendingIds(): string[] { return this.draft?.suggestions.get().map((s) => s.id) ?? []; } /** The element a suggestion is drawn with (its first). */ #elementOf(id: string): HTMLElement | null { for (const el of this.querySelectorAll(SUGGESTION_SELECTOR)) { let got: string; try { got = String(JSON.parse(el.dataset.id ?? '') as string | number); } catch { got = el.dataset.id ?? ''; } if (got === id) return el; } return null; } /** Put the keyboard on a proposal: outlined, scrolled to, take and drop beside it; null leaves them. */ focusSuggestion(id: string | null): void { if (!id) { this.focused = null; this.marginActions = null; return; } const el = this.#elementOf(id); if (!el) return; el.scrollIntoView({ block: 'nearest' }); this.#openMarginActions(el); this.#editor?.view.focus(); } #stepFocus(dir: 1 | -1): void { const ids = this.#pendingIds(); if (!ids.length) return; const i = ids.indexOf(this.focused ?? ''); this.focusSuggestion(ids[i < 0 ? (dir > 0 ? 0 : ids.length - 1) : (i + dir + ids.length) % ids.length]!); } /** Take or drop the focused proposal, and move to the next (the one before it when it was the last). */ #decide(accept: boolean): void { const d = this.draft; const id = this.focused; if (!d || !id) return; const ids = this.#pendingIds(); const i = ids.indexOf(id); const next = ids[i + 1] ?? ids[i - 1] ?? null; this.marginActions = null; if (accept) d.accept(id); else d.reject(id); this.focused = next; if (next) requestAnimationFrame(() => this.focusSuggestion(next)); } /** ⇥ and ⇧⇥ between proposals, ⌘⏎ takes, ⌘⌫ drops, Esc leaves them: only while the keyboard is on one. */ #focusKey(e: KeyboardEvent): boolean { const d = this.draft; if (!d || !this.focused || !d.suggestions.get().some((s) => s.id === this.focused)) return false; const mod = e.metaKey || e.ctrlKey; if (e.key === 'Tab' && !mod && !e.altKey) { e.preventDefault(); this.#stepFocus(e.shiftKey ? -1 : 1); return true; } if (mod && e.key === 'Enter') { e.preventDefault(); this.#decide(true); return true; } if (mod && e.key === 'Backspace') { e.preventDefault(); this.#decide(false); return true; } if (e.key === 'Escape') { this.focusSuggestion(null); return true; } return false; } /** Where an ask's scope is in the document, as a position the margin can be placed at. */ #scopePos(a: Ask): number | null { const e = this.#editor; if (!e) return null; const doc = e.state.doc; const s = a.scope; if (s.kind === 'section' || s.kind === 'note') { const b = findBlock(doc, s.id); return b ? b.pos + 1 : null; } if (s.kind === 'selection') return Math.min(s.from, doc.content.size); return Math.min(1, doc.content.size); } /** The proposals an ask made that are still in the document. */ #pendingOf(a: Ask): SuggestionItem[] { const mine = new Set(a.suggestions); return this.draft?.suggestions.get().filter((s) => mine.has(s.id)) ?? []; } /** After each update: the sections at work marked, a fresh landing's first proposal focused, the group heads redrawn, the clock ticking while an ask is out. */ #syncAsks(): void { const d = this.draft; const e = this.#editor; if (!d || !e) return; const asks = d.asks.get(); // the sections (and notes) at work for (const el of this.querySelectorAll('.working')) el.classList.remove('working'); for (const a of asks) { if (a.status !== 'working' || (a.scope.kind !== 'section' && a.scope.kind !== 'note')) continue; const b = findBlock(e.state.doc, a.scope.id); const dom = b ? (e.view.nodeDOM(b.pos) as HTMLElement | null) : null; if (!dom) continue; dom.classList.add('working'); dom.querySelector(':scope > .sec-body > .sec-head')?.classList.add('working'); } // a fresh landing: the keyboard goes to its first proposal for (const a of asks) { if (a.status === 'queued' || a.status === 'working' || this.#landed.has(a.id)) continue; this.#landed.add(a.id); const first = this.#pendingOf(a)[0]; if (first) requestAnimationFrame(() => this.focusSuggestion(first.id)); } // the focus is dropped with its proposal; the one focused is outlined if (this.focused && !d.suggestions.get().some((s) => s.id === this.focused)) { this.focused = null; this.marginActions = null; } // the group heads follow the asks and what is left of their proposals, the outline follows the focus: both are decorations (a class set on the text's own DOM would have the editor read the text back) const key = `${asks.map((a) => `${a.id}:${a.status}:${this.#pendingOf(a).length}`).join('|')}#${this.focused ?? ''}`; if (key !== this.#groupsKey) { this.#groupsKey = key; e.view.dispatch(e.state.tr.setMeta('draft-groups', true)); } // the clock const busy = asks.some((a) => a.status === 'working'); if (busy && !this.#ticker) this.#ticker = setInterval(() => (this.now = Date.now()), 1000); else if (!busy && this.#ticker) { clearInterval(this.#ticker); this.#ticker = null; } } /** The notes a block draws on, as a line under it: a square in the kind's colour, the title. */ #draws(draws: unknown[]): HTMLElement { const el = document.createElement('div'); el.className = 'draws'; el.contentEditable = 'false'; for (const d of draws) { const title = typeof d === 'string' ? d : d && typeof d === 'object' && typeof (d as { title?: unknown }).title === 'string' ? (d as { title: string }).title : ''; if (!title) continue; const kind = (d && typeof d === 'object' && typeof (d as { kind?: unknown }).kind === 'string' ? (d as { kind: string }).kind : undefined) ?? this.kindOf(title) ?? ''; const k = document.createElement('span'); k.className = `k ${kind}`; k.title = kind || 'a note in your vault'; el.append(k, `${title} `); } return el; } /** A group head before the first proposal of each ask (what was asked, who answered, how long, take all, drop all), the draws under a block, the outline on the focused proposal. */ #groups() { const self = this; return Extension.create({ name: 'draftGroups', addProseMirrorPlugins() { return [ new Plugin({ key: new PluginKey('draftGroups'), props: { decorations(state) { const d = self.draft; if (!d) return DecorationSet.empty; const decos: Decoration[] = []; for (const a of d.asks.get()) { if (a.status === 'queued' || a.status === 'working') continue; const mine = self.#pendingOf(a); if (!mine.length) continue; const first = mine.reduce((m, s) => (s.from < m.from ? s : m)); const $p = state.doc.resolve(Math.min(first.from, state.doc.content.size)); const parent = $p.parent.type.name; const pos = parent === 'doc' || parent === 'section' ? $p.pos : $p.before(Math.max(1, $p.depth)); decos.push(Decoration.widget(pos, () => self.#groupHead(a, mine), { side: -1, key: `group-${a.id}-${mine.length}` })); } // under a block that draws on the writer's notes, their names state.doc.descendants((node, pos) => { if (node.type.name === 'section') return true; const draws = node.attrs.draws as unknown; if (node.isBlock && Array.isArray(draws) && draws.length) decos.push(Decoration.widget(pos + node.nodeSize, () => self.#draws(draws), { side: -1, key: `draws-${String(node.attrs.id ?? pos)}-${JSON.stringify(draws)}` })); return false; }); // the proposal the keyboard is on: outlined, block by block when it is blocks, else over its text const on = self.focused ? d.suggestions.get().find((s) => s.id === self.focused) : undefined; if (on) { const size = state.doc.content.size; const from = Math.max(0, Math.min(on.from, size)); const to = Math.max(from, Math.min(on.to, size)); if (on.blockLevel) { state.doc.nodesBetween(from, to, (node, pos) => { if (!node.isBlock) return false; if (pos >= from && pos + node.nodeSize <= to) { decos.push(Decoration.node(pos, pos + node.nodeSize, { class: 'focus' })); return false; } return true; }); } else if (to > from) decos.push(Decoration.inline(from, to, { class: 'focus' })); } return DecorationSet.create(state.doc, decos); }, }, }), ]; }, }); } #groupHead(a: Ask, mine: SuggestionItem[]): HTMLElement { const d = this.draft!; const el = document.createElement('div'); el.className = 'draft-group'; el.contentEditable = 'false'; el.dataset.ask = a.id; const n = mine.length; const kinds = new Set(mine.map((s) => s.kind)); const one = kinds.size === 1 ? [...kinds][0] : undefined; const what = one === 'outline-section' ? `${n} section${n === 1 ? '' : 's'} proposed` : one === 'outline-note' || one === 'outline-points' ? `${n} note${n === 1 ? '' : 's'} proposed` : one === 'block-expansion' ? `${n} paragraph${n === 1 ? '' : 's'} written` : `${n} proposal${n === 1 ? '' : 's'}`; const who = shortWho(mine[0]?.meta?.author?.name ?? ''); const took = a.activity?.ended && a.activity.started ? seconds(a.activity.ended - a.activity.started) : ''; const b = document.createElement('b'); b.textContent = what; const of = document.createElement('span'); of.className = 'of'; of.textContent = [describeAsk(a, this.#editor?.state.doc ?? null), who, took].filter(Boolean).join(' · '); const acts = document.createElement('span'); acts.className = 'acts'; const btn = (label: string, icon: string, title: string, act: () => void) => { const x = document.createElement('button'); x.type = 'button'; x.className = 'btn btn-quiet btn-small'; x.title = title; x.innerHTML = ` ${label}`; x.addEventListener('mousedown', (ev) => ev.preventDefault()); x.addEventListener('click', act); return x; }; acts.append(btn('Take all', 'check-check', 'Take every proposal of this ask', () => d.takeAsk(a.id)), btn('Drop all', 'x', 'Drop every proposal of this ask', () => d.dropAsk(a.id))); el.append(b, of, acts); return el; } /** The margin: the comments beside their text, and the asks: who is at work where (with Stop), and each answered ask's reply and receipt at its proposals. */ #renderMargin() { const d = this.draft; const e = this.#editor; if (!d || !e) return nothing; d.version.get(); // the notes follow their text as it moves const narrow = this.#room < NOTES_MIN; const host = this.getBoundingClientRect(); const at = (pos: number) => { try { const r = e.view.coordsAtPos(Math.max(0, Math.min(pos, e.state.doc.content.size))); return { top: r.top - host.top, bottom: r.bottom - host.top }; } catch { return { top: 0, bottom: 0 }; } }; const items: { top: number; bottom: number; render: () => unknown }[] = []; for (const c of d.comments.get()) { if (c.resolved || c.from === undefined || c.to === undefined) continue; const p = at(c.from); items.push({ ...p, render: () => this.#renderNote(c, narrow ? p.bottom + 4 : p.top, narrow) }); } for (const a of d.asks.get()) { if (a.status === 'queued') continue; const mine = this.#pendingOf(a); const pos = mine.length ? Math.min(...mine.map((s) => s.from)) : this.#scopePos(a); if (pos === null) continue; const p = at(pos); items.push({ ...p, render: () => (a.status === 'working' ? this.#renderAtWork(a, p.top) : this.#renderReceipt(a, p.top, narrow)) }); } if (!items.length) return nothing; items.sort((x, y) => x.top - y.top); return html`
${items.map((it) => it.render())}
`; } /** Who is at it, for how long, the current step, and Stop. */ #renderAtWork(a: Ask, y: number) { const d = this.draft!; const who = shortWho(d.assistant.get()?.name ?? 'the assistant'); const started = a.activity?.started ?? Date.parse(a.at); const step = a.activity?.steps.at(-1)?.text ?? 'sending'; const placed = a.suggestions.length; return html`
!(ev.target as HTMLElement).closest('button') && ev.preventDefault()}>
${who}${seconds(Math.max(this.now, started) - started)}
${placed ? `${placed} placed so far · ` : ''}${step}
`; } /** What the assistant had to say, and the receipt of what it did, folded. */ #renderReceipt(a: Ask, y: number, narrow: boolean) { const d = this.draft!; const on = this.openReceipt === a.id; if (narrow && !on) return nothing; const act = a.activity; const who = act ? shortWho(d.suggestions.get().find((s) => a.suggestions.includes(s.id))?.meta?.author?.name ?? d.assistant.get()?.name ?? '') : ''; const took = act?.ended ? seconds(act.ended - act.started) : ''; const head = [describeAsk(a, this.#editor?.state.doc ?? null), who, took].filter(Boolean).join(' · '); const controls = (t: EventTarget | null) => !!(t as HTMLElement | null)?.closest('button, details, summary'); return html`
!controls(ev.target) && ev.preventDefault()} @click=${(ev: Event) => { if (controls(ev.target)) return; this.openReceipt = on ? null : a.id; }} >
${head}
${a.reply ? html`
${a.reply}
` : nothing} ${on && act ? html`
ev.stopPropagation()}> ${summariseActivity(act)}
    ${act.steps.map((s) => html`
  1. ${seconds(s.at)} ${s.kind === 'tool' ? html`${s.text} ${s.input ?? ''}${s.result !== undefined ? html` ${s.result}` : nothing}` : s.text}
  2. `)}
${act.text ? html`
The reply as it came (${act.text.length.toLocaleString()} characters)
${act.text}
` : nothing}
` : nothing}
`; } // --- the block menu -------------------------------------------------------------------------- #openBlockMenu(handle: HTMLElement): void { const { node, pos } = this.#handleNode; if (!node || pos < 0) return; const rect = handle.getBoundingClientRect(); this.blockMenu = { ...this.#local(rect), pos, node }; } #blockAction(what: 'comment' | 'delete' | 'above' | 'below' | 'outline'): void { const e = this.#editor; const m = this.blockMenu; this.blockMenu = null; if (!e || !m) return; const cur = e.state.doc.nodeAt(m.pos); if (cur !== m.node) return; switch (what) { case 'comment': this.#commentPrompt({ pos: m.pos, node: m.node }); return; case 'delete': e.chain().focus().deleteRange({ from: m.pos, to: m.pos + m.node.nodeSize }).run(); return; case 'outline': e.chain() .focus() .command(({ tr, dispatch }) => { tr.setNodeMarkup(m.pos, undefined, { ...m.node.attrs, outline: !m.node.attrs.outline }); dispatch?.(tr); return true; }) .run(); return; case 'above': case 'below': { const at = what === 'above' ? m.pos : m.pos + m.node.nodeSize; e.chain() .command(({ tr, state, dispatch }) => { tr.insert(at, state.schema.nodes.paragraph!.create()); tr.setSelection(TextSelection.create(tr.doc, at + 1)); dispatch?.(tr.scrollIntoView()); return true; }) .focus() .run(); return; } } } // --- the "/", "@", "[" menus -------------------------------------------------------------------- #suggestions() { const self = this; const render = (select: (item: MenuItem, props: SuggestionProps) => void) => () => { let current: SuggestionProps | null = null; const show = (props: SuggestionProps) => { current = props; const items = props.items as MenuItem[]; self.menu = items.length ? { items, index: 0, ...self.#local(props.clientRect?.() ?? null), select: (item) => select(item, props) } : null; }; return { onStart: show, onUpdate: show, onExit: () => { current = null; self.menu = null; }, onKeyDown: ({ event }: SuggestionKeyDownProps) => { const m = self.menu; if (!m || !current) return false; if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { const n = m.items.length; self.menu = { ...m, index: (m.index + (event.key === 'ArrowDown' ? 1 : n - 1)) % n }; return true; } if (event.key === 'Enter' || event.key === 'Tab') { const it = m.items[m.index]; if (it) m.select(it); return true; } if (event.key === 'Escape') { self.menu = null; return true; } return false; }, }; }; return Extension.create({ name: 'draftMenus', addProseMirrorPlugins() { const editor = this.editor; const refs = self.draft?.config.references; return [ Suggestion({ editor, char: '/', pluginKey: new PluginKey('slash'), startOfLine: true, allow: ({ state, range }) => { const $from = state.doc.resolve(range.from); const inList = $from.node(-1)?.type.name === 'listItem'; return $from.parent.type.name === 'paragraph' && !inList && $from.parent.textContent.startsWith('/') && $from.parentOffset === 0; }, items: ({ query }) => { const blocks = self.#blocks(); return SLASH_ITEMS.filter((i) => !i.needs || blocks.has(i.needs)).filter((i) => !query || i.label.toLowerCase().includes(query.toLowerCase()) || i.id.includes(query.toLowerCase())); }, render: render((item, props) => self.#runSlash(item.id, props.range)), }), Suggestion({ editor, char: '@', pluginKey: new PluginKey('dfnRefs'), items: async ({ query }) => { const q = query.toLowerCase(); const items: MenuItem[] = dfnsIn(editor.state.doc) .filter((d) => !q || d.text.toLowerCase().includes(q)) .slice(0, 6) .map((d) => ({ id: d.id, label: d.text, hint: `#${d.id}` })); // then the terms of the imported references if (refs?.searchTerms && query.trim()) { try { for (const t of (await refs.searchTerms(query.trim())).slice(0, 6)) { items.push({ id: `ext:${t.ref}:${t.href}`, label: t.text, hint: `[${t.ref}]${t.hint ? ` ${t.hint}` : ''}`, data: { ref: t.ref, uri: t.href } }); } } catch { // the catalogue is a convenience; offline it just isn't there } } if (query.trim() && !items.some((i) => i.label.toLowerCase() === q)) items.push({ id: `dfn-${slugify(query.trim())}`, label: query.trim(), hint: 'reference this term' }); return items; }, render: render((item, props) => { const attrs = item.data ? { id: null, ref: item.data.ref, uri: item.data.uri } : { id: item.id }; editor .chain() .focus() .insertContentAt(props.range, [{ type: 'text', text: item.label, marks: [{ type: 'dfnRef', attrs }] }, { type: 'text', text: ' ' }]) .run(); }), }), Suggestion({ editor, char: '[', pluginKey: new PluginKey('refs'), allowedPrefixes: null, items: async ({ query }) => { const q = query.toLowerCase(); const items: MenuItem[] = refsIn(editor.state.doc) .filter((r) => !q || r.key.toLowerCase().includes(q) || (r.title ?? '').toLowerCase().includes(q)) .slice(0, 6) .map((r) => ({ id: r.key, label: `[${r.key}]`, ...(r.title ? { hint: r.title } : {}) })); // then the catalogue if (refs?.searchRefs && query.trim()) { try { for (const r of (await refs.searchRefs(query.trim())).slice(0, 6)) { if (items.some((i) => i.id.toLowerCase() === r.key.toLowerCase())) continue; items.push({ id: `cat:${r.key}`, label: `[${r.key}]`, hint: r.title ?? r.hint ?? r.key, data: { key: r.key, uri: r.href ?? '', title: r.title ?? '' } }); } } catch { // no catalogue, no suggestions } } if (query.trim() && !items.some((i) => i.id.toLowerCase() === q || i.id.toLowerCase() === `cat:${q}`)) items.push({ id: `new:${query.trim()}`, label: `[${query.trim()}]`, hint: 'new reference: add a title and URL' }); return items; }, render: render((item, props) => { const isNew = item.id.startsWith('new:'); const key = item.data ? item.data.key! : isNew ? item.id.slice(4) : item.id; const attrs: Record = { key }; if (item.data) { attrs.uri = item.data.uri || null; attrs.title = item.data.title || null; } const from = props.range.from; editor .chain() .focus() .insertContentAt(props.range, [{ type: 'text', text: key, marks: [{ type: 'ref', attrs }] }, { type: 'text', text: ' ' }]) .run(); if (isNew) self.#refPrompt({ from, to: from + key.length }, key); }), }), ]; }, }); } #runSlash(id: string, range: { from: number; to: number }): void { const e = this.#editor; const d = this.draft; if (!e || !d) return; const chain = e.chain().focus().deleteRange(range); switch (id) { case 'paragraph': chain.run(); return; case 'outline': chain.updateAttributes('paragraph', { outline: true }).run(); return; case 'list': chain.toggleBulletList().run(); return; case 'ordered': chain.toggleOrderedList().run(); return; case 'code': chain.setCodeBlock().run(); return; case 'math': { chain.insertContent({ type: 'blockMath', attrs: { latex: '' } }).run(); // edit it right away: the last math block at or before the caret let found: { node: PMNode; pos: number } | null = null; e.state.doc.nodesBetween(0, e.state.selection.to, (node, pos) => { if (node.type.name === 'blockMath') found = { node, pos }; return true; }); if (found) this.#openMath((found as { node: PMNode; pos: number }).node, (found as { node: PMNode; pos: number }).pos); return; } case 'definitionList': { chain.insertContent({ type: 'definitionList', content: [{ type: 'definitionItem', content: [{ type: 'definitionTerm' }, { type: 'definitionDescription' }] }] }).run(); const $from = e.state.selection.$from; if ($from.parent.type.name === 'definitionDescription') e.commands.setTextSelection($from.pos - 2); // the empty term before it return; } case 'figure': chain.insertContent({ type: 'figure', attrs: { cid: '', mimeType: '', size: 0, alt: '' } }).run(); return; case 'section': case 'subsection': { chain.run(); const $from = e.state.selection.$from; let secPos = -1; for (let depth = $from.depth; depth > 0; depth--) { if ($from.node(depth).type.name === 'section') { secPos = $from.before(depth); break; } } if (secPos < 0) return; const sec = e.state.doc.nodeAt(secPos)!; const at = id === 'section' ? secPos + sec.nodeSize : secPos + sec.nodeSize - 1; const json = emptySectionNode(d.newId(), d.newId()); e.chain() .command(({ tr, state, dispatch }) => { tr.insert(at, state.schema.nodeFromJSON(json)); tr.setSelection(TextSelection.create(tr.doc, at + 2)); dispatch?.(tr.scrollIntoView()); return true; }) .focus() .run(); return; } default: chain.run(); } } // --- rendering ---------------------------------------------------------------------------------- #renderMenu() { const m = this.menu; if (!m) return nothing; return html``; } #renderBlockMenu() { const m = this.blockMenu; if (!m) return nothing; const kind = m.node.type.name; const what = kind === 'section' ? 'section' : kind === 'codeBlock' ? 'code block' : kind === 'figure' ? 'image' : kind.endsWith('List') ? 'list' : 'block'; const id = String(m.node.attrs.id ?? ''); const blk = id ? findBlock(this.#editor!.state.doc, id) : undefined; return html``; } #renderMarginActions() { const m = this.marginActions; if (!m || !this.draft?.suggestions.get().some((s) => s.id === m.id)) return nothing; const detail = [m.who, m.note].filter(Boolean).join(': '); return html`
e.preventDefault()}>
`; } #renderNote(c: CommentView, y: number, narrow: boolean) { const d = this.draft!; const on = c.id === this.activeComment; if (narrow && !on) return nothing; const replying = this.replying === c.id; const controls = (t: EventTarget | null) => !!(t as HTMLElement | null)?.closest('button, input, form'); return html`
!controls(ev.target) && ev.preventDefault()} @click=${(ev: Event) => { if (controls(ev.target)) return; if (!on && c.from !== undefined && c.to !== undefined) d.select(Math.min(c.from + 1, c.to)); this.activeComment = c.id; }} >
${c.author.name} ${on ? html`${when(c.at)}` : nothing}
${c.text}
${on ? html`${c.replies.map((r) => html`
${r.author.name} ${r.text}
`)} ${replying ? html`
{ ev.preventDefault(); const input = (ev.target as HTMLFormElement).querySelector('input'); if (input) d.reply(c.id, input.value); this.replying = null; }} > { ev.stopPropagation(); if (ev.key === 'Escape') this.replying = null; }} />
` : html``}` : nothing}
`; } #renderPrompt() { const p = this.prompt; if (!p) return nothing; const onKey = (e: KeyboardEvent) => { e.stopPropagation(); if (e.key === 'Enter' && !(e.target instanceof HTMLTextAreaElement && e.shiftKey)) { e.preventDefault(); this.#applyPrompt(); } else if (e.key === 'Escape') this.prompt = null; }; const field = (name: string, label: string, ph = '') => html``; let body; if (p.kind === 'link') body = field('uri', 'Link URL', 'https://…'); else if (p.kind === 'ref') body = html`${field('key', 'Reference key', 'rfc2119')} ${field('title', 'Title (optional)')} ${field('uri', 'URL (optional)')}`; else body = html``; return html`
e.stopPropagation()}> ${body}
`; } #applyPrompt(): void { const p = this.prompt; if (!p) return; this.prompt = null; p.apply(p.fields); } #renderMathEdit() { const m = this.mathEdit; if (!m) return nothing; return html`
e.stopPropagation()}>
`; } /** The count: this text's words and characters (and whatever the host adds, a book's, a section's), a discreet note at the bottom left of the screen; against a target, how far along. */ #renderCounts() { const cfg = this.draft?.config; const editor = this.draft?.editor.get(); this.draft?.version.get(); if (!editor || cfg?.counts === false) return nothing; const live = countNode(editor.state.doc); const lines: CountLine[] = cfg?.counts ? cfg.counts(live) : [live]; return html`
${lines.map((l) => { const pct = l.target ? percentOf(l.words, l.target) : 0; return html` ${l.label ? html`${l.label}` : nothing}${formatLine(l)} ${l.target ? html`` : nothing} `; })}
`; } override render() { return html`
${this.#renderMargin()}
${this.#renderMenu()} ${this.#renderBlockMenu()} ${this.#renderPrompt()} ${this.#renderMathEdit()} ${this.#renderMarginActions()}
${this.#renderCounts()}`; } } customElements.define('draft-editor', DraftEditor);