Files
RuneStone/src/lib/editor/liveMarkdown.ts
T
Knotty Wyvern 5e1533c371 Make Table Formulas a built-in feature
The formula engine, the rendered results, and the formula help now
come from src/lib/formulas/. The editor and the renderer call this
module directly. The tableFormulas contribution type is removed.

- Add the tableFormulas general setting (default on) and a switch in
  Settings > General. When it is off, formulas show as source text.
- Do not load an installed runestone.table-formulas package. Settings
  > Plug-ins marks it as included with RuneStone and tells the user
  that it can be removed. The user's files stay in place.
- Translate the formula help and the error descriptions into French,
  Japanese, and Simplified Chinese.
- Port the plugin unit tests. Test the setting and use a test-only
  contribution for the generic plugin lifecycle tests.
- Smoke tests load only Terminal. The formula and lifecycle tests use
  the built-in feature and its setting.
- Remove scripts/buildPlugins.mjs, the build:plugins script, and the
  plugin-packages requirement of the smoke runner.
- Remove RuneStone_Table_Formulas from the menu audit scope. It had no
  menu surfaces.
- Update the README, the user guides, and the developer references.
2026-10-28 01:05:43 -07:00

384 lines
22 KiB
TypeScript

import { tr } from '../i18n/index.ts';
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
import { tableControls, tableEditors } from "./tableControls";
import { parseMarkdownTable } from "./markdownTable";
import type { TableContextActions } from "./tableCellActions";
import { imageControls } from "./imageControls";
import { ImagePreview, type ImageContext } from "./imagePreview";
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { activeTableFormulas } from "../formulas/index.ts";
const previewFormulas = new WeakMap<HTMLElement, unknown>();
export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>();
const linkTooltips = ViewPlugin.define(view => {
const attached = new Map<HTMLElement, () => void>();
const refresh = () => {
for (const [node, dispose] of attached) if (!view.dom.contains(node)) { dispose(); attached.delete(node); }
for (const node of view.dom.querySelectorAll<HTMLElement>("[data-editor-tooltip]")) {
if (!attached.has(node)) attached.set(node, attachTooltip(node, () => node.dataset.editorTooltip || ""));
}
};
const observer = new MutationObserver(refresh);
observer.observe(view.dom, { childList: true, subtree: true });
refresh();
return { destroy() { observer.disconnect(); attached.forEach(dispose => dispose()); } };
});
class CodeCopy extends WidgetType {
constructor(readonly code: string) { super(); }
eq(other: CodeCopy) { return this.code === other.code; }
toDOM() {
const button = document.createElement("button");
button.type = "button";
button.className = "rs-fence-copy writer-code-copy";
button.setAttribute("aria-label", tr("Copy code"));
button.dataset.editorTooltip = tr("Copy code");
button.append(actionIcon("copy"));
button.onmousedown = event => event.preventDefault();
button.onclick = async event => {
event.preventDefault(); event.stopPropagation();
try {
await navigator.clipboard.writeText(this.code);
button.dataset.copied = "true";
button.dataset.editorTooltip = tr("Copied");
button.setAttribute("aria-label", tr("Code copied"));
} catch {
button.dataset.editorTooltip = tr("Could not copy code");
button.setAttribute("aria-label", tr("Could not copy code"));
}
};
return button;
}
ignoreEvent() { return true; }
}
class Divider extends WidgetType {
eq(other: Divider) { return other instanceof Divider; }
toDOM(view: EditorView) {
const dom = document.createElement("span");
dom.className = "writer-divider";
dom.setAttribute("role", "separator");
dom.addEventListener("mousedown", event => {
if (event.button !== 0 || event.shiftKey) return;
event.preventDefault();
view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true });
view.focus();
});
return dom;
}
ignoreEvent() { return false; }
}
class Checkbox extends WidgetType {
constructor(readonly checked: boolean) { super(); }
eq(other: Checkbox) { return this.checked === other.checked; }
toDOM(view: EditorView) {
const box = document.createElement("input");
box.type = "checkbox";
box.checked = this.checked;
box.className = "writer-checkbox";
box.setAttribute("aria-label", this.checked ? tr("Mark task incomplete") : tr("Mark task complete"));
box.addEventListener("mousedown", event => event.preventDefault());
box.addEventListener("click", event => {
event.stopPropagation();
const line = view.state.doc.lineAt(view.posAtDOM(box));
const match = /^(\s*[-+*]\s+\[)([ xX])(\])/.exec(line.text);
if (!match) return;
const from = line.from + match[1].length;
view.dispatch({ changes: { from, to: from + 1, insert: this.checked ? " " : "x" }, userEvent: "input" });
});
return box;
}
ignoreEvent() { return true; }
}
class Preview extends WidgetType {
readonly formulas = activeTableFormulas();
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
get estimatedHeight() { return this.height.value; }
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
measure(dom: HTMLElement, view: EditorView) {
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
}
updateDOM(dom: HTMLElement, view: EditorView) {
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
this.measure(dom, view);
return true;
}
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
toDOM(view: EditorView) {
const dom = document.createElement("div");
previewFormulas.set(dom, this.formulas);
dom.className = "reading writer-preview";
dom.innerHTML = this.html;
// Widgets handle their own events, so CodeMirror's link handler cannot run.
dom.addEventListener("mousedown", event => {
if (event.button !== 0 || (!event.ctrlKey && !event.metaKey)) return;
const link = event.target instanceof Element ? event.target.closest<HTMLElement>("[data-href], a[href]") : null;
if (!link) return;
event.preventDefault();
event.stopPropagation();
void this.actions.linkActions?.().open?.({ kind: link.dataset.kind === "wiki" ? "wiki" : "md", target: link.dataset.href ?? link.getAttribute("href") ?? "" });
}, { capture: true });
// Cancel native anchor navigation even when an ordinary click reveals source.
dom.addEventListener("click", event => {
if (event.target instanceof Element && event.target.closest("a[href], [data-href]")) event.preventDefault();
}, { capture: true });
tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
this.measure(dom, view);
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
dom.addEventListener("mousedown", event => {
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
if (event.target instanceof Element && event.target.closest("summary, .md-image-frame")) return;
if (event.ctrlKey || event.metaKey) return;
event.preventDefault();
view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true });
view.focus();
});
requestAnimationFrame(() => {
if (dom.isConnected) {
void renderDiagrams(dom, () => !dom.isConnected).then(() => view.requestMeasure());
view.requestMeasure();
}
});
return dom;
}
ignoreEvent() { return true; }
}
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
const selecting = StateEffect.define<boolean>();
const mouseSelecting = StateField.define({
create: () => false,
update(value, transaction) {
if (transaction.docChanged) return false;
for (const effect of transaction.effects) if (effect.is(selecting)) value = effect.value;
return value;
},
});
const focusBody = StateEffect.define<boolean>();
const bodyFocused = StateField.define({
create: () => false,
update(value, transaction) {
for (const effect of transaction.effects) if (effect.is(focusBody)) value = effect.value;
return value;
},
});
const syncBodyFocus = ViewPlugin.define(view => {
// A restored editor can already own focus before its focus observer starts.
const sync = () => queueMicrotask(() => {
if (view.dom.isConnected && view.state.field(bodyFocused, false) !== undefined && view.state.field(bodyFocused) !== view.hasFocus) {
view.dispatch({ effects: focusBody.of(view.hasFocus) });
}
});
sync();
return { update: sync };
});
function build(state: EditorState, previous?: DecorationSet): DecorationSet {
const ranges: Range<Decoration>[] = [];
const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to }));
const selected = (from: number, to: number) => active.some(range => range.from <= to && range.to >= from);
const hiddenBlocks: { from: number; to: number }[] = [];
foldedRanges(state).between(0, state.doc.length, (from, to) => { hiddenBlocks.push({ from, to }); });
const source = state.doc.toString();
const editing = state.field(imageSource);
const imageNodes = imageSourceRanges(source);
for (const section of renderMarkdownSections(source, urls)) {
if (hiddenBlocks.some(block => block.from <= section.start && block.to >= section.end - 1)) continue;
if (!/(?:<pre|<table|<img|md-properties|md-callout|missing-image)/.test(section.html)) continue;
// Code remains a real editor surface. A preview swap loses the first drag
// and changes block height when focus or the selection moves elsewhere.
if (/^<pre\b/.test(section.html)) continue;
// The first rendered section includes leading blank lines. Keep those
// editable when the user exits above a table at the start of a note.
if (/<table>/.test(section.html)) section.start += /^(?:[ \t]*\r?\n)+/.exec(source.slice(section.start, section.end))?.[0].length ?? 0;
const end = section.end - (source.slice(section.start, section.end).match(/\n+$/)?.[0].length || 0);
const isTable = /<table>/.test(section.html) && parseMarkdownTable(source.slice(section.start, end));
if (end <= section.start) continue;
const imageHtml = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g) || [];
const nodes = imageNodes.filter(node => node.from >= section.start && node.to <= end);
if (!isTable && imageHtml.length && imageHtml.length === nodes.length && (!/md-callout/.test(section.html) || selected(section.start, end))) {
nodes.forEach((node, index) => {
const revealed = editing?.from === node.from;
const block = state.doc.lineAt(node.from).from === node.from && state.doc.lineAt(node.to).to === node.to;
const widget = new ImagePreview(imageHtml[index], source.slice(node.from, node.to), images, revealed, revealed || block);
if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to));
else {
hiddenBlocks.push(node);
ranges.push(Decoration.replace({ widget, block, atomic: true }).range(node.from, node.to));
}
});
continue;
}
if (!isTable && selected(section.start, end)) {
// Keep images below the editable source, without duplicating surrounding prose.
const images = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g)?.join("");
if (images) ranges.push(Decoration.widget({ widget: new Preview(images, source.slice(section.start, end), actions, true), block: true, side: 1 }).range(end));
continue;
}
hiddenBlocks.push({ from: section.start, to: end });
// Keep the table height between edits and the next layout pass. A one-line
// estimate can move the scroll anchor below a tall table on a second update.
let height: { value: number } | undefined;
if (isTable) previous?.between(section.start, end, (from, to, decoration) => {
if (from === section.start && to === end && decoration.spec.widget instanceof Preview) height = decoration.spec.widget.height;
});
ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions, false, height), block: true, atomic: true }).range(section.start, end));
}
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
for (let number = 1; number <= state.doc.lines; number++) {
const line = state.doc.line(number);
if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
}
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
const codeRanges: { from: number; to: number }[] = [];
syntaxTree(state).iterate({ enter(node) {
if (hidden(node.from, node.to)) return false;
if (node.name === "FencedCode" || node.name === "CodeBlock") {
codeRanges.push({ from: node.from, to: node.to });
const first = state.doc.lineAt(node.from), last = state.doc.lineAt(node.to);
const fenced = node.name === "FencedCode";
const closed = fenced && /^\s*(`{3,}|~{3,})\s*$/.test(last.text) && last.number > first.number;
const code = fenced ? source.slice(Math.min(first.to + 1, node.to), closed ? last.from : node.to) : source.slice(node.from, node.to);
const editingCode = selected(node.from, node.to);
if (!editingCode) ranges.push(Decoration.widget({ widget: new CodeCopy(code), side: 1 }).range(first.to));
for (let number = first.number; number <= last.number; number++) {
const line = state.doc.line(number);
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
}
return false;
}
const line = state.doc.lineAt(node.from);
// A list starts with one hyphen. Do not enlarge the preceding paragraph
// while the user enters that marker. Keep the Markdown source unchanged.
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
}
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
if (node.name === "TaskMarker") {
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
if (!match) return;
const markerFrom = line.from + match[1].length;
// ArrowLeft and Home reach the replacement's start, before the list bullet.
// Keep the trailing space outside the edit range so task text stays rendered.
const editingMarker = state.field(bodyFocused) && state.selection.ranges.some(range => range.from <= node.to && range.to >= markerFrom);
if (editingMarker) return;
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).range(markerFrom, line.from + match[0].length));
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
return;
}
if (selected(node.from, node.to)) return;
if (node.name === "HorizontalRule") {
ranges.push(Decoration.line({ class: "writer-divider-line" }).range(line.from));
ranges.push(Decoration.replace({ widget: new Divider(), atomic: true }).range(node.from, node.to));
return false;
}
if (node.name === "HeaderMark" && !(source.slice(node.from, node.to) === "-" && node.node.parent?.name === "SetextHeading2")) replace(node.from, Math.min(line.to, node.to + 1));
if (node.name === "StrongEmphasis") mark(node.from, node.to, "writer-strong");
if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis");
if (node.name === "Strikethrough") mark(node.from, node.to, "writer-strike");
if (node.name === "InlineCode") mark(node.from, node.to, "writer-inline-code");
if (node.name === "NoteHighlight") mark(node.from, node.to, "writer-highlight");
if (node.name === "NoteMath") mark(node.from, node.to, "writer-math");
if (node.name === "NoteComment") mark(node.from, node.to, "writer-comment");
if (["EmphasisMark", "StrikethroughMark", "CodeMark", "NoteFormatMark"].includes(node.name)) replace(node.from, node.to);
if (node.name === "Link") {
// Wiki links are handled separately, because CommonMark sees their inner
// brackets as an incomplete reference link.
if (source[node.from - 1] === "[" && source[node.to] === "]") return false;
const text = source.slice(node.from, node.to);
const match = /^\[([^\]]+)\]\(([^\s)]+)(?:\s+"[^"]*")?\)$/.exec(text);
if (!match) return;
replace(node.from, node.from + 1);
replace(node.from + 1 + match[1].length, node.to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
return false;
}
} });
for (const match of source.matchAll(/\[\^([^\]\s]+)\](:)?/g)) {
const from = match.index, to = from + match[0].length;
if (hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
if (source[from - 1] === "\\") continue;
mark(from, to, match[2] && state.doc.lineAt(from).from === from ? "writer-footnote-definition" : "writer-footnote-ref");
}
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
const from = match.index, to = from + match[0].length;
if (selected(from, to) || hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
const separator = match[1].indexOf("|");
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
replace(from, labelStart);
replace(to - 2, to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0], "data-editor-tooltip": "Ctrl+click to open link" } }).range(labelStart, to - 2));
}
for (const link of documentLinks(source)) {
if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue;
mark(link.from, link.to, "writer-link-source");
mark(link.targetFrom, link.targetTo, "writer-link-target");
}
return Decoration.set(ranges, true);
}
const decorations = StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
// Preserve the rendered geometry until the pointer gesture ends.
if (transaction.state.field(mouseSelecting) && !transaction.docChanged) return value;
return transaction.docChanged || transaction.selection
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|| transaction.effects.some(effect => effect.is(selecting) || effect.is(focusBody) || effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
? build(transaction.state, value.map(transaction.changes)) : value;
},
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({
filter: (_from, _to, decoration) => decoration.spec.atomic === true,
}))],
});
const mousePreview = ViewPlugin.define(view => {
const finish = () => {
if (!view.state.field(mouseSelecting)) return;
const selection = view.state.selection;
const ranges = selection.ranges.map(range => {
if (range.empty) return range;
let from = range.from, to = range.to;
// Include hidden syntax at the selected label's exposed boundaries.
view.state.field(decorations).between(0, view.state.doc.length, (start, end, decoration) => {
if (decoration.spec.atomic !== true || decoration.spec.widget) return;
if (range.from >= start && range.from <= end) from = Math.min(from, start);
if (range.to >= start && range.to <= end) to = Math.max(to, end);
});
return EditorSelection.range(range.anchor <= range.head ? from : to, range.anchor <= range.head ? to : from);
});
view.dispatch({ selection: EditorSelection.create(ranges, selection.mainIndex), effects: selecting.of(false) });
};
const release = () => queueMicrotask(finish);
const start = (event: MouseEvent) => {
if (event.button || event.ctrlKey || event.metaKey || !(event.target instanceof Element)
|| event.target.closest(".writer-preview, button, input")) return;
view.dispatch({ effects: selecting.of(true) });
};
view.contentDOM.addEventListener("mousedown", start);
document.addEventListener("mouseup", release);
document.addEventListener("dragend", release);
window.addEventListener("blur", finish);
return { destroy() {
view.contentDOM.removeEventListener("mousedown", start);
document.removeEventListener("mouseup", release);
document.removeEventListener("dragend", release);
window.removeEventListener("blur", finish);
} };
});
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, mousePreview, syncBodyFocus,
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
}