Release RuneStone 0.1.4 with installable plugins and settings
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState } from "@codemirror/state";
|
||||
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
||||
@@ -33,8 +34,10 @@
|
||||
focusLine?: number | null;
|
||||
tableActions?: TableContextActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
focusTitle?: boolean;
|
||||
onTitleFocused?: () => void;
|
||||
};
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor = $state.raw<EditorView>();
|
||||
let error = $state("");
|
||||
@@ -234,7 +237,7 @@
|
||||
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
|
||||
focus() { view.focus(); },
|
||||
}, untrack(() => tableActions), message => { error = message; });
|
||||
if (shouldFocusOnMount()) view.focus();
|
||||
if (!focusTitle && shouldFocusOnMount()) view.focus();
|
||||
}).catch(reason => { if (!cancelled) error = String(reason); });
|
||||
return () => {
|
||||
cancelled = true;
|
||||
@@ -251,12 +254,25 @@
|
||||
};
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
void $pluginHost;
|
||||
editor?.dispatch({ effects: refreshImages.of() });
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const name = markdownTitle(buffer.relPath);
|
||||
const view = editor;
|
||||
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!focusTitle || !editor) return;
|
||||
const button = editor.dom.querySelector<HTMLButtonElement>(".note-title-button");
|
||||
if (!button) return;
|
||||
button.click();
|
||||
onTitleFocused?.();
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
const value = buffer.contents;
|
||||
const path = buffer.relPath;
|
||||
|
||||
@@ -10,6 +10,9 @@ import { imageControls } from "./imageControls";
|
||||
import { ImagePreview, type ImageContext } from "./imagePreview";
|
||||
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
|
||||
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
|
||||
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||
export const refreshImages = StateEffect.define<void>();
|
||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
@@ -54,20 +57,22 @@ class Checkbox extends WidgetType {
|
||||
}
|
||||
|
||||
class Preview extends WidgetType {
|
||||
readonly formulas = pluginHost.get("tableFormulas");
|
||||
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.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
|
||||
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 (tableEditors.get(dom)?.source !== this.source) return false;
|
||||
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;
|
||||
tableControls(dom, view, this.source, this.actions);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
import { isTableFormula } from "./tableFormulas.ts";
|
||||
// Preserve formula source even when calculation is disabled.
|
||||
const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
|
||||
|
||||
// Extract inline content into a note without confusing literal <br> in code
|
||||
// with actual cell hard breaks.
|
||||
|
||||
@@ -11,8 +11,7 @@ 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";
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
|
||||
const cellFormats = ["math", "comment"].map(name => Mark.create({
|
||||
name,
|
||||
@@ -36,6 +35,7 @@ const CellImage = Image.extend({
|
||||
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 formulas = pluginHost.get("tableFormulas");
|
||||
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
|
||||
const table = scroll?.querySelector("table");
|
||||
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
|
||||
@@ -76,17 +76,17 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
|
||||
function refreshFormulas() {
|
||||
const parsed = parseMarkdownTable(controller.source);
|
||||
if (!parsed) return;
|
||||
if (!parsed || !formulas) 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);
|
||||
const results = formulas.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);
|
||||
const address = formulas.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 (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
|
||||
if (cell === active) {
|
||||
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
|
||||
formulaHint.textContent = result?.error ? formulaErrors[result.error] : "";
|
||||
formulaHint.textContent = result?.error ? formulas.formulaErrors[result.error] : "";
|
||||
formulaHint.hidden = !formulaHint.textContent;
|
||||
}
|
||||
}
|
||||
@@ -156,9 +156,9 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
// 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 formula = originalCell && (/^=(?!=)/.test(originalCell.text.trim()) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
|
||||
const html = cell.innerHTML;
|
||||
formulaStatus.textContent = `${cellAddress(row, column)} · Type = to calculate`;
|
||||
formulaStatus.textContent = formulas ? `${formulas.cellAddress(row, column)} · Type = to calculate` : "";
|
||||
cell.innerHTML = "";
|
||||
cell.classList.add("is-editing");
|
||||
editor = new Editor({
|
||||
@@ -239,7 +239,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
if (isTableFormula(editor?.getText() || "")) { finish(); wrapper.focus(); }
|
||||
if (/^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
|
||||
else if (event.ctrlKey || event.metaKey) leave(true);
|
||||
else editor?.commands.setHardBreak();
|
||||
return true;
|
||||
@@ -301,48 +301,11 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
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);
|
||||
const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure());
|
||||
const formulaStatus = tools?.formulaStatus ?? document.createElement("span");
|
||||
const formulaHint = tools?.formulaHint ?? document.createElement("div");
|
||||
footer.append(help);
|
||||
if (tools) footer.append(tools.formulaTools, formulaHint);
|
||||
wrapper.after(footer);
|
||||
for (const kind of ["column", "row"] as const) {
|
||||
const button = document.createElement("button");
|
||||
@@ -365,7 +328,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
}
|
||||
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.setAttribute("aria-label", `${formulas ? formulas.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);
|
||||
|
||||
@@ -1,151 +0,0 @@
|
||||
// Formulas are plain Markdown cell text. No JavaScript evaluation or external data.
|
||||
export const formulaErrors = {
|
||||
"#ERROR!": "Invalid formula syntax or function arguments",
|
||||
"#REF!": "Cell reference is outside this table",
|
||||
"#VALUE!": "Expected a number",
|
||||
"#NAME?": "Unknown function or cell name",
|
||||
"#DIV/0!": "Cannot divide by zero or average an empty range",
|
||||
"#CYCLE!": "Circular cell reference",
|
||||
"#NUM!": "Result is not a finite number",
|
||||
"#LIMIT!": "Formula is too complex",
|
||||
} as const;
|
||||
type ErrorCode = keyof typeof formulaErrors;
|
||||
export type FormulaResult = { formula: string; text: string; value?: number; error?: ErrorCode };
|
||||
class FormulaError extends Error {
|
||||
code: ErrorCode;
|
||||
constructor(code: ErrorCode) { super(formulaErrors[code]); this.code = code; }
|
||||
}
|
||||
function fail(code: ErrorCode): never { throw new FormulaError(code); }
|
||||
export const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
|
||||
|
||||
export function cellAddress(row: number, column: number): string {
|
||||
let letters = "";
|
||||
for (let n = column + 1; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + (n - 1) % 26) + letters;
|
||||
return letters + (row + 1);
|
||||
}
|
||||
|
||||
type Scalar = number | string | null;
|
||||
type Value = Scalar | Scalar[];
|
||||
const number = (value: Value): number => typeof value === "number" ? value : value === null ? 0 : fail("#VALUE!");
|
||||
const finite = (value: number) => Number.isFinite(value) ? value : fail("#NUM!");
|
||||
const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
|
||||
|
||||
// Header is row 1; the Markdown separator is not a spreadsheet row.
|
||||
export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[][] {
|
||||
const cache = new Map<string, Scalar | FormulaError>();
|
||||
const visiting = new Set<string>();
|
||||
let budget = 50000;
|
||||
const spend = () => { if (--budget < 0) fail("#LIMIT!"); };
|
||||
function reference(address: string): [number, number] {
|
||||
const match = /^\$?([A-Z]+)\$?([1-9]\d*)$/i.exec(address) || fail("#REF!");
|
||||
let column = 0;
|
||||
for (const letter of match[1].toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64;
|
||||
const row = Number(match[2]);
|
||||
if (row > grid.length || column > (grid[0]?.length || 0)) fail("#REF!");
|
||||
return [row - 1, column - 1];
|
||||
}
|
||||
function cell(row: number, column: number): Scalar {
|
||||
spend();
|
||||
const key = `${row}:${column}`;
|
||||
if (visiting.has(key)) fail("#CYCLE!");
|
||||
if (visiting.size >= 128) fail("#LIMIT!");
|
||||
const cached = cache.get(key);
|
||||
if (cached instanceof FormulaError) throw cached;
|
||||
if (cache.has(key)) return cached!;
|
||||
const source = (grid[row]?.[column] || "").trim();
|
||||
if (!isTableFormula(source)) return source === "" ? null : numeric.test(source) ? finite(Number(source)) : source;
|
||||
visiting.add(key);
|
||||
try {
|
||||
const value = parse(source.slice(1));
|
||||
cache.set(key, value);
|
||||
return value;
|
||||
} catch (error) {
|
||||
const problem = error instanceof FormulaError ? error : new FormulaError("#LIMIT!");
|
||||
cache.set(key, problem);
|
||||
throw problem;
|
||||
} finally { visiting.delete(key); }
|
||||
}
|
||||
function parse(source: string): number {
|
||||
if (source.length > 2048) fail("#LIMIT!");
|
||||
const tokens: string[] = [];
|
||||
const pattern = /\s*(\$?[A-Za-z]+\$?\d+|[A-Za-z_]+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+\-*/^%(),:])/y;
|
||||
let offset = 0;
|
||||
while (offset < source.trimEnd().length) {
|
||||
pattern.lastIndex = offset;
|
||||
const match = pattern.exec(source) || fail("#ERROR!");
|
||||
tokens.push(match[1]); offset = pattern.lastIndex;
|
||||
}
|
||||
let position = 0, depth = 0;
|
||||
const peek = () => tokens[position];
|
||||
const take = () => { spend(); return tokens[position++]; };
|
||||
const expect = (token: string) => { if (take() !== token) fail("#ERROR!"); };
|
||||
function expression(min = 0): Value {
|
||||
if (++depth > 64) fail("#LIMIT!");
|
||||
let left: Value;
|
||||
const token = take();
|
||||
if (token === "+" || token === "-") left = number(expression(3)) * (token === "-" ? -1 : 1);
|
||||
else if (token === "(") { left = expression(); expect(")"); }
|
||||
else if (token && numeric.test(token)) left = finite(Number(token));
|
||||
else if (token && /^\$?[a-z]+\$?\d+$/i.test(token)) {
|
||||
const [row, column] = reference(token);
|
||||
if (peek() === ":") {
|
||||
take(); const [endRow, endColumn] = reference(take() || "");
|
||||
const values: Scalar[] = [];
|
||||
for (let r = Math.min(row, endRow); r <= Math.max(row, endRow); r++) {
|
||||
for (let c = Math.min(column, endColumn); c <= Math.max(column, endColumn); c++) values.push(cell(r, c));
|
||||
}
|
||||
left = values;
|
||||
} else left = cell(row, column);
|
||||
} else if (token && /^[a-z_]+$/i.test(token)) {
|
||||
if (peek() !== "(") fail("#NAME?");
|
||||
take(); const args: Value[] = [];
|
||||
if (peek() !== ")") {
|
||||
do { args.push(expression()); if (peek() !== ",") break; take(); } while (true);
|
||||
}
|
||||
expect(")");
|
||||
left = call(token.toUpperCase(), args);
|
||||
} else fail("#ERROR!");
|
||||
while (true) {
|
||||
const op = peek();
|
||||
if (op === "%") { take(); left = number(left) / 100; continue; }
|
||||
const precedence = op === "+" || op === "-" ? 1 : op === "*" || op === "/" ? 2 : op === "^" ? 3 : -1;
|
||||
if (precedence < min) break;
|
||||
take();
|
||||
const right = number(expression(precedence + (op === "^" ? 0 : 1))), a = number(left);
|
||||
left = finite(op === "+" ? a + right : op === "-" ? a - right : op === "*" ? a * right : op === "/" ? (right === 0 ? fail("#DIV/0!") : a / right) : a ** right);
|
||||
}
|
||||
depth--;
|
||||
return left;
|
||||
}
|
||||
const result = finite(number(expression()));
|
||||
if (position !== tokens.length) fail("#ERROR!");
|
||||
return result;
|
||||
}
|
||||
function call(name: string, args: Value[]): number {
|
||||
if (name === "ABS") return args.length === 1 ? Math.abs(number(args[0])) : fail("#ERROR!");
|
||||
if (name === "ROUND") {
|
||||
if (args.length < 1 || args.length > 2) fail("#ERROR!");
|
||||
const value = number(args[0]), digits = args.length === 2 ? number(args[1]) : 0;
|
||||
if (!Number.isInteger(digits) || Math.abs(digits) > 100) fail("#NUM!");
|
||||
const factor = 10 ** digits, scaled = Math.abs(value) * factor;
|
||||
return finite(Math.sign(value) * Math.round(scaled + Number.EPSILON * scaled) / factor);
|
||||
}
|
||||
if (!["SUM", "AVERAGE", "MIN", "MAX", "COUNT"].includes(name)) fail("#NAME?");
|
||||
const values = args.flat().filter((value): value is number => typeof value === "number");
|
||||
if (name === "COUNT") return values.length;
|
||||
if (name === "MIN" || name === "MAX") return values.length ? values.reduce((a, b) => name === "MIN" ? Math.min(a, b) : Math.max(a, b)) : 0;
|
||||
const sum = finite(values.reduce((a, b) => a + b, 0));
|
||||
return name === "AVERAGE" ? (values.length ? sum / values.length : fail("#DIV/0!")) : sum;
|
||||
}
|
||||
return grid.map((row, r) => row.map((source, c) => {
|
||||
if (!isTableFormula(source)) return null;
|
||||
const formula = source.trim();
|
||||
try {
|
||||
const value = number(cell(r, c));
|
||||
return { formula, value, text: String(Number(value.toPrecision(12))) };
|
||||
} catch (error) {
|
||||
const code = error instanceof FormulaError ? error.code : "#LIMIT!";
|
||||
return { formula, text: code, error: code };
|
||||
}
|
||||
}));
|
||||
}
|
||||
Reference in New Issue
Block a user