Initial RuneStone project

This commit is contained in:
Knotty Wyvern
2026-09-26 01:25:42 -07:00
commit bdc15e952d
190 changed files with 25986 additions and 0 deletions
+386
View File
@@ -0,0 +1,386 @@
import { Editor, Mark } from "@tiptap/core";
import Highlight from "@tiptap/extension-highlight";
import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
import Image from "@tiptap/extension-image";
import type { EditorView } from "@codemirror/view";
import { isolateHistory, undo, redo } from "@codemirror/commands";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
import { tableCellMarkdown } from "./tableCellMarkdown";
import { tableSelectionControls } from "./tableSelectionControls";
import { tableDragControls } from "./tableDragControls";
import type { TableContextActions } from "./tableCellActions";
import { actionIcon } from "../ui/actionIcons";
import { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula } from "./tableFormulas";
import { tableFormulaHtml } from "../workspace/noteHtml";
const cellFormats = ["math", "comment"].map(name => Mark.create({
name,
parseHTML: () => [{ tag: `span[data-cell-format="${name}"]` }],
renderHTML: () => ["span", { "data-cell-format": name, class: `md-inline-${name}` }, 0],
}));
const CellLink = Link.extend({
addAttributes() { return { ...this.parent?.(), "data-kind": { default: "md" } }; },
});
const CellImage = Image.extend({
addAttributes() { return { ...this.parent?.(), "data-md-src": { default: null }, "data-md-kind": { default: "md" } }; },
parseHTML() { return [...(this.parent?.() || []), { tag: "span.missing-image[data-md-src]" }]; },
renderHTML({ HTMLAttributes }) {
return HTMLAttributes.src
? ["img", HTMLAttributes]
: ["span", { ...HTMLAttributes, class: "missing-image" }, `Image unavailable: ${HTMLAttributes.alt || HTMLAttributes["data-md-src"] || ""}`];
},
});
export const tableEditors = new WeakMap<HTMLElement, { source: string; enter: (forward: boolean, x?: number) => void; destroy: () => void }>();
export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) {
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
const table = scroll?.querySelector("table");
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
const wrapper = document.createElement("div");
wrapper.className = "writer-table";
scroll.before(wrapper);
wrapper.append(scroll);
let editor: Editor | undefined;
let active: HTMLTableCellElement | undefined;
let firstEdit = true;
let selectionControls: ReturnType<typeof tableSelectionControls> | undefined;
let dragControls: ReturnType<typeof tableDragControls> | undefined;
const controller = { source: initialSource, enter, destroy: () => { dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } };
tableEditors.set(root, controller);
function enter(forward: boolean, x?: number) {
const row = table!.rows[forward ? 0 : table!.rows.length - 1];
const cells = [...row.cells];
let cell = cells[forward ? 0 : cells.length - 1];
if (x !== undefined) {
const distance = (candidate: HTMLTableCellElement) => {
const rect = candidate.getBoundingClientRect();
return Math.max(rect.left - x, x - rect.right, 0);
};
cell = cells.reduce((nearest, candidate) => distance(candidate) < distance(nearest) ? candidate : nearest);
}
activate(cell);
const current = editor!;
let position = forward ? 1 : current.state.doc.content.size - 1;
if (x !== undefined) {
const edge = current.view.coordsAtPos(position);
position = current.view.posAtCoords({ left: x, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
}
current.commands.setTextSelection(position);
current.view.focus();
cell.scrollIntoView({ block: "nearest", inline: "nearest" });
}
function refreshFormulas() {
const parsed = parseMarkdownTable(controller.source);
if (!parsed) return;
const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || ""));
const results = evaluateTableFormulas(grid);
for (const row of table!.rows) for (const cell of row.cells) {
const result = results[row.rowIndex]?.[cell.cellIndex];
const address = cellAddress(row.rowIndex, cell.cellIndex);
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
if (result && cell !== active) cell.innerHTML = tableFormulaHtml(result);
if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
formulaHint.textContent = result?.error ? formulaErrors[result.error] : "";
formulaHint.hidden = !formulaHint.textContent;
}
}
}
function change(insert: string, structural = false) {
const source = controller.source;
const from = view.posAtDOM(root);
if (view.state.doc.sliceString(from, from + source.length) !== source || insert === source) return;
// Keep the same DOM/editor on typing, including composition and text selection.
if (!structural) controller.source = insert;
let start = 0, oldEnd = source.length, newEnd = insert.length;
while (start < oldEnd && start < newEnd && source[start] === insert[start]) start++;
while (oldEnd > start && newEnd > start && source[oldEnd - 1] === insert[newEnd - 1]) { oldEnd--; newEnd--; }
view.dispatch({
changes: { from: from + start, to: from + oldEnd, insert: insert.slice(start, newEnd) },
userEvent: structural ? "input" : editor?.view.composing ? "input.type.compose" : "input.type.table",
annotations: structural ? isolateHistory.of("full") : firstEdit ? isolateHistory.of("before") : [],
});
firstEdit = false;
if (!structural) refreshFormulas();
view.requestMeasure();
}
function finish() {
if (!editor || !active) return;
const cell = active;
const html = editor.getHTML();
editor.destroy(); editor = undefined; active = undefined;
cell.innerHTML = html;
cell.classList.remove("is-editing");
refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate";
formulaHint.hidden = true;
view.requestMeasure();
if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") });
}
function leave(after: boolean) {
const from = view.posAtDOM(root), to = from + controller.source.length;
finish();
let anchor = after ? Math.min(view.state.doc.length, to + 1) : Math.max(0, from - 1);
if (after && to + 1 >= view.state.doc.length) {
view.dispatch({ changes: { from: view.state.doc.length, insert: to === view.state.doc.length ? "\n\n" : "\n" }, userEvent: "input" });
anchor = to + 2;
} else if (after && view.state.doc.sliceString(to, to + 2) === "\n\n") {
// Leave the separator blank so typing below cannot become another row.
anchor = to + 2;
} else if (!after && from === 0) {
view.dispatch({ changes: { from: 0, insert: "\n\n" }, userEvent: "input" });
anchor = 0;
}
view.dispatch({ selection: { anchor }, scrollIntoView: true });
view.focus();
}
function activate(cell: HTMLTableCellElement) {
if (active === cell) return;
finish();
active = cell;
firstEdit = true;
const row = (cell.parentElement as HTMLTableRowElement).rowIndex;
const column = cell.cellIndex;
const sourceRow = row === 0 ? 0 : row + 1;
const originalCell = parseMarkdownTable(controller.source)?.rows[sourceRow]?.cells[column];
// The nested editor owns browser focus, but the outer editor also needs to
// leave its previous active line so its Markdown markers render again.
view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" });
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
const formula = originalCell && (isTableFormula(originalCell.text) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
const html = cell.innerHTML;
formulaStatus.textContent = `${cellAddress(row, column)} · Type = to calculate`;
cell.innerHTML = "";
cell.classList.add("is-editing");
editor = new Editor({
element: cell,
extensions: [
StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }),
CellLink.configure({ openOnClick: false, autolink: false }),
CellImage.configure({ inline: true, allowBase64: true }),
Highlight, ...cellFormats,
],
content: formula ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: formula }] }] } : html,
enableInputRules: false,
enablePasteRules: false,
editorProps: {
attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" },
handleKeyDown(_editorView, event) {
if (event.isComposing) return false;
if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
// The nested editor owns cursor movement, including word movement
// and selections. Never let an arrow reach the prose editor.
event.stopPropagation();
// Native cursor movement can precede ProseMirror's selectionchange
// observer (especially during key repeat). Test the visible caret.
const native = document.getSelection();
if (native?.anchorNode && native.focusNode && _editorView.dom.contains(native.anchorNode) && _editorView.dom.contains(native.focusNode)) {
const anchor = _editorView.posAtDOM(native.anchorNode, native.anchorOffset);
const head = _editorView.posAtDOM(native.focusNode, native.focusOffset);
if (anchor !== _editorView.state.selection.anchor || head !== _editorView.state.selection.head) editor!.commands.setTextSelection({ from: anchor, to: head });
}
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || !_editorView.state.selection.empty) return false;
const direction = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down";
const horizontal = direction === "left" || direction === "right";
const backwards = direction === "left" || direction === "up";
const { $head } = _editorView.state.selection;
// Pasted rich text can have several paragraphs within one cell.
if ($head.depth && (backwards ? $head.before(1) > 0 : $head.after(1) < _editorView.state.doc.content.size)) return false;
if (!_editorView.endOfTextblock(direction)) return false;
event.preventDefault();
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
const next = horizontal
? cells[cells.indexOf(cell) + (backwards ? -1 : 1)]
: table!.rows[row + (backwards ? -1 : 1)]?.cells[column];
// Once there are no more cells in this direction, return to prose.
if (!next) { leave(!backwards); return true; }
const caret = _editorView.coordsAtPos(_editorView.state.selection.head);
activate(next);
const current = editor!;
let position = backwards ? current.state.doc.content.size - 1 : 1;
if (!horizontal) {
// Enter the closest position on the first/last visual line, even
// when either cell wraps or contains a hard break.
const edge = current.view.coordsAtPos(position);
position = current.view.posAtCoords({ left: caret.left, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
}
current.commands.setTextSelection(position);
current.view.focus();
next.scrollIntoView({ block: "nearest", inline: "nearest" });
return true;
}
// Keep formatting shortcuts local; the workbench also binds Ctrl+B.
if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation();
if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) {
event.preventDefault(); event.stopPropagation();
const position = event.key === "Home" ? 1 : editor!.state.doc.content.size - 1;
editor?.commands.setTextSelection(event.shiftKey ? { from: editor.state.selection.anchor, to: position } : position);
return true;
}
if ((event.ctrlKey || event.metaKey) && ["z", "y"].includes(event.key.toLowerCase())) {
event.preventDefault(); event.stopPropagation();
const from = view.posAtDOM(root);
(event.key.toLowerCase() === "y" || event.shiftKey ? redo : undo)(view);
requestAnimationFrame(() => {
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
(updated?.querySelector("table")?.rows[row]?.cells[column])?.focus();
});
return true;
}
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
if (event.key === "Enter") {
event.preventDefault();
if (isTableFormula(editor?.getText() || "")) { finish(); wrapper.focus(); }
else if (event.ctrlKey || event.metaKey) leave(true);
else editor?.commands.setHardBreak();
return true;
}
if (event.key === "Tab") {
event.preventDefault();
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
const next = cells[cells.indexOf(cell) + (event.shiftKey ? -1 : 1)];
if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); }
else if (event.shiftKey) leave(false);
else add("row", true);
return true;
}
return false;
},
},
onUpdate({ editor: current }) {
const text = tableCellMarkdown(current.getJSON());
const source = controller.source;
// Track the full edited range, including typed spaces. Re-parsing the
// trimmed cell on each key would gradually turn those spaces into padding.
const insert = contentFrom === undefined || contentTo === undefined
? replaceTableCell(source, sourceRow, column, text)
: source.slice(0, contentFrom) + text + source.slice(contentTo);
contentFrom ??= parseMarkdownTable(insert)?.rows[sourceRow]?.cells[column]?.from;
if (contentFrom !== undefined) contentTo = contentFrom + text.length;
change(insert);
},
onBlur() {
// A toolbar click, another cell, or the prose editor can now take focus.
queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); });
},
});
editor.commands.setTextSelection(editor.state.doc.content.size - 1); editor.view.focus();
refreshFormulas();
view.requestMeasure();
}
function add(kind: "row" | "column", focusNew = false) {
const from = view.posAtDOM(root);
finish();
const current = controller.source;
change(kind === "column" ? appendTableColumn(current) : appendTableRow(current), true);
view.focus();
requestAnimationFrame(() => {
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
if (!updated) return;
if (focusNew) updated.querySelector<HTMLTableCellElement>("tbody tr:last-child td")?.focus();
if (kind === "column") {
const viewport = updated.querySelector<HTMLElement>(".md-table-scroll")!;
viewport.scrollLeft = viewport.scrollWidth;
} else updated.querySelector(".table-add-row")?.scrollIntoView({ block: "nearest", inline: "nearest" });
view.requestMeasure();
});
}
const help = document.createElement("div");
help.className = "table-edit-help";
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
const footer = document.createElement("div");
footer.className = "table-footer";
const formulaTools = document.createElement("div");
formulaTools.className = "table-formula-tools";
const formulaHelp = document.createElement("details");
formulaHelp.className = "table-formula-help";
const summary = document.createElement("summary");
summary.append(actionIcon("math"), document.createTextNode("Formulas"));
summary.title = "How to calculate with table cells";
// Committing a wrapped formula can shrink its row. Keep the click target in
// place until mouseup, then finish editing and give keyboard focus to help.
summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } });
summary.addEventListener("click", () => { finish(); summary.focus(); });
const instructions = document.createElement("div");
instructions.className = "table-formula-instructions";
const intro = document.createElement("p");
intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2.";
const examples = document.createElement("dl");
for (const [formula, description] of [
["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."],
["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."],
["=SUM(B2:B10)", "Add the values in a range."],
["=(B2+C2)/2", "Add two values and divide by two."],
["=ROUND(B2/3,2)", "Round to two decimal places."],
]) {
const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd");
code.textContent = formula; term.append(code); descriptionElement.textContent = description;
examples.append(term, descriptionElement);
}
const functions = document.createElement("p");
functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range.";
const references = document.createElement("p");
references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting.";
instructions.append(intro, examples, functions, references);
formulaHelp.append(summary, instructions);
formulaHelp.addEventListener("toggle", () => view.requestMeasure());
const formulaStatus = document.createElement("span");
formulaStatus.className = "table-formula-status";
formulaStatus.textContent = "Type = in a cell to calculate";
const formulaHint = document.createElement("div");
formulaHint.className = "table-formula-hint";
formulaHint.hidden = true;
formulaTools.append(formulaHelp, formulaStatus);
footer.append(help, formulaTools, formulaHint);
wrapper.after(footer);
for (const kind of ["column", "row"] as const) {
const button = document.createElement("button");
const label = kind === "column" ? "Add column to the right" : "Add row below";
button.type = "button";
button.className = `table-add table-add-${kind}`;
button.title = label;
button.setAttribute("aria-label", label);
const plus = document.createElement("span");
plus.append(actionIcon("plus"));
plus.setAttribute("aria-hidden", "true");
button.append(plus);
button.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); });
button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); add(kind); });
button.addEventListener("pointermove", event => {
const rect = button.getBoundingClientRect();
button.style.setProperty("--table-add-position", `${kind === "column" ? Math.max(12, Math.min(rect.height - 12, event.clientY - rect.top)) : Math.max(12, Math.min(rect.width - 12, event.clientX - rect.left))}px`);
});
wrapper.append(button);
}
for (const row of table.rows) for (const cell of row.cells) {
cell.tabIndex = 0;
cell.setAttribute("aria-label", `${cellAddress(row.rowIndex, cell.cellIndex)} · Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
cell.addEventListener("focus", () => activate(cell));
}
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate }, actions);
dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change);
table.addEventListener("mousedown", event => {
if (event.button !== 0) return;
if (event.ctrlKey || event.metaKey || !(event.target instanceof Element)) return;
const cell = event.target.closest<HTMLTableCellElement>("td, th");
if (!cell) return;
event.stopPropagation();
if (active !== cell) {
event.preventDefault(); activate(cell);
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
}
});
refreshFormulas();
}