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:
@@ -21,11 +21,11 @@ For checksums, updates, and reinstalls, see [Installation and updates](docs/inst
|
||||
|
||||
## What you can do
|
||||
|
||||
- Write Markdown with live formatting, editable tables, images, and Mermaid diagrams.
|
||||
- Write Markdown with live formatting, editable tables, table formulas, images, and Mermaid diagrams.
|
||||
- Switch between Writer, IDE source editing, Read, and Split views.
|
||||
- Find files, search a workspace, and resolve changes that other tools make to your files.
|
||||
- Open web pages in browser tabs beside your documents.
|
||||
- Add optional plugins, such as Terminal, Git, Project Management, Table Formulas, PDF Viewer, and CSV Viewer.
|
||||
- Add optional plugins, such as Terminal, Git, Project Management, PDF Viewer, and CSV Viewer.
|
||||
|
||||
## Find help
|
||||
|
||||
|
||||
+3
-4
@@ -81,6 +81,7 @@ A new command needs an entry in `generate_handler!` in `lib.rs`, in the command
|
||||
| --- | --- |
|
||||
| `layout/` | The app shell (`Workbench.svelte`), the file tree, tabs, panes, Settings, and dialogs |
|
||||
| `editor/` | The Writer view (`LiveWriter.svelte`), the source editor (`EditorHost.svelte`), tables, links, images, and editor menus |
|
||||
| `formulas/` | Table formulas: the parser and evaluator (`engine.ts`), the rendered results, the formula help, and the `tableFormulas` setting (`index.ts`) |
|
||||
| `workspace/` | Tauri wrappers, document buffers, the note index and backlinks, paths, templates, and tab transfer (`tabTransfer.ts`) |
|
||||
| `settings/` | The settings store (`store.ts`), and the code that moves the old browser values to the settings file (`migration.ts`) |
|
||||
| `plugins/` | The plugin runtime, the SDK types (`sdk.ts`), and Settings → Plug-ins |
|
||||
@@ -123,7 +124,7 @@ On macOS, it is `~/Library/Application Support/<identifier>/`. On Linux, it is `
|
||||
{
|
||||
"schema": 1,
|
||||
"revision": 12,
|
||||
"general": { "autosaveEnabled": true, "autosaveSeconds": 5, "showInternalFolder": false },
|
||||
"general": { "autosaveEnabled": true, "autosaveSeconds": 5, "showInternalFolder": false, "tableFormulas": true },
|
||||
"appearance": { "theme": "default", "mode": "dark" },
|
||||
"customThemes": [],
|
||||
"customThemesLegacy": [],
|
||||
@@ -146,7 +147,7 @@ After that, `src/lib/settings/store.ts` reads the sections from memory and tells
|
||||
## Product boundaries
|
||||
|
||||
- Workspace documents stay ordinary local files. Users keep access to them when plugins are disabled.
|
||||
- The core includes basic Markdown table editing and rendering.
|
||||
- The core includes Markdown table editing, rendering, and table formulas.
|
||||
- Native file access, file watching, search, Git, and terminals belong in Rust.
|
||||
- Optional features ship as plugins. The [plugin development reference](plugin-development.md) defines the package format and the API.
|
||||
- For sync, prefer a local Git clone. Do not use a live network share as the sync path.
|
||||
@@ -179,7 +180,6 @@ For type errors while you edit, run `pnpm check:watch`.
|
||||
|
||||
Some tests need files from outside this repository. Without those files, the tests skip and state the reason:
|
||||
|
||||
- `tests/unit/plugins/plugins.spec.ts` and `tests/unit/tables/formulas.spec.ts` import the compiled Table Formulas package. To run them, run `pnpm build:plugins` first. See [Build examples](plugin-development.md#build-examples).
|
||||
- `tests/unit/release/installerVersion.spec.ts` needs the NSIS compiler that the Tauri CLI downloads on Windows.
|
||||
- The Rust terminal tests start the real shells on the computer.
|
||||
|
||||
@@ -206,7 +206,6 @@ A test states what it needs near its top. The runner skips the test, with the re
|
||||
|
||||
| Line | Requirement |
|
||||
| --- | --- |
|
||||
| `// @requires plugin:table-formulas` | `plugin-packages/table-formulas/`. Run `pnpm build:plugins`. |
|
||||
| `// @requires plugin:terminal` | The compiled Terminal plugin |
|
||||
| `// @requires repo:RuneStone_Git/dist` | A file or folder in a sibling plugin checkout |
|
||||
| `// @requires electron` | The browser engine dependencies. Run `npm ci --prefix browser-runtime`. |
|
||||
|
||||
@@ -74,9 +74,10 @@ Right-click selected text in a cell for note links, external links, workspace se
|
||||
**Extract current selection…** saves the selected Markdown to a new note and replaces the selection with a link to that note.
|
||||
Undo restores the original text. It does not delete the new note.
|
||||
|
||||
## Calculate with Table Formulas
|
||||
## Calculate with table formulas
|
||||
|
||||
These calculations need the optional Table Formulas plugin. See [Install a plugin](../plugins.md#install-a-plugin).
|
||||
RuneStone calculates formulas in Markdown tables.
|
||||
To show formulas as text, turn off **Settings → General → Table formulas**. The setting does not change your files.
|
||||
|
||||
Start a cell with `=` to make a formula. Columns use letters A, B, … AA. Row 1 is the header, so the first data row is row 2.
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
"RuneStone_Local_Autocomplete",
|
||||
"RuneStone_Git",
|
||||
"RuneStone_PDF_Viewer",
|
||||
"RuneStone_Table_Formulas",
|
||||
"RuneStone_CSV_Viewer"
|
||||
],
|
||||
"limits": [
|
||||
|
||||
@@ -115,24 +115,6 @@ In user instructions, do not tell users to load JSON, select a build folder, ren
|
||||
Each example is specific to one plugin. Read the package scripts of a plugin before you build it.
|
||||
For the RuneStone source setup, see [Run from source](development.md#run-from-source).
|
||||
|
||||
### Example: Table Formulas
|
||||
|
||||
Source: [Table Formulas repository](https://git.knottywyvern.com/kwyvern/RuneStone_TableFormulas) and the host script `scripts/buildPlugins.mjs`.
|
||||
|
||||
| Item | Value |
|
||||
| --- | --- |
|
||||
| Prerequisites | Node.js 24, pnpm 10, and the RuneStone source setup. A Table Formulas checkout in `RuneStone_Table_Formulas` beside the RuneStone folder, with `pnpm install --frozen-lockfile` complete. |
|
||||
| Working folder | The RuneStone repository root |
|
||||
| Command | `pnpm build:plugins` |
|
||||
| Output | `<Table Formulas>/releases/runestone.table-formulas-<version>.zip` |
|
||||
|
||||
The `build:plugins` script builds only Table Formulas. It runs the plugin's `scripts/build.mjs`, which compiles without a type check.
|
||||
It copies the compiled files to `plugin-packages/table-formulas/` in RuneStone. Host tests read that folder.
|
||||
Set `RUNESTONE_TABLE_FORMULAS_ROOT` when the Table Formulas checkout is in a different location.
|
||||
|
||||
The plugin also has its own command. In the Table Formulas folder, `pnpm package:plugin` runs the type check, the build, and the RuneStone packager.
|
||||
It finds the packager in `../RuneStone`. Set `RUNESTONE_ROOT` when the RuneStone checkout is in a different location.
|
||||
|
||||
### Example: Terminal
|
||||
|
||||
Source: [Terminal repository](https://git.knottywyvern.com/kwyvern/RuneStone_Terminal), its `package.json`, and its `scripts/build.mjs`.
|
||||
@@ -364,7 +346,6 @@ Only one enabled plugin can own each key. The host removes contributions before
|
||||
| Key | Purpose | Owner |
|
||||
| --- | --- | --- |
|
||||
| `terminal` | Mounts terminal controls in a host element. Returns update, command, and dispose functions. | Terminal plugin |
|
||||
| `tableFormulas` | Evaluates and renders formulas in Markdown tables. | Table Formulas plugin |
|
||||
| `git` | Supplies line blame for the editor. | Git plugin |
|
||||
| `browser` | The built-in browser. | RuneStone |
|
||||
|
||||
|
||||
+2
-5
@@ -142,17 +142,14 @@ The same ID, enable, update, and removal rules apply to local and remote package
|
||||
| `src/lib/plugins/backgrounds.ts` | Background frames |
|
||||
| `src/lib/completion/` | The [completion API](completion.md) |
|
||||
| `scripts/packagePlugin.mjs` | The packager for plugin authors |
|
||||
| `scripts/buildPlugins.mjs` | The [Table Formulas build](plugin-development.md#example-table-formulas) |
|
||||
|
||||
### Run the plugin checks
|
||||
|
||||
Run these commands from the RuneStone repository root.
|
||||
For the general checks, see [Checks](development.md#checks). For the browser setup, see [Browser smoke tests](development.md#browser-smoke-tests).
|
||||
|
||||
Some tests load the compiled feature plugins:
|
||||
|
||||
- `pnpm build:plugins` makes `plugin-packages/table-formulas/`. `tests/unit/plugins/plugins.spec.ts` and the feature smoke tests need it.
|
||||
- The smoke tests read Terminal from `../RuneStone_Terminal/dist/`. To make it without a release ZIP, run `node scripts/build.mjs --no-package` in the Terminal folder. Set `RUNESTONE_TERMINAL_DIST` to use another folder.
|
||||
The feature smoke tests read the compiled Terminal plugin from `../RuneStone_Terminal/dist/`.
|
||||
To make it without a release ZIP, run `node scripts/build.mjs --no-package` in the Terminal folder. Set `RUNESTONE_TERMINAL_DIST` to use another folder.
|
||||
|
||||
Unit tests:
|
||||
|
||||
|
||||
+3
-3
@@ -4,7 +4,7 @@
|
||||
|
||||
This guide explains how to install, enable, update, and remove optional plugins such as Terminal, Git, and PDF Viewer.
|
||||
|
||||
Manage all plugins in **Settings → Plug-ins**. The built-in browser is part of RuneStone and is not a plugin.
|
||||
Manage all plugins in **Settings → Plug-ins**. The built-in browser and table formulas are part of RuneStone and are not plugins.
|
||||
|
||||
Plugins run with the full access of RuneStone, including your files. There is no permission sandbox, and the author field does not prove who published the plugin. Enable only code that you trust.
|
||||
|
||||
@@ -50,7 +50,7 @@ If the dialog contains an update, it shows only **Apply packages**. New plugins
|
||||
4. Choose **Uninstall and delete files**.
|
||||
|
||||
RuneStone stops the plugin in every window, then deletes its installed folder.
|
||||
It keeps your downloaded ZIP, the plugin settings, and your workspace documents. For example, Table Formulas leaves the formula text in your Markdown files.
|
||||
It keeps your downloaded ZIP, the plugin settings, and your workspace documents.
|
||||
If you install the plugin again, it can use the kept settings. You choose again whether to enable it.
|
||||
|
||||
**Cancel** changes nothing. **Disable instead** stops the plugin and keeps it installed.
|
||||
@@ -76,7 +76,6 @@ RuneStone uses the token for this request only and does not save it.
|
||||
| Plugin | Guide |
|
||||
| --- | --- |
|
||||
| Terminal | [Terminal guide](guides/terminal.md) |
|
||||
| Table Formulas | [Calculate with Table Formulas](guides/document-tools.md#calculate-with-table-formulas) |
|
||||
| Git | [Git usage](https://git.knottywyvern.com/kwyvern/RuneStone_Git/src/branch/main/docs/usage.md) |
|
||||
| Project Management | [Project Management guide](https://git.knottywyvern.com/kwyvern/RuneStone_PM/src/branch/main/project-management.md) |
|
||||
| Background Slideshow | [Background Slideshow usage](https://git.knottywyvern.com/kwyvern/RuneStone_BG_Slideshow/src/branch/main/docs/usage.md) |
|
||||
@@ -96,6 +95,7 @@ RuneStone uses the token for this request only and does not save it.
|
||||
| The plugin shows **Removal incomplete** | Choose **Retry cleanup** to finish the removal. If the error names changed files, check that path first. |
|
||||
| A Gitea release has no usable package | Check the release tag. Ask the publisher for a release with one attached plugin ZIP. |
|
||||
| An old Browser plugin shows in the list | Uninstall it. The built-in browser keeps your profiles and bookmarks. |
|
||||
| An old Table Formulas plugin shows in the list | Uninstall it. RuneStone does not run it. Your formulas stay in your files. See [Calculate with table formulas](guides/document-tools.md#calculate-with-table-formulas). |
|
||||
|
||||
To see the installed files of a plugin, choose **Show files** beside it. **Open plugins folder** opens the folder for all plugins.
|
||||
When you report a plugin problem, include the plugin name and version, the RuneStone version, and the error text.
|
||||
|
||||
+1
-1
@@ -175,7 +175,7 @@ Settings apply to all workspaces on this computer and update all open windows.
|
||||
|
||||
| Category | Settings |
|
||||
| --- | --- |
|
||||
| General | Display language, **Show .runestone folder**, and auto-save |
|
||||
| General | Display language, **Table formulas**, **Show .runestone folder**, and auto-save |
|
||||
| Appearance | Color theme, transparency, background image, and custom themes. See [Appearance and custom themes](guides/themes.md). |
|
||||
| Plug-ins | Install, enable, update, and remove plugins. See [Install and manage plugins](plugins.md). |
|
||||
| Browser | Homepage, search engine, profiles, ad blocking, and web data |
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
"tauri": "tauri",
|
||||
"test": "node --experimental-strip-types --test \"tests/unit/**/*.spec.ts\"",
|
||||
"smoke": "node scripts/smoke.mjs",
|
||||
"build:plugins": "node scripts/buildPlugins.mjs",
|
||||
"browser:check": "npm --prefix browser-runtime run check",
|
||||
"browser:test": "npm --prefix browser-runtime test",
|
||||
"browser:test:engine": "npm --prefix browser-runtime run test:browser",
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { mkdir, cp, access, rm } from "node:fs/promises";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { packagePlugin } from "./packagePlugin.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || resolve(root, "..");
|
||||
const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(pluginRepos, "RuneStone_Table_Formulas"));
|
||||
const formulasBuild = resolve(formulasRoot, "scripts/build.mjs");
|
||||
try {
|
||||
await access(formulasBuild);
|
||||
} catch {
|
||||
throw new Error("Clone RuneStone_Table_Formulas beside RuneStone, or set RUNESTONE_PLUGIN_REPOS or RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins.");
|
||||
}
|
||||
execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" });
|
||||
const formulasOutput = resolve(root, "plugin-packages/table-formulas");
|
||||
// Remove the previous build, so deleted plugin files do not stay in the package.
|
||||
await rm(formulasOutput, { recursive: true, force: true });
|
||||
await mkdir(formulasOutput, { recursive: true });
|
||||
await cp(resolve(formulasRoot, "dist/plugin"), formulasOutput, { recursive: true });
|
||||
console.log(await packagePlugin(formulasOutput, resolve(formulasRoot, "releases")));
|
||||
@@ -4,7 +4,7 @@ import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
const pluginRepos = process.env.RUNESTONE_PLUGIN_REPOS || path.resolve(root, '..');
|
||||
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_Table_Formulas', 'RuneStone_CSV_Viewer'];
|
||||
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_CSV_Viewer'];
|
||||
const patterns = {
|
||||
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
|
||||
svelteMenu: /<ContextMenu\b/g,
|
||||
|
||||
+1
-5
@@ -6,7 +6,7 @@
|
||||
// After the parallel run, the runner runs each failed test again, one at a time (--retries, default 1).
|
||||
// A test that passes on a retry counts as "flaky". The summary lists it, but the run does not fail.
|
||||
// A test declares what it needs on a line near the top:
|
||||
// // @requires plugin:terminal plugin:table-formulas repo:RuneStone_Git/dist electron
|
||||
// // @requires plugin:terminal repo:RuneStone_Git/dist electron
|
||||
// The runner skips a test, with the reason, when a requirement is missing.
|
||||
// A test that fails because of a known app defect states it near the top:
|
||||
// // @known-issue <the defect>
|
||||
@@ -68,10 +68,6 @@ function missing(requirement) {
|
||||
const dist = env.RUNESTONE_TERMINAL_DIST || path.join(pluginRepos, "RuneStone_Terminal", "dist");
|
||||
return existsSync(path.join(dist, "main.js")) ? null : `the Terminal plugin is not built at ${dist}`;
|
||||
}
|
||||
if (kind === "plugin") {
|
||||
const entry = path.join(root, "plugin-packages", value, "main.js");
|
||||
return existsSync(entry) ? null : `plugin-packages/${value} is missing; run pnpm build:plugins`;
|
||||
}
|
||||
if (kind === "repo") {
|
||||
const target = path.join(pluginRepos, value);
|
||||
return existsSync(target) ? null : `${target} is missing; set RUNESTONE_PLUGIN_REPOS to the folder of the plugin checkouts`;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { tableFormulasEnabled } from "$lib/formulas";
|
||||
import { isSpellingTarget } from "./spellingMenu";
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
|
||||
@@ -369,7 +369,7 @@
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
void $pluginHost;
|
||||
void $tableFormulasEnabled;
|
||||
editor?.dispatch({ effects: refreshImages.of() });
|
||||
});
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { actionIcon } from "../ui/actionIcons";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
import { documentLinks } from "./documentLinks";
|
||||
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
import { activeTableFormulas } from "../formulas/index.ts";
|
||||
|
||||
const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||
export const refreshImages = StateEffect.define<void>();
|
||||
@@ -103,7 +103,7 @@ class Checkbox extends WidgetType {
|
||||
}
|
||||
|
||||
class Preview extends WidgetType {
|
||||
readonly formulas = pluginHost.get("tableFormulas");
|
||||
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; }
|
||||
|
||||
@@ -15,7 +15,7 @@ import { tableSelectionControls } from "./tableSelectionControls";
|
||||
import { tableDragControls } from "./tableDragControls";
|
||||
import type { TableContextActions } from "./tableCellActions";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
import { activeTableFormulas } from "../formulas/index.ts";
|
||||
import { attachTooltip } from "../ui/tooltip";
|
||||
import { documentLinks } from "./documentLinks";
|
||||
import { tableLinkLabelPosition } from "./tableLinkSource";
|
||||
@@ -43,7 +43,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 formulas = activeTableFormulas();
|
||||
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
|
||||
const table = scroll?.querySelector("table");
|
||||
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
|
||||
@@ -98,7 +98,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
|
||||
if (cell === active) {
|
||||
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : tr(" · Type = to calculate")}`;
|
||||
formulaHint.textContent = result?.error ? formulas.formulaErrors[result.error] : "";
|
||||
formulaHint.textContent = result?.error ? formulas.formulaErrorText(result.error) : "";
|
||||
formulaHint.hidden = !formulaHint.textContent;
|
||||
}
|
||||
}
|
||||
@@ -176,7 +176,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
|
||||
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
|
||||
const formula = originalCell && (/^=(?!=)/.test(originalCell.text.trim()) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
|
||||
const html = cell.innerHTML;
|
||||
formulaStatus.textContent = formulas ? `${formulas.cellAddress(row, column)} · Type = to calculate` : "";
|
||||
formulaStatus.textContent = formulas ? `${formulas.cellAddress(row, column)}${tr(" · Type = to calculate")}` : "";
|
||||
cell.innerHTML = "";
|
||||
cell.classList.add("is-editing");
|
||||
editor = new Editor({
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// The table formula engine. Formulas are plain Markdown cell text.
|
||||
// The engine does not evaluate JavaScript and does not read 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;
|
||||
export type FormulaErrorCode = keyof typeof formulaErrors;
|
||||
type ErrorCode = FormulaErrorCode;
|
||||
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 };
|
||||
}
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Table formulas are a built-in feature. The `tableFormulas` general setting turns them on or off.
|
||||
// When they are off, the editor and the renderer show formulas as their source text.
|
||||
import { get, writable } from "svelte/store";
|
||||
import { onSettingsChange } from "../settings/store.ts";
|
||||
import { DEFAULT_SETTINGS, readSettings } from "../workspace/settings.ts";
|
||||
import { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula } from "./engine.ts";
|
||||
import { formulaErrorText, renderTableFormulas, tableFormulaHtml } from "./render.ts";
|
||||
import { createFormulaTools } from "./tools.ts";
|
||||
|
||||
export { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula, type FormulaErrorCode, type FormulaResult } from "./engine.ts";
|
||||
export { formulaErrorText, renderTableFormulas, tableFormulaHtml } from "./render.ts";
|
||||
export { createFormulaTools } from "./tools.ts";
|
||||
|
||||
export const tableFormulas = { formulaErrors, formulaErrorText, isTableFormula, cellAddress, evaluateTableFormulas, tableFormulaHtml, renderTableFormulas, createFormulaTools };
|
||||
export type TableFormulas = typeof tableFormulas;
|
||||
|
||||
const enabled = writable(DEFAULT_SETTINGS.tableFormulas);
|
||||
/** A store with the current state of the setting. Views subscribe to it to render again after a change. */
|
||||
export const tableFormulasEnabled = { subscribe: enabled.subscribe };
|
||||
|
||||
export function setTableFormulasEnabled(value: boolean) { enabled.set(value); }
|
||||
|
||||
/** The formula functions when the setting is on, otherwise undefined. */
|
||||
export function activeTableFormulas(): TableFormulas | undefined {
|
||||
return get(enabled) ? tableFormulas : undefined;
|
||||
}
|
||||
|
||||
/** Apply the saved setting now and after each change in any window. Returns a function that stops it. */
|
||||
export function syncTableFormulas() {
|
||||
const read = () => {
|
||||
try { setTableFormulasEnabled(readSettings().tableFormulas); }
|
||||
catch { setTableFormulasEnabled(DEFAULT_SETTINGS.tableFormulas); }
|
||||
};
|
||||
read();
|
||||
return onSettingsChange("general", read);
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import MarkdownIt from "markdown-it";
|
||||
import type { Token } from "markdown-it";
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import { evaluateTableFormulas, formulaErrors, type FormulaErrorCode, type FormulaResult } from "./engine.ts";
|
||||
|
||||
const escapeHtml = (text: string) => text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
||||
|
||||
/** The description of an error code in the current language. */
|
||||
export function formulaErrorText(code: FormulaErrorCode): string {
|
||||
return tr(formulaErrors[code]);
|
||||
}
|
||||
|
||||
export function tableFormulaHtml(result: FormulaResult): string {
|
||||
const label = `${result.formula} → ${result.error ? formulaErrorText(result.error) : result.text}`;
|
||||
return `<span class="md-table-formula${result.error ? " is-error" : ""}" title="${escapeHtml(label)}" aria-label="${escapeHtml(label)}">${escapeHtml(result.text)}</span>`;
|
||||
}
|
||||
|
||||
/** Replace the inline content of each formula cell with its result. Each table is calculated separately. */
|
||||
export function renderTableFormulas(tokens: Token[]) {
|
||||
let rows: Token[][] | undefined;
|
||||
for (const token of tokens) {
|
||||
if (token.type === "table_open") rows = [];
|
||||
else if (rows && token.type === "tr_open") rows.push([]);
|
||||
else if (rows && token.type === "inline") rows.at(-1)?.push(token);
|
||||
else if (rows && token.type === "table_close") {
|
||||
const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content)));
|
||||
rows.forEach((row, r) => row.forEach((cell, c) => {
|
||||
const result = results[r][c];
|
||||
if (!result) return;
|
||||
const output = new MarkdownIt.Token("html_inline", "", 0);
|
||||
output.content = tableFormulaHtml(result);
|
||||
cell.children = [output];
|
||||
}));
|
||||
rows = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import { actionIcon } from "../ui/actionIcons.ts";
|
||||
|
||||
/** The formula help, status line, and error hint below a table in Writer. */
|
||||
export function createFormulaTools(finish: () => void, measure: () => void) {
|
||||
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(tr("Formulas")));
|
||||
summary.title = tr("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 = tr("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)", tr("Average two values: 9 and 10 give 9.5.")],
|
||||
["=AVERAGE(B2:C2)", tr("Average every cell in the range B2 through C2.")],
|
||||
["=SUM(B2:B10)", tr("Add the values in a range.")],
|
||||
["=(B2+C2)/2", tr("Add two values and divide by two.")],
|
||||
["=ROUND(B2/3,2)", tr("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 = tr("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 = tr("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", measure);
|
||||
const formulaStatus = document.createElement("span");
|
||||
formulaStatus.className = "table-formula-status";
|
||||
formulaStatus.textContent = tr("Type = in a cell to calculate");
|
||||
const formulaHint = document.createElement("div");
|
||||
formulaHint.className = "table-formula-hint";
|
||||
formulaHint.hidden = true;
|
||||
formulaTools.append(formulaHelp, formulaStatus);
|
||||
return { formulaTools, formulaStatus, formulaHint };
|
||||
}
|
||||
@@ -3474,7 +3474,29 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["Move {count} selected items to the trash?", "Placer les {count} éléments sélectionnés dans la corbeille ?", "選択した{count}項目をごみ箱に移動しますか?", "将所选的 {count} 项移到回收站?"],
|
||||
["Move {count} selected items and all contents of selected folders to the trash?", "Placer les {count} éléments et tout le contenu des dossiers sélectionnés dans la corbeille ?", "選択した{count}項目と選択フォルダー内のすべてをごみ箱に移動しますか?", "将所选的 {count} 项及所选文件夹的全部内容移到回收站?"],
|
||||
["Moved {count} of {total} items to the trash. Restore them from the system trash.", "{count} éléments sur {total} placés dans la corbeille. Restaurez-les depuis la corbeille du système.", "{total}項目中{count}項目をごみ箱に移動しました。システムのごみ箱から復元できます。", "已将 {total} 项中的 {count} 项移到回收站。可从系统回收站恢复。"],
|
||||
["To delete permanently instead, select the items and press Shift+Delete.", "Pour supprimer définitivement, sélectionnez les éléments et appuyez sur Maj+Suppr.", "完全に削除するには、項目を選択して Shift+Delete を押してください。", "要永久删除,请选择这些项目并按 Shift+Delete。"]
|
||||
["To delete permanently instead, select the items and press Shift+Delete.", "Pour supprimer définitivement, sélectionnez les éléments et appuyez sur Maj+Suppr.", "完全に削除するには、項目を選択して Shift+Delete を押してください。", "要永久删除,请选择这些项目并按 Shift+Delete。"],
|
||||
["Formulas", "Formules", "数式", "公式"],
|
||||
["How to calculate with table cells", "Comment calculer avec les cellules d’un tableau", "表のセルで計算する方法", "如何使用表格单元格进行计算"],
|
||||
["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.", "Commencez une cellule par =, puis appuyez sur Entrée ou Tab. Les colonnes sont A, B, C… ; l’en-tête est la ligne 1 et la première ligne de données est la ligne 2.", "セルを=で始め、EnterキーまたはTabキーを押します。列はA、B、C…です。見出しが1行目、最初のデータ行が2行目です。", "以 = 开始单元格,然后按 Enter 或 Tab。列为 A、B、C…;表头为第 1 行,第一行数据为第 2 行。"],
|
||||
["Average two values: 9 and 10 give 9.5.", "Moyenne de deux valeurs : 9 et 10 donnent 9,5.", "2つの値の平均:9と10で9.5になります。", "求两个值的平均值:9 和 10 得到 9.5。"],
|
||||
["Average every cell in the range B2 through C2.", "Moyenne de toutes les cellules de la plage B2 à C2.", "B2からC2までの範囲にあるすべてのセルの平均を求めます。", "求 B2 到 C2 范围内所有单元格的平均值。"],
|
||||
["Add the values in a range.", "Additionner les valeurs d’une plage.", "範囲内の値を合計します。", "将范围内的值相加。"],
|
||||
["Add two values and divide by two.", "Additionner deux valeurs et diviser par deux.", "2つの値を足して2で割ります。", "将两个值相加后除以二。"],
|
||||
["Round to two decimal places.", "Arrondir à deux décimales.", "小数点以下2桁に丸めます。", "四舍五入到两位小数。"],
|
||||
["Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range.", "Fonctions : SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Opérateurs : + − * / ^ et %. Séparez les arguments par des virgules ; utilisez deux-points pour une plage de cellules.", "関数:SUM、AVERAGE、MIN、MAX、COUNT、ABS、ROUND。演算子:+ − * / ^ と %。関数の引数はカンマで区切り、セル範囲にはコロンを使います。", "函数:SUM、AVERAGE、MIN、MAX、COUNT、ABS、ROUND。运算符:+ − * / ^ 和 %。函数参数之间用逗号分隔;单元格范围使用冒号。"],
|
||||
["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.", "Les références gardent leur adresse écrite lors de la copie, de l’insertion, de la suppression, du tri ou du déplacement de cellules. Les expressions au format code restent du texte ; une formule doit commencer par = hors du format code.", "セルのコピー、挿入、削除、並べ替え、移動をしても、参照は書かれたアドレスのままです。コード書式の式はそのままの文字列です。数式はコード書式の外側で=から始めてください。", "复制、插入、删除、排序或移动单元格时,引用保持其书写的地址。代码格式的表达式是纯文本;公式必须在代码格式之外以 = 开头。"],
|
||||
["Invalid formula syntax or function arguments", "Syntaxe de formule ou arguments de fonction non valides", "数式の構文または関数の引数が無効です", "公式语法或函数参数无效"],
|
||||
["Cell reference is outside this table", "La référence de cellule est hors de ce tableau", "セル参照がこの表の範囲外です", "单元格引用超出此表格"],
|
||||
["Expected a number", "Un nombre est attendu", "数値が必要です", "需要数字"],
|
||||
["Unknown function or cell name", "Fonction ou nom de cellule inconnu", "不明な関数またはセル名です", "未知的函数或单元格名称"],
|
||||
["Cannot divide by zero or average an empty range", "Impossible de diviser par zéro ou de faire la moyenne d’une plage vide", "0で割ることや、空の範囲の平均を求めることはできません", "无法除以零或对空范围求平均值"],
|
||||
["Circular cell reference", "Référence de cellule circulaire", "循環するセル参照です", "循环单元格引用"],
|
||||
["Result is not a finite number", "Le résultat n’est pas un nombre fini", "結果が有限の数値ではありません", "结果不是有限数字"],
|
||||
["Formula is too complex", "La formule est trop complexe", "数式が複雑すぎます", "公式过于复杂"],
|
||||
["Tables", "Tableaux", "表", "表格"],
|
||||
["Table formulas", "Formules de tableau", "表の数式", "表格公式"],
|
||||
["Calculate table cells that start with =. When this is off, formulas show as text.", "Calculer les cellules de tableau qui commencent par =. Désactivé, les formules s’affichent comme du texte.", "=で始まる表のセルを計算します。オフにすると、数式は文字列として表示されます。", "计算以 = 开头的表格单元格。关闭后,公式显示为文本。"],
|
||||
["Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.", "Les formules de tableau sont maintenant intégrées. Vous pouvez supprimer cet ancien paquet. Vos formules restent dans vos fichiers. Pour activer ou désactiver les formules, ouvrez Paramètres → Général.", "表の数式は内蔵されました。この古いパッケージは削除できます。数式はファイルに残ります。数式のオン/オフは「設定 → 一般」で切り替えます。", "表格公式现已内置。可以移除此旧包。公式保留在文件中。要打开或关闭公式,请前往“设置 → 常规”。"]
|
||||
];
|
||||
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
|
||||
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { tableFormulasEnabled } from "$lib/formulas";
|
||||
import { tick, type Snippet } from "svelte";
|
||||
import { workspaceReadDataUrl } from "$lib/workspace/api";
|
||||
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
|
||||
@@ -64,7 +64,7 @@
|
||||
}
|
||||
|
||||
$effect(() => {
|
||||
void $pluginHost;
|
||||
void $tableFormulasEnabled;
|
||||
const path = noteRel;
|
||||
if (foldingNote !== path) { collapsedHeadings.clear(); foldingNote = path; }
|
||||
const text = contents;
|
||||
|
||||
@@ -40,7 +40,7 @@
|
||||
type Section = string;
|
||||
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = $derived([
|
||||
{ id: "about", label: $t("Help and about"), icon: "help", keywords: "help about version shortcuts keyboard guide" },
|
||||
{ id: "general", label: $t("General"), icon: "settings", keywords: "auto-save autosave save interval seconds files language français 日本語 简体中文" },
|
||||
{ id: "general", label: $t("General"), icon: "settings", keywords: "auto-save autosave save interval seconds files language français 日本語 简体中文 tables table formulas calculate" },
|
||||
{ id: "appearance", label: $t("Appearance"), icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" },
|
||||
{ id: "plugins", label: $t("Plug-ins"), icon: "puzzle", keywords: "plugins extensions community" },
|
||||
]);
|
||||
@@ -129,6 +129,13 @@
|
||||
<p class="intro">{$t("Choose how RuneStone saves your work.")}</p>
|
||||
<h3>{$t('Language')}</h3>
|
||||
<div class="card"><div class="setting-row language-row"><div><label for="language-picker">{$t('Display language')}</label><p>{$t('Choose the language for RuneStone controls.')}</p></div><button id="language-picker" class="text-button language-picker" aria-haspopup="menu" onclick={languagePicker}><Icon icon="globe" />{LANGUAGES.find(item => item.id === $locale)?.name}<Icon icon="chevron-down" /></button></div></div>
|
||||
<h3>{$t("Tables")}</h3>
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
<div><label for="table-formulas">{$t("Table formulas")}</label><p id="table-formulas-description">{$t("Calculate table cells that start with =. When this is off, formulas show as text.")}</p></div>
|
||||
<input id="table-formulas" class="switch" type="checkbox" role="switch" aria-describedby="table-formulas-description" checked={settings.tableFormulas} onchange={event => apply({ ...settings, tableFormulas: event.currentTarget.checked })} />
|
||||
</div>
|
||||
</div>
|
||||
<h3>{$t("Files")}</h3>
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton from "$lib/ui/IconButton.svelte";
|
||||
import { installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
|
||||
import { builtInPackages, installedPlugins, externalErrors, pluginServiceError, restartPlugins, refreshPlugins, setPluginEnabled } from "./external";
|
||||
import type { Candidate, RemovalPlan, InstalledPlugin } from "./sdk";
|
||||
const desktop = isTauri();
|
||||
const installDateFormat = new Intl.DateTimeFormat(undefined, {
|
||||
@@ -122,7 +122,7 @@
|
||||
<div class="row">
|
||||
<div class="plugin-copy"><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · {$t("Full app access")}</small>
|
||||
<div class="status">
|
||||
<span class="badge">{plugin.manifest.id === "runestone.browser" ? $t("Included with RuneStone") : plugin.removal ? $t("Removal incomplete") : plugin.enabled ? $t("Enabled") : $t("Disabled")}</span>
|
||||
<span class="badge">{builtInPackages.includes(plugin.manifest.id) ? $t("Included with RuneStone") : plugin.removal ? $t("Removal incomplete") : plugin.enabled ? $t("Enabled") : $t("Disabled")}</span>
|
||||
<span class="note">
|
||||
{#if plugin.installedAt != null}
|
||||
{$t("Installed")} <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
|
||||
@@ -133,7 +133,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.manifest.id === "runestone.browser" || plugin.enabled} disabled={busy || plugin.removal || plugin.manifest.id === "runestone.browser"} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
|
||||
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={builtInPackages.includes(plugin.manifest.id) || plugin.enabled} disabled={busy || plugin.removal || builtInPackages.includes(plugin.manifest.id)} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
|
||||
<IconButton icon="folder-open" label={$t("Show files")} disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
|
||||
{#if plugin.removal}
|
||||
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = $t("Plugin file cleanup completed."); })}><Icon icon="refresh" />{$t("Retry cleanup")}</button>
|
||||
@@ -143,6 +143,7 @@
|
||||
</div>
|
||||
</div>
|
||||
{#if plugin.manifest.id === "runestone.browser"}<p class="note">{$t("Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.")}</p>{/if}
|
||||
{#if plugin.manifest.id === "runestone.table-formulas"}<p class="note">{$t("Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.")}</p>{/if}
|
||||
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { Token } from "markdown-it";
|
||||
import type { Dispose } from "./sdk.ts";
|
||||
|
||||
export type TerminalAction = "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories";
|
||||
@@ -12,8 +11,6 @@ export interface TerminalMount {
|
||||
command(action: Exclude<TerminalAction, "toggle">): void | Promise<void>;
|
||||
dispose: Dispose;
|
||||
}
|
||||
export type FormulaErrorCode = "#ERROR!" | "#REF!" | "#VALUE!" | "#NAME?" | "#DIV/0!" | "#CYCLE!" | "#NUM!" | "#LIMIT!";
|
||||
export type FormulaResult = { formula: string; text: string; value?: number; error?: FormulaErrorCode };
|
||||
export interface Contributions {
|
||||
git: { blame(path: string, line: number): Promise<import("../git/contracts.ts").GitLineInfo | null> };
|
||||
browser: {
|
||||
@@ -26,13 +23,4 @@ export interface Contributions {
|
||||
mount(container: HTMLElement, props: TerminalProps): TerminalMount;
|
||||
shortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): TerminalAction | null;
|
||||
};
|
||||
tableFormulas: {
|
||||
formulaErrors: Record<FormulaErrorCode, string>;
|
||||
isTableFormula(text: string): boolean;
|
||||
cellAddress(row: number, column: number): string;
|
||||
evaluateTableFormulas(rows: string[][]): (FormulaResult | null)[][];
|
||||
tableFormulaHtml(result: FormulaResult): string;
|
||||
renderTableFormulas(tokens: Token[]): void;
|
||||
createFormulaTools(finish: () => void, measure: () => void): { formulaTools: HTMLDivElement; formulaStatus: HTMLSpanElement; formulaHint: HTMLDivElement };
|
||||
};
|
||||
}
|
||||
|
||||
@@ -76,6 +76,8 @@ export const pluginNavigation = writable<{ owner: string; id: string; title: str
|
||||
export const pluginEditorActive = writable(false);
|
||||
export const pluginServiceError = writable("");
|
||||
export const restartPlugins = writable<string[]>([]);
|
||||
/** Old packages of features that RuneStone now includes. The host never loads their code. */
|
||||
export const builtInPackages: readonly string[] = ["runestone.browser", "runestone.table-formulas"];
|
||||
const sessions = new Map<string, { hash: string; session: ExternalSession }>();
|
||||
const failures = new Map<string, string>();
|
||||
const errors: Record<string, string> = {};
|
||||
@@ -335,7 +337,7 @@ export function refreshPlugins(): Promise<void> {
|
||||
}
|
||||
for (const row of snapshot.plugins) {
|
||||
const id = row.manifest.id;
|
||||
if (id === "runestone.browser") continue;
|
||||
if (builtInPackages.includes(id)) continue;
|
||||
if (allowedPlugins && !allowedPlugins.includes(id)) continue;
|
||||
if (!row.enabled) { failures.delete(id); continue; }
|
||||
if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row);
|
||||
|
||||
@@ -9,7 +9,7 @@ export class ContributionRegistry {
|
||||
return this.entries.get(key)?.value as Contributions[K] | undefined;
|
||||
}
|
||||
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
|
||||
if (key !== "terminal" && key !== "tableFormulas" && key !== "browser" && key !== "git") throw new Error("Unknown plugin contribution.");
|
||||
if (key !== "terminal" && key !== "browser" && key !== "git") throw new Error("Unknown plugin contribution.");
|
||||
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
|
||||
const entry = { owner, value };
|
||||
this.entries.set(key, entry); this.emit();
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
<script lang="ts">
|
||||
import { syncLocale } from '$lib/i18n';
|
||||
import { syncTableFormulas } from '$lib/formulas';
|
||||
import { onMount } from 'svelte';
|
||||
import { onSettingsChange, readSection, writeSection } from '$lib/settings/store';
|
||||
import { applyAppearance, readAppearance } from './appearance';
|
||||
onMount(() => {
|
||||
const stopLocale = syncLocale();
|
||||
const stopFormulas = syncTableFormulas();
|
||||
const read = () => {
|
||||
try {
|
||||
const stored = readSection('appearance');
|
||||
@@ -19,6 +21,6 @@
|
||||
};
|
||||
read();
|
||||
const stops = [onSettingsChange('appearance', read), onSettingsChange('customThemes', read)];
|
||||
return () => { stopLocale(); stops.forEach(stop => stop()); };
|
||||
return () => { stopLocale(); stopFormulas(); stops.forEach(stop => stop()); };
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import MarkdownIt from "markdown-it";
|
||||
import type { Token } from "markdown-it";
|
||||
import { inlineMathEnd } from "./inlineMath.ts";
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
import { activeTableFormulas } from "../formulas/index.ts";
|
||||
import { hasTableDelimiter } from "../editor/markdownTable.ts";
|
||||
import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts";
|
||||
|
||||
@@ -167,7 +167,7 @@ markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>
|
||||
markdown.renderer.rules.table_close = () => '</table></div>\n';
|
||||
|
||||
markdown.core.ruler.after("inline", "table_formulas", state => {
|
||||
pluginHost.get("tableFormulas")?.renderTableFormulas(state.tokens);
|
||||
activeTableFormulas()?.renderTableFormulas(state.tokens);
|
||||
});
|
||||
|
||||
function documentParts(contents: string) {
|
||||
|
||||
@@ -9,12 +9,15 @@ export interface AppSettings {
|
||||
autosaveEnabled: boolean;
|
||||
autosaveSeconds: number;
|
||||
showInternalFolder: boolean;
|
||||
/** Calculate table cells that start with `=`. When off, formulas show as source text. */
|
||||
tableFormulas: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
|
||||
autosaveEnabled: true,
|
||||
autosaveSeconds: 5,
|
||||
showInternalFolder: false,
|
||||
tableFormulas: true,
|
||||
};
|
||||
|
||||
export function validAutosaveSeconds(value: unknown): value is number {
|
||||
@@ -28,6 +31,7 @@ export function normalizeSettings(input: unknown): AppSettings {
|
||||
autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled,
|
||||
autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds,
|
||||
showInternalFolder: value?.showInternalFolder === true,
|
||||
tableFormulas: typeof value?.tableFormulas === "boolean" ? value.tableFormulas : DEFAULT_SETTINGS.tableFormulas,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -45,5 +49,5 @@ export function saveSettings(settings: AppSettings): Promise<void> {
|
||||
if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") {
|
||||
throw new Error("Choose a whole number from 1 to 300 seconds.");
|
||||
}
|
||||
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true });
|
||||
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true, tableFormulas: settings.tableFormulas !== false });
|
||||
}
|
||||
|
||||
@@ -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,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,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";
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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.');
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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,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,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);
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
@@ -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' },
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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!");
|
||||
});
|
||||
@@ -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, /"<img>"/);
|
||||
assert.match(html, /md-table-formula is-error/);
|
||||
assert.match(html, /Invalid formula syntax or function arguments/);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user