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.
This commit is contained in:
Knotty Wyvern
2026-10-28 01:05:43 -07:00
parent 72671e5d01
commit 5e1533c371
43 changed files with 580 additions and 198 deletions
+25 -17
View File
@@ -2,22 +2,27 @@ import { readFile } from "node:fs/promises";
import { resolve } from "node:path";
import { pathToFileURL } from "node:url";
/** Load the actual compiled packages through the production Blob module loader. */
export async function mockFeaturePlugins(surface) {
const packages = await Promise.all(["terminal", "table-formulas"].map(async name => {
const root = name === "terminal"
? (process.env.RUNESTONE_TERMINAL_DIST ? pathToFileURL(resolve(process.env.RUNESTONE_TERMINAL_DIST) + "/") : new URL("../../../../RuneStone_Terminal/dist/", import.meta.url))
: new URL(`../../../plugin-packages/${name}/`, import.meta.url);
return {
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
code: await readFile(new URL("main.js", root), "utf8"),
css: name === "terminal" ? await readFile(new URL("style.css", root), "base64") : "",
};
}));
await surface.addInitScript(packages => {
/** An installed package of the old Table Formulas plugin. RuneStone now includes the feature and must not load this code. */
export const oldTableFormulasRow = {
manifest: { schemaVersion: 1, id: "runestone.table-formulas", name: "Table Formulas", author: "RuneStone Team", description: "Calculate formulas in Markdown tables.", version: "0.1.3", apiVersion: 1, entry: "main.js", access: "full-app" },
hash: "old-hash", enabled: true, path: "C:\\AppData\\RuneStone\\plugins\\runestone.table-formulas", error: null, removal: false,
};
/**
* Load the compiled Terminal package through the production Blob module loader.
* `extraRows` adds installed rows without code, for example `oldTableFormulasRow`.
*/
export async function mockFeaturePlugins(surface, extraRows = []) {
const root = process.env.RUNESTONE_TERMINAL_DIST ? pathToFileURL(resolve(process.env.RUNESTONE_TERMINAL_DIST) + "/") : new URL("../../../../RuneStone_Terminal/dist/", import.meta.url);
const packages = [{
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
code: await readFile(new URL("main.js", root), "utf8"),
css: await readFile(new URL("style.css", root), "base64"),
}];
await surface.addInitScript(({ packages, extraRows }) => {
const key = "test.installed-plugins";
const root = "C:\\AppData\\RuneStone\\plugins";
const defaults = packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false }));
const defaults = [...packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false })), ...extraRows];
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(defaults));
const write = rows => { localStorage.setItem(key, JSON.stringify(rows)); window.__TEST__?.emit("plugins-changed", {}); };
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(defaults));
@@ -27,8 +32,11 @@ export async function mockFeaturePlugins(surface) {
if (!command.startsWith("plugins_")) return original(command, args);
window.__TEST__?.calls.push({ command, args });
if (command === "plugins_snapshot") return { root, plugins: read() };
if (command === "plugins_load") return packages.find(item => item.manifest.id === args.id).code;
if (command === "plugins_asset") return packages.find(item => item.manifest.id === args.id).css;
if (command === "plugins_load" || command === "plugins_asset") {
const item = packages.find(item => item.manifest.id === args.id);
if (!item) throw new Error(`No code for ${args.id}`);
return command === "plugins_load" ? item.code : item.css;
}
if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; }
if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) };
if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; }
@@ -36,5 +44,5 @@ export async function mockFeaturePlugins(surface) {
if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return;
throw new Error(`Unhandled plugin IPC: ${command}`);
};
}, packages);
}, { packages, extraRows });
}
+1 -1
View File
@@ -1,5 +1,5 @@
// Custom window controls: maximize, restore, minimize, the terminal close guard, the keyboard tooltip, and the header at 1400 and 880 px.
// @requires plugin:terminal plugin:table-formulas
// @requires plugin:terminal
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
+1 -1
View File
@@ -1,5 +1,5 @@
// Core workbench: source edits and history, agent refresh and conflicts, persistent terminals, Reading and Mermaid previews, the live Writer, tables and their menus, and narrow layouts.
// @requires plugin:terminal plugin:table-formulas
// @requires plugin:terminal
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
+2 -1
View File
@@ -89,7 +89,8 @@ await runSmoke("links/linkEditing", async ({ page }) => {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
await page.locator('.writer-table td').nth(1).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(),/Row 2, column 2/);
// Table formulas are on by default, so the cell tooltip shows the cell address.
assert.equal(await page.locator('.rs-tooltip:popover-open').innerText(),'B2');
await page.screenshot({path:path.join(output, 'editor-cell-tooltip-narrow-'+mode+'.png')});
await page.keyboard.press('Escape');
await page.mouse.move(5,90);
+25 -16
View File
@@ -1,9 +1,10 @@
// Feature plug-in lifecycle: Table formulas and Terminal turn off, persist, reopen across windows, and uninstall without restoration.
// @requires plugin:terminal plugin:table-formulas
// Feature lifecycle: the built-in Table formulas setting and the Terminal plug-in turn off, persist, reopen across windows, and uninstall without restoration.
// An old Table Formulas package stays inactive and shows that the feature is built in.
// @requires plugin:terminal
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
import { mockFeaturePlugins } from '../_harness/pluginMocks.mjs';
import { mockFeaturePlugins, oldTableFormulasRow } from '../_harness/pluginMocks.mjs';
await runSmoke('plugins/lifecycle', async ({ browser }) => {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
@@ -44,7 +45,7 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
};
},
});
await mockFeaturePlugins(context);
await mockFeaturePlugins(context, [oldTableFormulasRow]);
const output = await outputDir('plugins/lifecycle');
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
const table = page.locator('.live-writer table');
@@ -58,13 +59,15 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await page.getByRole('dialog').getByRole('button').filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
}
async function settings() {
async function settings(category = 'Plug-ins') {
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
await settingsPage.goto(smokeUrl + '/?settingsWindow=true');
await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
await dialog.getByRole('button', { name: category, exact: true }).click();
}
// The switch of an old package of a built-in feature stays disabled.
const idle = () => settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled || input.id === 'external-runestone.table-formulas'));
async function closeSettings() {
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
await idle();
await settingsPage.goto(smokeUrl + '/__settings-closed');
await page.bringToFront();
}
@@ -76,28 +79,30 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await quickOpen('formulas.md');
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').innerText(), '6');
await settings();
assert(!await page.evaluate(() => window.__TEST__.calls.some(call => call.command === 'plugins_load' && call.args.id === 'runestone.table-formulas')), 'The old Table Formulas package does not load');
await settings('General');
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
assert.equal(await page.evaluate(() => window.__TEST__.settings('general').tableFormulas), false, 'The settings file stores the choice');
assert.match(await table.innerText(), /=A2\*3/);
assert.equal(await page.locator('.table-formula-tools').count(), 0);
await table.locator('td').last().click();
await page.locator('.writer-cell-editor').fill('=A2*4');
await page.keyboard.press('Enter');
await settings();
await settings('General');
await switchFor('Table formulas').check();
await closeSettings();
await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8');
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
const preview = page.locator('.md-page table').first();
await preview.locator('.md-table-formula').waitFor();
await settings();
await settings('General');
await switchFor('Table formulas').uncheck();
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-page .md-table-formula'));
assert.match(await preview.innerText(), /=A2\*4/);
await settings();
await settings('General');
await switchFor('Table formulas').check();
await closeSettings();
await preview.locator('.md-table-formula').waitFor();
@@ -109,6 +114,10 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
await page.waitForFunction(ptyCalled, 'pty_open');
await settings();
const oldPackage = dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name: 'Table Formulas', exact: true }) });
await oldPackage.getByText('Included with RuneStone', { exact: true }).waitFor();
await oldPackage.getByText(/Table Formulas is now built in\. You can remove this old package\./).waitFor();
assert(await oldPackage.getByRole('switch').isDisabled(), 'The old package cannot be enabled');
await switchFor('Terminal').uncheck();
await page.waitForFunction(ptyCalled, 'pty_close');
await settingsPage.screenshot({ path: path.join(output, 'plugins-settings.png') });
@@ -143,8 +152,8 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await quickOpen('formulas.md');
await settings();
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
for (const name of ['Terminal', 'Table formulas']) {
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
for (const name of ['Terminal', 'Table Formulas']) {
await idle();
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
@@ -152,9 +161,9 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
await switchFor(name).waitFor({ state: 'detached' });
}
await closeSettings();
await page.waitForFunction(() => !document.querySelector('.md-table-formula') && !document.querySelector('.xterm'));
await page.waitForFunction(() => !document.querySelector('.xterm'));
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
assert.match(await table.innerText(), /=A2\*4/);
assert.equal(await table.locator('.md-table-formula').innerText(), '8', 'Removing the old package keeps the built-in formulas');
await page.reload();
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await settings();
@@ -168,5 +177,5 @@ await runSmoke('plugins/lifecycle', async ({ browser }) => {
console.log([...page.errors, ...settingsPage.errors]);
throw error;
}
console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.');
console.log('Plugin smoke passed: formula setting, source preservation, inactive old package, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.');
});
+22 -4
View File
@@ -1,9 +1,8 @@
// Table formulas: live recalculation, raw formula editing, Enter and Tab, undo, cycles, saving, the footer layout, and the Read and Split views.
// @requires plugin:terminal plugin:table-formulas
// Built-in table formulas: live recalculation, raw formula editing, Enter and Tab, undo, cycles, saving, the footer layout, the Read and Split views,
// and the general setting that turns formulas off and on.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
const source = '# Table formulas\n\n| Name | Appearance | Charisma | Combined |\n| --- | ---: | ---: | ---: |\n| First | 9 | 10 | =AVERAGE(B2:C2) |\n| Second | 7 | 9 | =SUM(B3+C3)/2 |\n| Total | | | =SUM(D2:D3) |\n\nAfter.\n';
@@ -17,7 +16,6 @@ await runSmoke("tables/formulas", async ({ page }) => {
return workspace;
},
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
@@ -137,4 +135,24 @@ await runSmoke("tables/formulas", async ({ page }) => {
const total = preview.locator('tbody tr').filter({ hasText: 'Total' });
assert.equal(await total.locator('.md-table-formula').last().innerText(), '58', `${mode} view`);
}
// The general setting turns formulas off in all views. The source text shows and the file stays the same.
const file = await page.evaluate(() => window.__TEST__.files.get('formulas.md'));
const general = await page.evaluate(() => window.__TEST__.settings('general') ?? {});
await page.evaluate(value => window.__TEST__.writeSettings('general', value), { ...general, tableFormulas: false });
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
const total = page.locator('.md-page table').first().locator('tbody tr').filter({ hasText: 'Total' });
assert.match(await total.innerText(), /=SUM\(D2:D3\)/);
assert.match(await total.innerText(), /=SUM\(B2:B3\)/);
await shot('formulas-off-split');
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { name: 'Edit', exact: true }).click();
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').count(), 0);
assert.match(await cell(3, 3).innerText(), /=SUM\(D2:D3\)/);
assert.equal(await page.locator('.table-formula-tools').count(), 0, 'Writer shows no formula help');
await shot('formulas-off-writer');
await page.evaluate(value => window.__TEST__.writeSettings('general', value), { ...general, tableFormulas: true });
await result(3, 3).waitFor();
assert.equal(await result(3, 3).innerText(), '58');
await page.locator('.table-formula-tools').first().waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.files.get('formulas.md')), file);
});
+4 -4
View File
@@ -62,7 +62,7 @@ await runSmoke("tables/linkCaret", async ({ page }) => {
await page.getByRole('button', { name:'Files', exact:true }).click();
await page.getByRole('button', { name:'Hide outline', exact:true }).click();
}
const cell = page.getByRole('cell', { name:'Row 6, column 2', exact:true });
const cell = page.getByRole('cell', { name:'B6 · Row 6, column 2', exact:true });
await clickTextAt(cell.locator('a'), 5);
await sourceCell().waitFor();
assert.equal(await cell.locator('.writer-link-target').innerText(), 'docs/roadmap.md', 'Ordinary click reveals the URL');
@@ -89,7 +89,7 @@ await runSmoke("tables/linkCaret", async ({ page }) => {
await page.keyboard.press('Control+s');
assert.match(await page.evaluate(() => window.__TEST__.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
const keyboard = page.getByRole('cell', { name:'Row 7, column 2', exact:true });
const keyboard = page.getByRole('cell', { name:'B7 · Row 7, column 2', exact:true });
await clickTextAt(keyboard, 7);
assert.equal(await sourceCell().count(), 0, 'Plain cell text remains rendered');
await page.keyboard.press('ArrowRight');
@@ -99,7 +99,7 @@ await runSmoke("tables/linkCaret", async ({ page }) => {
await shot(`keyboard-${theme}-${width}`);
await page.keyboard.press('Escape');
const wiki = page.getByRole('cell', { name:'Row 8, column 2', exact:true });
const wiki = page.getByRole('cell', { name:'B8 · Row 8, column 2', exact:true });
await clickTextAt(wiki.locator('a'), 3);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '[[guide\\|Gui');
@@ -110,7 +110,7 @@ await runSmoke("tables/linkCaret", async ({ page }) => {
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'), 'new-guide');
const repeated = page.getByRole('cell', { name:'Row 9, column 2', exact:true });
const repeated = page.getByRole('cell', { name:'B9 · Row 9, column 2', exact:true });
await clickTextAt(repeated.locator('a').nth(1), 4);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '**Prefix** [One](same.md) + [Sec**o');
+1 -1
View File
@@ -1,5 +1,5 @@
// Table keyboard navigation: arrows, caret positions, entry and exit in all directions, goal columns, line breaks, stable cell sizes, saving, and undo.
// @requires plugin:terminal plugin:table-formulas
// @requires plugin:terminal
import assert from "node:assert/strict";
import { mockTauri, runSmoke, settle, smokeUrl } from "../_harness/index.mjs";
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
+7 -5
View File
@@ -7,9 +7,9 @@ test("missing or damaged preferences keep safe defaults", () => {
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
}
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false });
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true });
}
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false });
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false, tableFormulas: true });
});
function withStorage(storage: Pick<Storage, "getItem" | "setItem">, body: () => void) {
@@ -22,7 +22,7 @@ test("preferences persist and load at both interval limits", () => {
const store = new Map<string, string>();
withStorage({ getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => { store.set(key, value); } }, () => {
for (const autosaveSeconds of [1, 23, 300]) {
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false };
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false, tableFormulas: autosaveSeconds !== 23 };
void saveSettings(settings);
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
assert.deepEqual(readSettings(), settings);
@@ -34,7 +34,7 @@ test("invalid changes never reach storage and storage failures reach the caller"
let writes = 0;
withStorage({ getItem: () => null, setItem: () => { writes++; } }, () => {
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false }));
assert.throws(() => saveSettings({ autosaveEnabled: true, autosaveSeconds, showInternalFolder: false, tableFormulas: true }));
}
});
assert.equal(writes, 0);
@@ -45,5 +45,7 @@ test("invalid changes never reach storage and storage failures reach the caller"
test("stored values of any type normalize to safe settings", () => {
for (const value of [undefined, null, 42, "text", [], { autosaveSeconds: 0 }]) assert.deepEqual(normalizeSettings(value), DEFAULT_SETTINGS);
assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true });
assert.deepEqual(normalizeSettings({ autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true }), { autosaveEnabled: false, autosaveSeconds: 9, showInternalFolder: true, tableFormulas: true });
assert.equal(normalizeSettings({ tableFormulas: false }).tableFormulas, false);
for (const tableFormulas of [null, 0, "false", {}]) assert.equal(normalizeSettings({ tableFormulas }).tableFormulas, true);
});
+26 -28
View File
@@ -2,14 +2,12 @@ import test from "node:test";
import assert from "node:assert/strict";
import { ContributionRegistry, pluginHost } from "../../../src/lib/plugins/registry.ts";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import { existsSync } from "node:fs";
// The Table Formulas package comes from a sibling repository. Run `pnpm build:plugins` to build it.
const tableFormulasEntry = new URL("../../../plugin-packages/table-formulas/main.js", import.meta.url);
const tableFormulas = existsSync(tableFormulasEntry) ? await import(tableFormulasEntry.href) : undefined;
const activate = tableFormulas?.activate;
const needsTableFormulas = { skip: tableFormulas ? false : "the Table Formulas package is not built; run pnpm build:plugins" };
import { renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
import type { PluginApi } from "../../../src/lib/plugins/sdk.ts";
import type { Contributions } from "../../../src/lib/plugins/contracts.ts";
// A small test-only package. It contributes a feature, as the optional plugins do.
const blame: Contributions["git"] = { blame: async () => null };
const activate = (api: PluginApi) => { api.contribute("git", blame); };
const services = {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
@@ -38,45 +36,45 @@ test("optional workspace creation and reads stop when the plugin is disabled", a
assert.throws(() => api.workspace.readOptional!("board.json"), /disabled/);
assert.equal(files.size, 1);
});
test("core starts without optional features and formula packages preserve source when stopped", needsTableFormulas, async () => {
test("core starts without optional features and package contributions end with their session", async () => {
assert.equal(pluginHost.get("terminal"), undefined);
assert.equal(pluginHost.get("tableFormulas"), undefined);
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
assert.doesNotMatch(renderMarkdownHtml(source, new Map()), /md-table-formula/);
const session = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
assert.equal(pluginHost.get("git"), undefined);
const registry = new ContributionRegistry();
const session = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await session.start({ activate });
const enabled = renderMarkdownHtml(source, new Map());
assert.match(enabled, />6<\/span>/);
assert.equal(registry.get("git"), blame);
await session.stop();
for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) {
assert.doesNotMatch(html, /md-table-formula/);
assert.match(html, /=A2\*3/);
assert.match(html, /<table>/);
}
const next = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
assert.equal(registry.get("git"), undefined);
const next = new ExternalSession("org.test.feature", services, () => {}, () => {}, registry);
await next.start({ activate });
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
assert.equal(registry.get("git"), blame);
await next.stop();
assert.equal(registry.get("git"), undefined);
});
test("package contribution conflicts preserve the first owner and revoke access before cleanup", needsTableFormulas, async () => {
test("unknown contribution keys are rejected", () => {
const registry = new ContributionRegistry();
assert.throws(() => registry.register("old", "tableFormulas" as keyof Contributions, blame as never), /Unknown plugin contribution/);
});
test("package contribution conflicts preserve the first owner and revoke access before cleanup", async () => {
const registry = new ContributionRegistry();
const first = new ExternalSession("first", services, () => {}, () => {}, registry);
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
let api!: PluginApi;
await first.start({ activate(value) { api = value; activate(api); } });
const contribution = registry.get("tableFormulas");
const contribution = registry.get("git");
await assert.rejects(second.start({ activate }), /already registered/);
await second.stop();
assert.equal(registry.get("tableFormulas"), contribution);
assert.equal(registry.get("git"), contribution);
api.onDispose(() => {
assert.equal(registry.get("tableFormulas"), undefined);
assert.throws(() => api.contribute("tableFormulas", contribution!), /disabled/);
assert.equal(registry.get("git"), undefined);
assert.throws(() => api.contribute("git", contribution!), /disabled/);
});
await first.stop();
});
test("partial activation and failed cleanup cannot retain feature contributions", needsTableFormulas, async () => {
test("partial activation and failed cleanup cannot retain feature contributions", async () => {
const registry = new ContributionRegistry();
const session = new ExternalSession("failed", services, () => {}, () => {}, registry);
await assert.rejects(session.start({ activate(api) {
@@ -85,5 +83,5 @@ test("partial activation and failed cleanup cannot retain feature contributions"
throw new Error("Activation failed");
} }), /Activation failed/);
await assert.rejects(session.stop(), /Cleanup failed/);
assert.equal(registry.get("tableFormulas"), undefined);
assert.equal(registry.get("git"), undefined);
});
+2 -2
View File
@@ -16,7 +16,7 @@ test('Migration reads the four old keys and the theme backup, and normalizes eac
'runestone.language': 'fr',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false },
general: { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true },
language: 'fr',
customThemes: [custom],
customThemesLegacy: [{ schema: 1, id: 'kept' }],
@@ -50,7 +50,7 @@ test('Damaged old values become defaults and unknown languages become English',
'runestone.language': 'de',
}));
assert.deepEqual(sections, {
general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false },
general: { autosaveEnabled: true, autosaveSeconds: 5, showInternalFolder: false, tableFormulas: true },
language: 'en',
appearance: { theme: 'default', mode: 'dark' },
});
+1 -1
View File
@@ -64,7 +64,7 @@ test('The first start migrates the old localStorage values, and later reads come
assert.deepEqual(calls.filter(call => !call.command.startsWith('plugin:')).map(call => call.command), ['settings_read', 'settings_migrate']);
assert.equal(calls[0].command, 'plugin:event|listen', 'The listener starts before the read');
assert.equal(store.readSection('language'), 'ja');
assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false });
assert.deepEqual(store.readSection('general'), { autosaveEnabled: true, autosaveSeconds: 12, showInternalFolder: false, tableFormulas: true });
assert.equal(legacy.get('runestone.language'), 'ja', 'The old value stays in place');
assert.equal(store.takeSettingsNotice(), 'Notice once');
assert.equal(store.takeSettingsNotice(), null);
+68
View File
@@ -0,0 +1,68 @@
// Ported from the Table Formulas plugin (tests/formulas.test.ts). The engine is now part of the host.
import assert from "node:assert/strict";
import test from "node:test";
import { cellAddress, evaluateTableFormulas } from "../../../src/lib/formulas/engine.ts";
const calculate = (formula: string) => evaluateTableFormulas([[formula]])[0][0]!.text;
test("aggregates distinguish separate cells and ranges from an arithmetic argument", () => {
const evaluate = (formula: string) => evaluateTableFormulas([["Name", "B", "C", "Result"], ["First", "9", "10", formula]])[1][3]!;
for (const [name, separate, combined] of [["SUM", "19", "19"], ["AVERAGE", "9.5", "19"], ["MIN", "9", "19"], ["MAX", "10", "19"], ["COUNT", "2", "1"]]) {
for (const separator of [",", ":"]) {
const result = evaluate(`=${name}(B2${separator}C2)`);
assert.equal(result.text, separate);
}
const result = evaluate(`=${name}(B2+C2)`);
assert.equal(result.text, combined);
}
assert.equal(evaluate("=(B2+C2)/2").text, "9.5");
assert.equal(evaluate("=ROUND(AVERAGE(B2,C2),0)").text, "10");
assert.equal(evaluate("=ABS(B2-C2)").text, "1");
assert.equal(evaluate("=AVERAGE((B2+C2))").text, "19");
});
test("arithmetic, precedence, parentheses, percentages and rounding", () => {
for (const [formula, result] of [
["=SUM(2+3)", "5"], ["=2+3*4", "14"], ["=(2+3)*4", "20"],
["=2^3^2", "512"], ["=-2^2", "-4"], ["=2^-2", "0.25"],
["=200*10%", "20"], ["=0.1+0.2", "0.3"], ["=1e2 + .5", "100.5"],
["=ROUND(-1.25,1)", "-1.3"], ["=ROUND(1.005,2)", "1.01"],
["=ROUND(125,-1)", "130"], ["=ABS(-4)", "4"], ["=sum(1,2,3)", "6"],
]) assert.equal(calculate(formula), result, formula);
});
test("same-table references, ranges, chained dependencies, and empty/text cells", () => {
const results = evaluateTableFormulas([
["Name", "Appearance", "Cha", "Combined"],
["First", "9", "10", "=AVERAGE(B2:C2)"],
["Second", "7", "9", "=SUM(B3,C3)/2"],
["Total", "", "=B4+1", "=SUM(D2:D3)"],
["Count", "=COUNT(A1:C4)", "=MAX(B2:C3)-MIN(B2:C3)", "=ROUND(D4/3,2)"],
["", "=SUM($B$2:$C$3)", "=AVERAGE(B1:B4)", "=SUM(C3:B2)"],
]);
assert.equal(results[1][3]?.text, "9.5");
assert.equal(results[2][3]?.text, "8");
assert.equal(results[3][3]?.text, "17.5");
assert.equal(results[3][2]?.text, "1");
assert.equal(results[4][1]?.text, "5");
assert.equal(results[4][2]?.text, "3");
assert.equal(results[4][3]?.text, "5.83");
assert.equal(results[5][1]?.text, "35");
assert.equal(results[5][2]?.text, "8");
assert.equal(results[5][3]?.text, "35");
assert.equal(results[0][0], null);
assert.equal(cellAddress(1, 26), "AA2");
assert.equal(evaluateTableFormulas([Array.from({ length: 27 }, (_, c) => c === 0 ? "=AA1" : "3")])[0][0]?.text, "3");
});
test("errors are visible, propagated, bounded, and never executed", () => {
for (const [formula, result] of [
["=1/0", "#DIV/0!"], ["=AVERAGE()", "#DIV/0!"], ["=A2", "#REF!"],
["=B1:B999999999", "#REF!"], ["=A0", "#REF!"], ["=1+", "#ERROR!"],
["=1 2", "#ERROR!"], ["=ROUND(1,2,3)", "#ERROR!"], ["=BOGUS(1)", "#NAME?"],
["=A1", "#CYCLE!"], ["=1e999", "#NUM!"], ["=9^9999", "#NUM!"],
["=globalThis.alert(1)", "#ERROR!"], ["=" + "(".repeat(100) + "1" + ")".repeat(100), "#LIMIT!"],
]) assert.equal(calculate(formula), result, formula);
const cycle = evaluateTableFormulas([["=B1", "=A1", "=SUM(A1:B1)", "=2+3"]]);
assert.deepEqual(cycle[0].map(cell => cell?.text), ["#CYCLE!", "#CYCLE!", "#CYCLE!", "5"]);
assert.equal(evaluateTableFormulas([["text", "=A1+1"]])[0][1]?.text, "#VALUE!");
});
+46 -18
View File
@@ -1,24 +1,14 @@
import assert from "node:assert/strict";
import test, { before, after } from "node:test";
import { ExternalSession } from "../../../src/lib/plugins/externalSession.ts";
import { existsSync } from "node:fs";
// The Table Formulas package comes from a sibling repository. Run `pnpm build:plugins` to build it.
const tableFormulasEntry = new URL("../../../plugin-packages/table-formulas/main.js", import.meta.url);
const tableFormulas = existsSync(tableFormulasEntry) ? await import(tableFormulasEntry.href) : undefined;
const activate = tableFormulas?.activate;
const needsTableFormulas = { skip: tableFormulas ? false : "the Table Formulas package is not built; run pnpm build:plugins" };
const session = new ExternalSession("runestone.table-formulas", {
workspace: { list: async () => [], read: async () => "", write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
before(() => activate && session.start({ activate }));
after(() => activate && session.stop());
import test, { afterEach } from "node:test";
import { get } from "svelte/store";
import MarkdownIt from "markdown-it";
import { activeTableFormulas, renderTableFormulas, setTableFormulasEnabled, tableFormulaHtml, tableFormulas, tableFormulasEnabled } from "../../../src/lib/formulas/index.ts";
import { tableCellMarkdown } from "../../../src/lib/editor/tableCellMarkdown.ts";
import { renderMarkdownHtml, renderMarkdownSections } from "../../../src/lib/workspace/noteHtml.ts";
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", needsTableFormulas, () => {
afterEach(() => setTableFormulasEnabled(true));
test("Markdown rendering isolates tables and preserves literal, formatted, and non-table text", () => {
const source = "| X | Y | Result |\r\n| --- | --- | --- |\r\n| 9 | 10 | =AVERAGE(A2:B2) |\r\n\r\n| X | Y | Result |\r\n| --- | --- | --- |\r\n| 1 | 3 | =A2*B2 |\r\n";
const html = renderMarkdownHtml(source, new Map());
assert.match(html, /aria-label="=AVERAGE\(A2:B2\) → 9.5">9.5<\/span>/);
@@ -34,9 +24,47 @@ test("Markdown rendering isolates tables and preserves literal, formatted, and n
assert.match(hostile, /#ERROR!/);
});
test("editing keeps formulas readable and code or explicit escapes literal", needsTableFormulas, () => {
test("editing keeps formulas readable and code or explicit escapes literal", () => {
const doc = (text: string, marks?: { type: string }[]) => ({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text, marks }] }] });
assert.equal(tableCellMarkdown(doc("=SUM($B$2:C2)*50%")), "=SUM($B$2:C2)*50%");
assert.equal(tableCellMarkdown(doc("\\=1+2")), "\\=1+2");
assert.equal(tableCellMarkdown(doc("=1+2", [{ type: "code" }])), "`=1+2`");
});
test("the setting turns formulas off and back on without a change to the source", () => {
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
assert.equal(get(tableFormulasEnabled), true, "Formulas are on by default");
assert.equal(activeTableFormulas(), tableFormulas);
const enabled = renderMarkdownHtml(source, new Map());
assert.match(enabled, />6<\/span>/);
setTableFormulasEnabled(false);
assert.equal(activeTableFormulas(), undefined);
for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) {
assert.doesNotMatch(html, /md-table-formula/);
assert.match(html, /=A2\*3/);
assert.match(html, /<table>/);
}
setTableFormulasEnabled(true);
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
});
// Ported from the Table Formulas plugin (tests/render.test.ts).
test("rendering separates tables and preserves literal expressions", () => {
const markdown = new MarkdownIt();
const source = "| A | B |\n| --- | --- |\n| 3 | =A2*2 |\n\n| A | B |\n| --- | --- |\n| 4 | =A2+1 |\n\n| Literal |\n| --- |\n| `=1+2` |\n| \\=1+2 |\n";
const tokens = markdown.parse(source, {});
renderTableFormulas(tokens);
const html = markdown.renderer.render(tokens, markdown.options, {});
assert.match(html, /aria-label="=A2\*2 → 6">6<\/span>/);
assert.match(html, /aria-label="=A2\+1 → 5">5<\/span>/);
assert.match(html, /<code>=1\+2<\/code>/);
assert.equal((html.match(/class="md-table-formula"/g) || []).length, 2);
});
test("formula labels escape markup and report errors", () => {
const html = tableFormulaHtml({ formula: '=SUM("<img>")', text: "#ERROR!", error: "#ERROR!" });
assert.doesNotMatch(html, /<img>/);
assert.match(html, /&quot;&lt;img&gt;&quot;/);
assert.match(html, /md-table-formula is-error/);
assert.match(html, /Invalid formula syntax or function arguments/);
});