// The controller a host holds: it owns the configuration, the suggestion // metadata, the assistant conversation, and (once mounted) the editor. // Components bind to it; hosts call it. import { signal, type Signal } from '@lit-labs/signals'; import type { Editor } from '@tiptap/core'; import type { Node as PMNode } from '@tiptap/pm/model'; import { TextSelection, type Transaction } from '@tiptap/pm/state'; import { applySuggestion, applySuggestions, revertSuggestion, revertSuggestions, selectSuggestion, suggestChangesKey, withSuggestChanges } from '@handlewithcare/prosemirror-suggest-changes'; import { newId } from './ids.ts'; import type { Author, ContextItem, DraftConfig, PMJson } from './types.ts'; import { SuggestionStore, type CommentThread } from './suggestions/store.ts'; import { commentRanges, listSuggestions, liveSuggestionIds, type SuggestionItem } from './suggestions/list.ts'; import { DIRECT_OPS, OpError, dropInsertedBlocks, opTransaction, remarkSuggestion, type Op } from './suggestions/ops.ts'; import { REF, countOps, outlineOps } from './suggestions/outline.ts'; import { OpArrivals } from './suggestions/arrival.ts'; import { blocksOf, emptySectionNode, findBlock, isOutlineNote, repairBody, sectionsAround, type BlockInfo, type SectionAt } from './doc.ts'; import { contextForAssistant, docForAssistant, type NamedNote } from './suggestions/protocol.ts'; import type { Assistant, AssistantEvent, AssistantReply } from './assistant/types.ts'; import { applyEvent, endActivity, newActivity, seconds, type Activity } from './activity.ts'; import { renderStyle, type StylePrefs } from './assistant/style.ts'; /** Where an ask is made: the piece (or, with chapters, the open chapter), the book as new chapters, a section, an outline note, or the selection. */ export type AskScope = { kind: 'piece' } | { kind: 'book' } | { kind: 'section'; id: string } | { kind: 'note'; id: string } | { kind: 'selection'; from: number; to: number }; export type AskVerb = 'write' | 'finer' | 'tighten' | 'review' | 'proofread' | 'outline' | 'structure' | 'anything'; export type AskStatus = 'queued' | 'working' | 'done' | 'stopped' | 'failed'; /** An ask: made about a place, with a verb and the writer's guidance; what came back, and the receipt of how. */ export type Ask = { id: string; at: string; scope: AskScope; verb: AskVerb; /** The writer's guidance, as blocks of rich text. */ guidance: PMJson[]; /** What was sent: the verb and the scope put into words, with the guidance. */ instruction: string; /** The notes pulled for it (the host's keys), for the record. */ pulled: string[]; status: AskStatus; /** What the assistant had to say, once it answered (or what went wrong). */ reply?: string; /** The suggestions it produced (their ids), and the ops that could not be applied. */ suggestions: string[]; failed?: { op: Op; reason: string }[]; /** The notes it named for the next step. */ named?: NamedNote[]; /** What it did on the way to its answer: the receipt. */ activity?: Activity; /** The asks sent together (one per section picked, say) share a batch, so a host can show what they named as one. */ batch?: string; }; export type AskRequest = { instruction: string; scope?: AskScope; verb?: AskVerb; guidance?: PMJson[]; pulled?: string[]; /** Material that goes with this ask alone, beside what the host gives every ask (the notes pulled for its scope, say). */ context?: ContextItem[]; /** The batch this ask is sent in, when several go together. */ batch?: string; /** A host may take some of the ops for itself first (one that turns proposed sections into chapters, say) and return the rest; the ops are then applied once the reply is whole. */ intercept?: (reply: AssistantReply) => Op[]; }; /** A batch of ops applied together, or in pieces as they arrive: the blocks made so far by the names their ops gave them, and the last block put after each anchor. With `own`, every block put in or taken out is a suggestion of its own (the parts of an outline, arriving one at a time). */ export type OpBatch = { chain: Map; made: Map; own?: boolean }; export const newBatch = (): OpBatch => ({ chain: new Map(), made: new Map() }); export type CommentView = CommentThread & { from?: number; to?: number; text_?: string }; export class Draft { readonly config: DraftConfig; readonly store: SuggestionStore; readonly newId: () => string; /** Whose edits these are. */ author: Author; /** The assistant in the sidebar; swappable at runtime. */ readonly assistant: Signal.State; readonly editor: Signal.State = signal(null); readonly suggesting: Signal.State; readonly suggestions: Signal.State = signal([]); readonly comments: Signal.State = signal([]); /** Every ask made on this document, oldest first: the ones out or queued, and the receipts of the ones answered. */ readonly asks: Signal.State = signal([]); /** An ask is out, or waiting its turn. */ readonly busy: Signal.State = signal(false); /** When the ask now being answered went out (ms since the epoch); 0 when none is. */ readonly askedAt: Signal.State = signal(0); /** What the assistant is doing about the ask now out: its steps, the words so far; null when none is. */ readonly activity: Signal.State = signal(null); #stopper: AbortController | null = null; /** Asks run one at a time, in the order made. */ #queue: Ask[] = []; #running: Ask | null = null; #waiters = new Map void>(); /** Bumped after every transaction, for things that read the document directly. */ readonly version: Signal.State = signal(0); /** The document title, for the assistant's context (hosts set it). */ title = ''; /** How the writing should read; null leaves it to the assistant. */ style: StylePrefs | null = null; #pinned: string | null = null; /** While an op is dispatched as a suggestion of its own: the block it makes or removes, re-marked with the pinned id so the library does not fold it into a neighbour. */ #own: { block: string; kind: 'insertion' | 'deletion' } | null = null; /** Ids this editor minted whose metadata is still to be written (once they are in the document). */ #minted = new Set(); /** Suggestion ids this editor has seen in its document: only those, once gone, lose their metadata here. */ #seenLive = new Set(); #unsubscribe: (() => void) | null = null; constructor(config: DraftConfig) { this.config = config; this.author = config.author; this.newId = config.generateId ?? newId; this.store = new SuggestionStore(config.collaboration?.doc); this.suggesting = signal(config.suggesting ?? false); this.assistant = signal(config.assistant ?? null); this.store.onChange(() => this.#refresh()); } // --- the editor ------------------------------------------------------------------- /** Called by once its TipTap editor exists. */ attach(editor: Editor): void { const orig = editor.view.props.dispatchTransaction; const own = () => ({ id: this.#pinned, block: this.#own }); const wrapped = withSuggestChanges( function (this: unknown, tr: Transaction) { // a block that is to be a suggestion of its own: the library gave it the // id of the suggestion it abuts, if any; it gets the pinned one back const o = own(); if (o.id && o.block) { const b = findBlock(tr.doc, o.block.block); if (b) remarkSuggestion(tr, b.pos, b.pos + b.node.nodeSize, o.id, o.block.kind); } orig?.call(this as never, tr); }, () => { if (this.#pinned) return this.#pinned; // the library asks for an id per transaction whether or not a step // uses it: mint one, attribute it once it shows up in the document const id = newId(); this.#minted.add(id); return id; }, ); editor.view.setProps({ dispatchTransaction: wrapped as (tr: Transaction) => void }); this.editor.set(editor); this.#unsubscribe?.(); const onTr = () => { this.version.set(this.version.get() + 1); this.#refresh(true); }; editor.on('transaction', onTr); this.#unsubscribe = () => editor.off('transaction', onTr); if (this.suggesting.get()) this.#setEnabled(true); this.#refresh(); } detach(): void { this.#unsubscribe?.(); this.#unsubscribe = null; this.editor.set(null); } get doc(): PMNode | null { return this.editor.get()?.state.doc ?? null; } getJSON(): PMJson | null { return (this.editor.get()?.getJSON() as PMJson | undefined) ?? null; } /** Replace the document (a fresh load). Not a suggestion, whatever the mode. */ setContent(json: PMJson): void { const e = this.editor.get(); if (!e) return; const was = this.suggesting.get(); if (was) this.#setEnabled(false); e.commands.setContent(repairBody(json, this.newId) as never, { emitUpdate: false }); if (was) this.#setEnabled(true); this.#refresh(); } /** Recompute the lists; after a transaction, also settle metadata: attribute what this editor minted, drop what is gone. */ #refresh(afterTransaction = false): void { const e = this.editor.get(); if (!e) return; const doc = e.state.doc; if (afterTransaction) { const live = liveSuggestionIds(doc); for (const id of this.#minted) { if (!live.has(id)) continue; this.#minted.delete(id); if (!this.store.suggestion(id)) this.store.setSuggestion({ id, author: this.author, at: new Date().toISOString() }); } // Metadata goes when a suggestion this editor saw is no longer there. // Pruning everything not live would race another editor on the same // shared document, whose changes arrive here a step behind their metadata. for (const id of this.#seenLive) if (!live.has(id)) this.store.forgetSuggestion(id); this.#seenLive = live; } const items = listSuggestions(doc, this.store); this.suggestions.set(items); const ranges = commentRanges(doc); this.comments.set( this.store.comments().map((t) => { const r = ranges.get(t.id); return r ? { ...t, from: r.from, to: r.to, text_: r.text } : t; }), ); } // --- suggesting ---------------------------------------------------------------------- #setEnabled(on: boolean): void { const e = this.editor.get(); if (!e) return; e.view.dispatch(e.state.tr.setMeta(suggestChangesKey, { enabled: on })); } setSuggesting(on: boolean): void { this.suggesting.set(on); this.#setEnabled(on); } toggleSuggesting(): void { this.setSuggesting(!this.suggesting.get()); } /** Run a plain change even while suggesting (accepting, rejecting, comments). */ #direct(fn: (tr: Transaction) => unknown): void { const e = this.editor.get(); if (!e) return; const tr = e.state.tr.setMeta(suggestChangesKey, { skip: true }); if (fn(tr) !== false) e.view.dispatch(tr); } accept(id: string): void { const e = this.editor.get(); if (!e) return; applySuggestion(id)(e.state, e.view.dispatch); this.store.forgetSuggestion(id); this.#refresh(); } reject(id: string): void { const e = this.editor.get(); if (!e) return; // whole blocks go first, by hand (the library trips on one at the end of the document); the rest is the library's this.#direct((tr) => dropInsertedBlocks(tr, new Set([id]))); if (liveSuggestionIds(e.state.doc).has(id)) revertSuggestion(id)(e.state, e.view.dispatch); this.store.forgetSuggestion(id); this.#refresh(); } acceptAll(): void { const e = this.editor.get(); if (!e) return; applySuggestions(e.state, e.view.dispatch); this.#refresh(); } rejectAll(): void { const e = this.editor.get(); if (!e) return; this.#direct((tr) => dropInsertedBlocks(tr)); if (liveSuggestionIds(e.state.doc).size) revertSuggestions(e.state, e.view.dispatch); this.#refresh(); } /** Take everything one ask proposed. */ takeAsk(askId: string): void { for (const id of this.pendingOf(askId)) this.accept(id); } /** Drop everything one ask proposed. */ dropAsk(askId: string): void { for (const id of this.pendingOf(askId)) this.reject(id); } /** The suggestions an ask made that are still in the document, in document order. */ pendingOf(askId: string): string[] { const mine = new Set(this.asks.get().find((a) => a.id === askId)?.suggestions ?? []); return this.suggestions .get() .filter((s) => mine.has(s.id)) .map((s) => s.id); } /** The ask that made a suggestion, if one did. */ askOf(suggestionId: string): Ask | undefined { return this.asks.get().find((a) => a.suggestions.includes(suggestionId)); } /** Scroll to and select a suggestion. */ show(id: string): void { const e = this.editor.get(); if (!e) return; selectSuggestion(id)(e.state, e.view.dispatch); e.commands.scrollIntoView(); e.view.focus(); } showRange(from: number, to: number): void { const e = this.editor.get(); if (!e) return; e.chain().setTextSelection({ from: Math.min(from, e.state.doc.content.size), to: Math.min(to, e.state.doc.content.size) }).scrollIntoView().run(); e.view.focus(); } // --- comments ------------------------------------------------------------------------ /** Comment on the selection (or, with no selection, on the block the caret is in). */ comment(text: string, range?: { from: number; to: number }, block?: string): CommentThread | null { const e = this.editor.get(); if (!e || !text.trim()) return null; let from: number; let to: number; if (range) ({ from, to } = range); else { const sel = e.state.selection; if (!sel.empty) ({ from, to } = sel); else { const $from = sel.$from; from = $from.start(); to = $from.end(); } } const quote = e.state.doc.textBetween(from, to, ' ').trim().slice(0, 120); const thread = this.store.newComment(this.author, text.trim(), { ...(block ? { block } : {}), ...(quote ? { quote } : {}) }); const type = e.schema.marks.comment; if (type && to > from) this.#direct((tr) => tr.addMark(from, to, type.create({ id: thread.id }))); this.#refresh(); return thread; } reply(id: string, text: string): void { if (text.trim()) this.store.reply(id, this.author, text.trim()); } resolveComment(id: string, resolved = true): void { this.store.resolve(id, resolved); const e = this.editor.get(); const type = e?.schema.marks.comment; if (e && type && resolved) { const r = commentRanges(e.state.doc).get(id); if (r) { this.#direct((tr) => { e.state.doc.nodesBetween(r.from, r.to, (node, pos) => { if (!node.isText) return true; for (const m of node.marks) if (m.type === type && String(m.attrs.id) === id) tr.removeMark(pos, pos + node.nodeSize, m); return true; }); }); } } this.#refresh(); } // --- structured ops ------------------------------------------------------------------- /** * Apply ops as suggestions by `author` (one suggestion per op); comments * become comment threads, and a target is set as it is (a knob, not a * change to the text). Several blocks inserted after the same block land * in the order given. An outline op is laid out part by part, each part * a suggestion of its own (a block inserted beside another suggestion * would otherwise join it); an insert-block may carry a "ref", and later * ops in the same batch may name "$ref" where they take a block id. * Returns what got in and what did not. A batch given keeps the names * and the chain across calls, so ops applied as they arrive still find * the blocks the earlier ones made. */ applyOps(ops: Op[], author: Author = this.author, extra: { reply?: string } = {}, batch: OpBatch = newBatch()): { applied: string[]; failed: { op: Op; reason: string }[] } { const e = this.editor.get(); const applied: string[] = []; const failed: { op: Op; reason: string }[] = []; if (!e) return { applied, failed: ops.map((op) => ({ op, reason: 'no editor' })) }; const was = this.suggesting.get(); if (!was) this.#setEnabled(true); // the last block inserted after each anchor (so the next one goes after it rather than before), and the blocks made, by the ref their op gave them const { chain, made } = batch; const resolve = (op: Op, field: 'in' | 'after' | 'before' | 'block'): string | undefined => { const v = (op as Record)[field]; if (typeof v !== 'string' || !v.startsWith(REF)) return undefined; const id = made.get(v); if (!id) throw new OpError(op, `${field}: no block was made as ${v}`); return id; }; const run = (given: Op, own: boolean): void => { let op = given; try { for (const f of ['in', 'after', 'before', 'block'] as const) { const id = resolve(op, f); if (id) op = { ...op, [f]: id } as Op; } if (op.op === 'insert-block' && op.after && chain.has(op.after)) op = { ...op, after: chain.get(op.after)! }; const tr = opTransaction(e.state, op, { newId: this.newId }); if (DIRECT_OPS.includes(op.op)) { tr.setMeta(suggestChangesKey, { skip: true }); e.view.dispatch(tr); return; } if (op.op === 'comment') { const meta = tr.getMeta('draft-comment') as { from: number; to: number; block: string; text: string }; const thread = this.comment(op.text, { from: meta.from, to: meta.to }, meta.block); if (thread) { this.store.setComment({ ...thread, author }); applied.push(thread.id); } return; } if (!tr.docChanged) { failed.push({ op, reason: 'nothing would change' }); return; } const id = this.store.fresh(author, { ...(op.note ? { note: op.note } : {}), kind: op.op, ...(extra.reply ? { reply: extra.reply } : {}) }); const inserted = tr.getMeta('draft-inserted') as { id: string } | undefined; this.#pinned = id; this.#own = own && op.op === 'insert-block' && inserted?.id ? { block: inserted.id, kind: 'insertion' } : own && op.op === 'delete-block' ? { block: op.block, kind: 'deletion' } : null; try { e.view.dispatch(tr); } finally { this.#pinned = null; this.#own = null; } applied.push(id); if (op.op === 'insert-block' && inserted?.id) { if (op.after) chain.set(op.after, inserted.id); if (op.ref) made.set(op.ref, inserted.id); } } catch (err) { failed.push({ op: given, reason: err instanceof OpError ? err.message : err instanceof Error ? err.message : String(err) }); } }; try { for (const given of ops) { if (given.op === 'outline') for (const part of outlineOps(given)) run(part, true); else run(given, !!batch.own); } } finally { if (!was) this.#setEnabled(false); } this.#refresh(); return { applied, failed }; } // --- the assistant ---------------------------------------------------------------------- /** The document as an assistant (or a person pasting into one) gets it. */ documentText(): string { const doc = this.doc; return doc ? docForAssistant(doc, this.title || undefined) : ''; } /** The style preferences as the assistant gets them; empty when there are none. */ styleText(): string { return renderStyle(this.style); } /** What goes beside the document for context (the host decides: other chapters, attached notes). */ contextItems(): ContextItem[] { return this.config.context?.() ?? []; } /** The context as the assistant gets it; empty when there is none. */ contextText(): string { return contextForAssistant(this.contextItems()); } /** * Ask the assistant about a place, with a verb and the writer's guidance * (or with a plain instruction), and apply what it proposes as * suggestions. Asks run one at a time, in the order made; the promise * resolves when this one is answered, stopped or fails. The ops are * applied as each closes in the streamed reply, so the words land where * they belong while the assistant is still writing; a host that takes some * of the ops for itself (`intercept`) gets the reply whole instead. */ ask(req: string | AskRequest): Promise { const r: AskRequest = typeof req === 'string' ? { instruction: req } : req; const text = r.instruction.trim(); if (!this.assistant.get() || !this.editor.get() || !text) return Promise.resolve(null); const ask: Ask = { id: newId(), at: new Date().toISOString(), scope: r.scope ?? { kind: 'piece' }, verb: r.verb ?? 'anything', guidance: r.guidance ?? [], instruction: text, pulled: r.pulled ?? [], status: 'queued', suggestions: [], ...(r.batch ? { batch: r.batch } : {}) }; this.asks.set([...this.asks.get(), ask]); this.#queue.push(ask); this.#intercepts.set(ask.id, r.intercept); if (r.context?.length) this.#contexts.set(ask.id, r.context); this.busy.set(true); const done = new Promise((resolve) => this.#waiters.set(ask.id, resolve)); void this.#pump(); return done; } #intercepts = new Map Op[]) | undefined>(); #contexts = new Map(); /** The ask with the fields given changed, in place in the list (a new object: signals compare by identity). */ #patch(id: string, patch: Partial): Ask | undefined { let out: Ask | undefined; this.asks.set( this.asks.get().map((a) => { if (a.id !== id) return a; out = { ...a, ...patch }; return out; }), ); return out; } #settle(ask: Ask): void { const w = this.#waiters.get(ask.id); this.#waiters.delete(ask.id); this.#intercepts.delete(ask.id); this.#contexts.delete(ask.id); w?.(ask); } async #pump(): Promise { if (this.#running) return; const next = this.#queue.shift(); if (!next) { this.busy.set(false); return; } this.#running = next; try { await this.#run(next); } finally { this.#running = null; void this.#pump(); } } async #run(queued: Ask): Promise { const a = this.assistant.get(); const e = this.editor.get(); const intercept = this.#intercepts.get(queued.id); if (!a || !e) { this.#settle(this.#patch(queued.id, { status: 'failed', reply: 'No assistant, or no editor.' }) ?? queued); return; } const started = Date.now(); this.askedAt.set(started); const stopper = new AbortController(); this.#stopper = stopper; this.#patch(queued.id, { status: 'working' }); const author: Author = { id: `assistant:${a.name}`, name: a.name, kind: 'assistant' }; const batch = newBatch(); const arrivals = new OpArrivals(); const applied: string[] = []; const failed: { op: Op; reason: string }[] = []; // the ops are applied as each closes in the streamed reply, unless a host wants the reply whole const land = (ops: Op[], own = false) => { const r = this.applyOps(ops, author, { reply: queued.id }, { ...batch, own }); applied.push(...r.applied); failed.push(...r.failed); if (r.applied.length) this.#patch(queued.id, { suggestions: [...applied] }); }; const arrive = (text: string) => { if (intercept) return; const got = arrivals.feed(text); for (const p of got.parts) land(outlineOps({ ...(p.head as object), op: 'outline', parts: [p.part] } as Extract, {}).filter((o) => o.op !== 'delete-block'), true); for (const o of got.ops) { if (o.op.op === 'outline') land(outlineOps(o.op, { from: arrivals.partsOf(o.index) }), true); else land([o.op]); } }; // the events come fast while the words stream: the signal is set a few times a second, not per word let act = newActivity(started); let flush: ReturnType | null = null; const publish = () => { flush = null; this.activity.set(act); this.#patch(queued.id, { activity: act }); arrive(act.text); }; const onEvent = (ev: AssistantEvent) => { act = applyEvent(act, ev); if (ev.kind === 'text' || ev.kind === 'thinking') { if (!flush) flush = setTimeout(publish, 80); } else { if (flush) clearTimeout(flush); publish(); } }; const end = (o: { error?: string; stopped?: boolean } = {}) => { if (flush) clearTimeout(flush); flush = null; act = endActivity(act, o); this.activity.set(act); return act; }; try { const sel = e.state.selection; const selection = queued.scope.kind === 'selection' ? e.state.doc.textBetween(queued.scope.from, queued.scope.to, ' ') : sel.empty ? undefined : e.state.doc.textBetween(sel.from, sel.to, ' '); const history = this.asks .get() .filter((x) => x.id !== queued.id && x.status === 'done' && x.reply) .flatMap((x) => [{ role: 'user' as const, text: x.instruction }, { role: 'assistant' as const, text: x.reply! }]); const style = this.styleText(); const context = [...this.contextItems(), ...(this.#contexts.get(queued.id) ?? [])]; const document = this.documentText(); const blocks = this.doc ? blocksOf(this.doc).length : 0; onEvent({ kind: 'status', text: `Sending the document: ${blocks} block${blocks === 1 ? '' : 's'}, ${document.length.toLocaleString()} characters${context.length ? `, with ${context.length} piece${context.length === 1 ? '' : 's'} of context` : ''}${style ? ', and the style' : ''}${selection ? ', and the selection' : ''}` }); const reply: AssistantReply = await a.suggest({ document, instruction: queued.instruction, ...(selection ? { selection } : {}), ...(style ? { style } : {}), ...(context.length ? { context } : {}), history, onEvent, signal: stopper.signal }); if (stopper.signal.aborted) throw new DOMException('stopped', 'AbortError'); if (flush) clearTimeout(flush); flush = null; // whatever had not closed when the words stopped, and what a host takes first arrive(act.text); const ops = intercept ? intercept(reply) : reply.ops.slice(arrivals.count); const n = countOps(reply.ops); onEvent({ kind: 'status', text: n ? `Reading the reply: ${n} suggestion${n === 1 ? '' : 's'} to place` : 'Reading the reply: no changes proposed' }); if (ops.length) land(ops); if (reply.ops.length) onEvent({ kind: 'status', text: `${applied.length} placed${failed.length ? `, ${failed.length} could not be` : ''}` }); const done = this.#patch(queued.id, { status: 'done', reply: reply.message, suggestions: applied, ...(failed.length ? { failed } : {}), ...(reply.named?.length ? { named: reply.named } : {}), activity: end() }); if (done) this.#settle(done); } catch (err) { const stopped = stopper.signal.aborted; const reply = stopped ? `Stopped after ${seconds(Date.now() - started)}.` : `Something went wrong: ${err instanceof Error ? err.message : String(err)}`; const done = this.#patch(queued.id, { status: stopped ? 'stopped' : 'failed', reply, suggestions: applied, ...(failed.length ? { failed } : {}), activity: end(stopped ? { stopped: true } : { error: err instanceof Error ? err.message : String(err) }) }); if (done) this.#settle(done); } finally { this.askedAt.set(0); this.activity.set(null); this.#stopper = null; } } /** Stop an ask: the one out (its answer, if it still comes, is dropped), or one still waiting its turn; with no id, the one out. */ stop(id?: string): void { if (id && this.#running?.id !== id) { const i = this.#queue.findIndex((a) => a.id === id); if (i < 0) return; const [a] = this.#queue.splice(i, 1); const done = this.#patch(a!.id, { status: 'stopped', reply: 'Stopped before it went out.' }); if (done) this.#settle(done); if (!this.#running && !this.#queue.length) this.busy.set(false); return; } this.#stopper?.abort(new DOMException('stopped', 'AbortError')); } /** The asks still to run, and the one out. */ get queued(): Ask[] { return this.#running ? [this.#running, ...this.#queue] : [...this.#queue]; } /** Forget the asks answered so far (the ones out stay). */ clearAsks(): void { this.asks.set(this.asks.get().filter((a) => a.status === 'queued' || a.status === 'working')); } /** Asks read back from a file: receipts, kept as they were. */ loadAsks(asks: Ask[]): void { this.asks.set(asks.map((a) => ({ ...a, status: a.status === 'queued' || a.status === 'working' ? 'stopped' : a.status }))); } // --- the outline: where the caret is, targets, and the notes at a level ------------------------- /** The innermost section the caret is in, if any. */ caretSection(): SectionAt | null { const e = this.editor.get(); if (!e) return null; return sectionsAround(e.state.doc, e.state.selection.from).at(-1) ?? null; } /** The block the caret is in (a paragraph, a list…), if any. */ caretBlock(): BlockInfo | null { const e = this.editor.get(); if (!e) return null; const { $from } = e.state.selection; for (let d = $from.depth; d >= 1; d--) { const node = $from.node(d); if (node.type.name === 'section' || node.type.name === 'sectionTitle') break; if (node.type.name === 'paragraph' || node.type.isBlock) { const id = String(node.attrs.id ?? ''); const found = id ? blocksOf(e.state.doc).find((b) => b.id === id) : undefined; if (found) return found; } } return null; } /** Drop the sections that are untitled and empty (the one a new document starts with) once there are others: a plain change. Returns how many went. */ dropEmptySections(): number { const e = this.editor.get(); if (!e) return 0; const tops = blocksOf(e.state.doc).filter((b) => b.type === 'section' && b.depth === 0); const empty = tops.filter((b) => !b.text.trim() && !b.node.textContent.trim() && b.node.childCount === 2 && b.node.child(1).type.name === 'paragraph'); if (!empty.length || empty.length === tops.length) return 0; this.#direct((tr) => { for (const b of [...empty].reverse()) tr.delete(b.pos, b.pos + b.node.nodeSize); }); this.#refresh(); return empty.length; } /** Give a section a new title: a plain change, as renaming from an outline is (not a suggestion). Returns false when it is already that. */ retitle(sectionId: string, title: string): boolean { const e = this.editor.get(); if (!e) return false; const b = findBlock(e.state.doc, sectionId); if (!b || b.type !== 'section' || b.text === title) return false; const t = b.node.child(0); const from = b.pos + 2; this.#direct((tr) => tr.replaceWith(from, from + t.content.size, title ? e.schema.text(title) : [])); this.#refresh(); return true; } /** Remove a section with everything in it: a plain change. */ removeSection(sectionId: string): boolean { const e = this.editor.get(); if (!e) return false; const b = findBlock(e.state.doc, sectionId); if (!b || b.type !== 'section') return false; this.#direct((tr) => tr.delete(b.pos, b.pos + b.node.nodeSize)); this.#refresh(); return true; } /** A new, empty top-level section at the end of the document, the caret in its title; its id. */ appendSection(title = ''): string | null { const e = this.editor.get(); if (!e) return null; const id = this.newId(); const node = e.schema.nodeFromJSON(emptySectionNode(id, this.newId(), title)); const at = e.state.doc.content.size; this.#direct((tr) => { tr.insert(at, node); tr.setSelection(TextSelection.create(tr.doc, at + 2)).scrollIntoView(); }); e.view.focus(); this.#refresh(); return id; } /** Move a section (or any block) next to another: a plain change, as dragging a row of the outline is. Returns false when it cannot go there. */ moveBlock(id: string, to: { after?: string; before?: string }): boolean { const e = this.editor.get(); if (!e) return false; try { const tr = opTransaction(e.state, { op: 'move-block', block: id, ...to }, { newId: this.newId }); tr.setMeta(suggestChangesKey, { skip: true }); e.view.dispatch(tr); this.#refresh(); return true; } catch { return false; } } /** Set (or, with 0, remove) a section's word target: a knob, never a suggestion. */ setTarget(sectionId: string, words: number): boolean { const e = this.editor.get(); if (!e) return false; try { const tr = opTransaction(e.state, { op: 'target', block: sectionId, words }, { newId: this.newId }); tr.setMeta(suggestChangesKey, { skip: true }); e.view.dispatch(tr); return true; } catch { return false; // already that } } /** * The outline notes at a level, as blocks of JSON: a section's own notes * (not its subsections'), or one note. A note is a paragraph (what will * be said) or a list (the points a paragraph will make). Empty when there * are none. */ outlineNotes(scopeId: string): { id: string; type: string; content: PMJson[] }[] { const e = this.editor.get(); if (!e) return []; const block = blocksOf(e.state.doc).find((b) => b.id === scopeId); if (!block) return []; const one = (n: PMNode) => ({ id: String(n.attrs.id ?? ''), type: n.type.name, content: (n.toJSON() as PMJson).content ?? [] }); if (block.type !== 'section') return isOutlineNote(block.node) ? [one(block.node)] : []; const out: { id: string; type: string; content: PMJson[] }[] = []; block.node.forEach((c) => { if (isOutlineNote(c)) out.push(one(c)); }); return out; } /** * Write the notes at a level back: each block given (a paragraph, or a * list of points) becomes an outline note at that level, in order, the * ones already there revised in place (their ids kept), the rest added * after them (after the title when there were none) and any left over * removed. A plain change, not a suggestion. Returns false when nothing * differed. */ setOutlineNotes(scopeId: string, blocks: PMJson[]): boolean { const e = this.editor.get(); if (!e) return false; const doc = e.state.doc; const block = blocksOf(doc).find((b) => b.id === scopeId); if (!block || (block.type !== 'section' && !isOutlineNote(block.node))) return false; const NOTE_TYPES = new Set(['paragraph', 'bulletList', 'orderedList']); const fresh = blocks.filter((b) => NOTE_TYPES.has(b.type) && hasText(b)); const old: { pos: number; node: PMNode }[] = []; let after: number; // where a new note goes when there is none to revise if (block.type !== 'section') { old.push({ pos: block.pos, node: block.node }); after = block.pos + block.node.nodeSize; } else { after = block.pos + 1 + block.node.child(0).nodeSize; block.node.forEach((c, off) => { if (isOutlineNote(c)) old.push({ pos: block.pos + 1 + off, node: c }); }); } // a block from a plain editor, made a note of this document: ids where its nodes take them const build = (b: PMJson): PMNode => e.schema.nodeFromJSON(this.#withIds({ ...b, attrs: { ...(b.attrs ?? {}), outline: true } })); const same = (a: PMJson[], b: PMJson[]) => JSON.stringify(a.map(stripIds)) === JSON.stringify(b.map(stripIds)); let changed = false; this.#direct((tr) => { const n = Math.min(old.length, fresh.length); // revise in place, from the end so the earlier positions hold for (let i = old.length - 1; i >= 0; i--) { const o = old[i]!; if (i >= n) { // more notes than blocks given (a note cleared goes too) tr.delete(o.pos, o.pos + o.node.nodeSize); changed = true; continue; } const f = fresh[i]!; if (o.node.type.name !== f.type) { tr.replaceWith(o.pos, o.pos + o.node.nodeSize, build(f)); changed = true; continue; } if (same((o.node.toJSON() as PMJson).content ?? [], f.content ?? [])) continue; tr.replaceWith(o.pos + 1, o.pos + 1 + o.node.content.size, build(f).content); changed = true; } if (fresh.length > old.length) { const last = old[old.length - 1]; let at = last ? tr.mapping.map(last.pos + last.node.nodeSize) : tr.mapping.map(after); for (const b of fresh.slice(old.length)) { const node = build(b); tr.insert(at, node); at += node.nodeSize; changed = true; } } return changed; }); if (changed) this.#refresh(); return changed; } /** Block JSON with an id on every node whose type carries one and has none yet. */ #withIds(json: PMJson): PMJson { const e = this.editor.get(); const type = e?.schema.nodes[json.type]; const takesId = !!type?.spec.attrs?.id; const attrs = takesId && !json.attrs?.id ? { ...(json.attrs ?? {}), id: this.newId() } : json.attrs; return { ...json, ...(attrs ? { attrs } : {}), ...(json.content ? { content: json.content.map((c) => this.#withIds(c)) } : {}) }; } /** Put the caret somewhere sensible. */ focus(where: 'start' | 'end' = 'start'): void { this.editor.get()?.chain().focus(where).run(); } /** Move the selection to a document position (bounded). */ select(pos: number): void { const e = this.editor.get(); if (!e) return; const p = Math.max(0, Math.min(pos, e.state.doc.content.size)); e.view.dispatch(e.state.tr.setSelection(TextSelection.near(e.state.doc.resolve(p))).scrollIntoView()); } } /** Whether a block of JSON holds any text (or inline maths) to keep. */ function hasText(json: PMJson): boolean { if (json.type === 'text') return !!(json.text ?? '').trim(); if (json.type === 'inlineMath') return true; return (json.content ?? []).some(hasText); } /** Block JSON without ids, for comparing what an editor without them gives back against what is there. */ function stripIds(json: PMJson): PMJson { const { attrs: given, content, ...rest } = json; const { id: _id, ...attrs } = given ?? {}; return { ...rest, ...(Object.keys(attrs).length ? { attrs } : {}), ...(content ? { content: content.map(stripIds) } : {}) }; }