Move the tests from scripts/ to tests/ by feature

Unit tests go to tests/unit/<area>/, browser smoke tests to
tests/smoke/<area>/, and tests against a running desktop app to
tests/native/. Files named after dates, work passes, or Kanban cards get
feature names, for example editorOctober12 -> editor/footnotes.

scripts/ keeps the build, release, and package tools. Plugin repositories
import scripts/packagePlugin.mjs, and the Terminal smoke test imports
scripts/pluginMocks.mjs, which now re-exports the harness copy.

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
This commit is contained in:
Knotty Wyvern
2026-10-27 19:47:39 -07:00
parent 90d1940c73
commit e433bed28e
154 changed files with 269 additions and 227 deletions
+232
View File
@@ -0,0 +1,232 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("Home");
await page.locator(".monaco-editor textarea").waitFor();
}
const source = '# Drag tables\n\n| Name | Value | Notes |\n| :--- | ---: | :---: |\n| Alpha | 10 | **Bold**<br>second line |\n| Beta | 20 | Two |\n| Gamma | 30 | Three |\n| Delta | 40 | Four |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const rows = () => table.locator('tbody tr td:first-child').allTextContents();
const headers = () => table.locator('th').allTextContents();
async function grip(axis, index) {
const handle = page.locator(`.table-drag-${axis}[data-index="${index}"]`);
await handle.scrollIntoViewIfNeeded();
const rect = await handle.boundingBox();
await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2);
await page.mouse.down();
}
async function target(axis, index, after = false) {
const rect = await (axis === 'row' ? table.locator('tr').nth(index) : table.locator('th').nth(index)).boundingBox();
await page.mouse.move(axis === 'row' ? rect.x + 10 : rect.x + (after ? rect.width - 2 : 2), axis === 'row' ? rect.y + (after ? rect.height - 2 : 2) : rect.y + 10, { steps: 8 });
}
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('drag.md'));
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('drag.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['drag.md'] });
}, source);
await quickOpen('drag.md');
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
assert.equal(await page.locator('.table-drag-row[data-index="0"]').count(), 0);
await page.mouse.move(5, 5);
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
const firstGrip = page.locator('.table-drag-row[data-index="1"]');
await firstGrip.hover();
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '1');
assert.equal(await page.locator('.table-drag-row[data-index="2"]').evaluate(el => getComputedStyle(el).opacity), '0');
await page.mouse.move(5, 5);
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-row[data-index="1"]')).opacity === '0');
await grip('row', 1);
assert.equal(await page.locator('.table-drag-preview').count(), 0);
await target('row', 2, true);
const preview = page.locator('.table-drag-preview');
await preview.waitFor();
assert.match(await preview.innerText(), /Alpha/);
assert.equal(await preview.getAttribute('aria-hidden'), 'true');
assert.equal(await preview.evaluate(el => getComputedStyle(el).pointerEvents), 'none');
const initialPreview = await preview.boundingBox();
await target('row', 4, true);
assert.ok((await preview.boundingBox()).y > initialPreview.y + 20);
assert.equal(await preview.locator('.table-drag-preview-label').innerText(), 'Row 2 → 5');
assert.equal(await table.locator('.is-cell-selected').count(), 3);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: '.audit/table-drag-row.png' });
await page.mouse.up();
assert.equal(await preview.count(), 0);
await page.mouse.move(5, 5);
await page.waitForFunction(() => [...document.querySelectorAll('.table-drag-handle')].every(el => getComputedStyle(el).opacity === '0'));
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
await save();
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| Delta | 40 | Four |\n| Alpha'));
await page.keyboard.press('Control+z');
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await page.keyboard.press('Control+y');
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha']);
await grip('row', 4); await target('row', 1); await page.mouse.up();
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('column', 0); await target('column', 2, true);
assert.deepEqual(await preview.locator('tr').allTextContents(), ['Name', 'Alpha', 'Beta', 'Gamma', 'Delta']);
await page.locator('.table-drop-indicator:visible').waitFor();
await page.screenshot({ path: '.audit/table-drag-column.png' });
await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await save();
await page.waitForFunction(() => window.__TEST__.files.get('drag.md').includes('| ---: | :---: | :--- |'));
await grip('column', 2); await target('column', 0); await page.mouse.up();
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// Cancel, out-of-table drop, and click without a drag must not change source.
await grip('row', 1); await target('row', 4, true); await page.keyboard.press('Escape'); await page.mouse.up();
assert.equal(await preview.count(), 0);
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('row', 1); await page.mouse.move(5, 5, { steps: 5 }); await page.mouse.up();
assert.deepEqual(await rows(), ['Alpha', 'Beta', 'Gamma', 'Delta']);
await grip('column', 0); await page.mouse.up();
assert.equal(await preview.count(), 0);
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// The focused grip offers the same operation to keyboard users.
// Tab into the handle, rather than leaving mouse focus on it.
await page.locator('.table-add-row').focus();
await page.keyboard.press('Tab');
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 1');
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-drag-column[data-index="0"]')).opacity === '1');
await page.keyboard.press('ArrowRight');
assert.deepEqual(await headers(), ['Value', 'Name', 'Notes']);
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Move column 2');
await page.keyboard.press('ArrowLeft');
assert.deepEqual(await headers(), ['Name', 'Value', 'Notes']);
// Editing a cell before dragging must commit its latest contents.
await table.locator('tbody tr').first().locator('td').first().click();
await page.keyboard.press('Control+End'); await page.keyboard.type(' edited');
await grip('row', 1); await target('row', 4, true); await page.mouse.up();
assert.deepEqual(await rows(), ['Beta', 'Gamma', 'Delta', 'Alpha edited']);
await page.keyboard.press('Control+z');
assert.deepEqual(await rows(), ['Alpha edited', 'Beta', 'Gamma', 'Delta']);
// Keep column handles aligned when a narrow table viewport scrolls.
await page.setViewportSize({ width: 760, height: 700 });
await table.locator('th').first().scrollIntoViewIfNeeded();
await grip('column', 0);
const viewport = await page.locator('.writer-table .md-table-scroll').boundingBox();
await page.mouse.move(viewport.x + viewport.width - 2, viewport.y + 15, { steps: 8 });
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft > 0; });
await page.waitForFunction(() => { const el = document.querySelector('.writer-table .md-table-scroll'); return el.scrollLeft + el.clientWidth >= el.scrollWidth - 2; });
await target('column', 2, true); await page.mouse.up();
assert.deepEqual(await headers(), ['Value', 'Notes', 'Name']);
await page.screenshot({ path: '.audit/table-drag-narrow.png' });
// Long tables scroll the document while the pointer stays at its lower edge.
await page.setViewportSize({ width: 1440, height: 700 });
await page.evaluate(() => {
window.__TEST__.files.set('long.md', '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n');
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['long.md'] });
});
await quickOpen('long.md');
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
await table.waitFor();
await grip('row', 1);
const scroller = await page.locator('.live-writer .cm-scroller').boundingBox();
const first = await table.locator('tr').nth(1).boundingBox();
await page.mouse.move(first.x + 20, scroller.y + scroller.height - 5, { steps: 8 });
await page.waitForFunction(() => {
const last = document.querySelector('.live-writer table tbody tr:last-child').getBoundingClientRect();
const viewport = document.querySelector('.live-writer .cm-scroller').getBoundingClientRect();
return last.bottom < viewport.bottom - 20;
});
await target('row', 30, true);
await page.mouse.up();
assert.equal((await rows()).at(-1), 'Item 1');
assert.equal((await rows())[0], 'Item 2');
await page.keyboard.press('Control+z');
assert.equal((await rows())[0], 'Item 1');
await grip('row', 2); await target('row', 3, true);
await page.locator('.table-drag-row[data-index="2"]').dispatchEvent('pointercancel');
await page.mouse.up();
assert.equal((await rows())[1], 'Item 2');
assert.equal(await page.locator('.is-table-dragging').count(), 0);
assert.equal(await preview.count(), 0);
assert.deepEqual(errors, []);
console.log('PASS: hover/focus grips, pointer-following previews and cleanup, row/column drag in both directions, indicators, alignment, undo/redo, cancellation, keyboard movement, active edits, horizontal and vertical auto-scroll.');
} catch (error) {
console.error('Browser errors:', errors);
await page.screenshot({ path: '.audit/table-drag-failure.png' });
throw error;
} finally { await browser.close(); }
+159
View File
@@ -0,0 +1,159 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
try {
await mkdir('output/october15-editor', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const source = '# Example\n\n| Name | Notes |\n| --- | --- |\n| Alpha | First<br>Second |\n| Beta | Last |\n\nAfter.\n\n- [ ] A task\n';
const reset = async () => {
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), source);
await page.locator('.live-writer table').waitFor();
};
const cell = (r, c) => page.locator('.live-writer table tr').nth(r).locator('th,td').nth(c);
for (const mode of ['dark', 'light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
await reset();
await cell(1, 1).click();
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 2);
await page.keyboard.press('Enter');
await page.waitForFunction(() => document.activeElement?.closest('td')?.cellIndex === 1 && document.activeElement.closest('tr').rowIndex === 3);
assert.equal(await page.locator('.live-writer table tr').count(), 4);
await page.keyboard.type('New');
await page.keyboard.press('Shift+Enter');
await page.keyboard.type('Line');
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /New<br>Line/);
await page.screenshot({ path: `output/october15-editor/${mode}-table-enter.png` });
await reset();
await cell(0, 0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name: 'Select cell', exact: true }).click();
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowDown');
const copied = await page.locator('.writer-table').evaluate(node => {
const data = new DataTransfer();
node.dispatchEvent(new ClipboardEvent('copy', { clipboardData: data, bubbles: true, cancelable: true }));
return { html: data.getData('text/html'), text: data.getData('text/plain') };
});
assert.match(copied.html, /<table>/);
assert.match(copied.text, /Name\tNotes/);
await page.evaluate(() => {
const view = window.__CM__;
const anchor = view.state.sliceDoc().indexOf('After.');
view.dispatch({ selection: { anchor } }); view.focus();
});
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, copied) => {
const data = new DataTransfer(); data.setData('text/html', copied.html); data.setData('text/plain', copied.text);
node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
}, copied);
assert.equal(await page.locator('.live-writer table').count(), 2);
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /First<br>Second/);
await page.screenshot({ path: `output/october15-editor/${mode}-table-paste.png` });
await reset();
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('A task') + 3 } }); view.focus();
});
assert.equal(await page.locator('.writer-checkbox').count(), 1);
await page.screenshot({ path: `output/october15-editor/${mode}-checklist-text.png` });
await page.evaluate(() => {
const view = window.__CM__;
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('[ ]') + 1 } }); view.focus();
});
assert.equal(await page.locator('.writer-checkbox').count(), 0);
await page.screenshot({ path: `output/october15-editor/${mode}-checklist-source.png` });
await page.getByRole('button', { name: 'Rename note', exact: true }).click();
await page.getByRole('textbox', { name: 'Note filename', exact: true }).press('Tab');
await page.waitForFunction(() => document.activeElement?.classList.contains('cm-content'));
await page.screenshot({ path: `output/october15-editor/${mode}-title-tab.png` });
await page.setViewportSize({ width: 600, height: 760 });
await reset();
await page.screenshot({ path: `output/october15-editor/${mode}-narrow.png` });
await page.setViewportSize({ width: 1440, height: 1000 });
}
assert.deepEqual(errors, []);
console.log('PASS: Enter advances and creates rows in the same column, Shift+Enter, table clipboard with line breaks, task marker editing, title Tab, both themes and narrow layouts.');
} catch (error) {
await page.screenshot({ path: 'output/october15-editor/failure.png' });
throw error;
} finally { await browser.close(); }
+199
View File
@@ -0,0 +1,199 @@
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer').waitFor();
await page.keyboard.press('Control+e');
await page.locator(".monaco-editor textarea").waitFor();
}
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';
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
const result = (r, c) => cell(r, c).locator('.md-table-formula');
async function save() {
await page.keyboard.press('Control+s');
await page.waitForFunction(() => !document.querySelector('[aria-label^="Save changes"]'));
return page.evaluate(() => window.__TEST__.files.get('formulas.md'));
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('formulas.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
}, source);
await quickOpen('formulas.md');
await page.keyboard.press('Control+e');
await table.waitFor();
assert.equal(await result(1, 3).innerText(), '9.5');
assert.equal(await result(3, 3).innerText(), '17.5');
await cell(1, 3).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.equal(await cell(1, 3).getAttribute('title'), null);
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /D2.*AVERAGE/);
await page.screenshot({ path: '.audit/table-cell-hint.png' });
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
await cell(1, 3).click();
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
await edit.fill('=AVERAGE(B2+C2)');
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 19');
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
await edit.fill('=AVERAGE(B2,C2)');
assert.equal(await page.locator('.table-formula-status').innerText(), 'D2 = 9.5');
assert.equal(await page.locator('.table-formula-hint').isVisible(), false);
await edit.fill('=AVERAGE(B2:C2)');
await page.keyboard.press('Enter');
await cell(1, 1).click();
await edit.fill('5');
assert.equal(await result(1, 3).innerText(), '7.5');
assert.equal(await result(3, 3).innerText(), '15.5');
await page.keyboard.press('Tab');
await cell(1, 3).click();
assert.equal(await edit.innerText(), '=AVERAGE(B2:C2)');
assert.match(await page.locator('.table-formula-status').innerText(), /D2/);
await edit.fill('=B2*C2');
await page.keyboard.press('Enter');
assert.equal(await result(1, 3).innerText(), '50');
assert.equal(await result(3, 3).innerText(), '58');
assert.match(await save(), /\| =B2\*C2 \|/);
await cell(1, 3).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=AVERAGE(B2:C2)');
assert.equal(await result(3, 3).innerText(), '15.5');
await page.keyboard.press('Control+y');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '=B2*C2');
assert.equal(await result(3, 3).innerText(), '58');
await cell(2, 3).click();
await edit.fill('=D3');
await page.keyboard.press('Enter');
assert.equal(await result(2, 3).innerText(), '#CYCLE!');
assert.equal(await result(3, 3).innerText(), '#CYCLE!');
await cell(2, 3).click();
await edit.fill('=AVERAGE(B3:C3)');
await page.keyboard.press('Tab');
await cell(3, 1).click();
await edit.fill('=SUM(B2:B3)');
await page.keyboard.press('Enter');
assert.equal(await result(3, 1).innerText(), '12');
const saved = await save();
assert.match(saved, /=SUM\(B2:B3\)/);
assert.doesNotMatch(saved, /\\=/);
// Footer controls share one normal-flow block aligned to the table at any width.
async function checkFooter() {
const geometry = await page.evaluate(() => {
const rect = selector => document.querySelector(selector).getBoundingClientRect().toJSON();
return { table: rect('.live-writer .md-table-scroll'), footer: rect('.table-footer'), tools: rect('.table-formula-tools'), help: rect('.table-edit-help'), helpHidden: document.querySelector('.table-edit-help').hidden, summary: rect('.table-formula-help summary'), status: rect('.table-formula-status') };
});
assert.ok(Math.abs(geometry.table.x - geometry.footer.x) < 2);
assert.ok(Math.abs(geometry.footer.x - geometry.tools.x) < 2);
if (!geometry.helpHidden) assert.ok(Math.abs(geometry.help.x - geometry.tools.x) < 2);
assert.ok(geometry.footer.y >= geometry.table.bottom);
assert.ok(geometry.footer.y - geometry.table.bottom <= 28, 'Only the add-row control sits between table and footer');
if (!geometry.helpHidden) {
assert.ok(geometry.tools.y >= geometry.help.bottom, 'Help must not overlap the controls');
assert.ok(geometry.help.right <= geometry.footer.right + 1);
}
if (geometry.status.x > geometry.summary.right) assert.ok(Math.abs((geometry.status.y + geometry.status.height / 2) - (geometry.summary.y + geometry.summary.height / 2)) < 2);
}
await cell(3, 1).click();
await checkFooter();
await page.screenshot({ path: '.audit/table-formula-footer.png' });
await page.setViewportSize({ width: 850, height: 1000 });
await checkFooter();
await page.screenshot({ path: '.audit/table-formula-footer-narrow.png' });
await page.locator('.table-formula-help summary').click();
assert.equal(await page.locator('.table-formula-help').getAttribute('open'), '');
await checkFooter();
await page.setViewportSize({ width: 1440, height: 1000 });
await page.screenshot({ path: '.audit/table-formulas.png' });
await page.keyboard.press('Control+e');
await page.keyboard.press('Control+e');
assert.equal(await result(3, 1).innerText(), '12');
assert.equal(await result(3, 3).innerText(), '58');
for (const mode of ['Read', 'Split']) {
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.waitFor();
assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58');
}
assert.deepEqual(errors, []);
console.log('PASS: live recalculation, raw formula editing, Enter/Tab, undo/redo, cycle recovery, Markdown saves, help, remount, Read, and Split');
} finally { await browser.close(); }
+157
View File
@@ -0,0 +1,157 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", '# Links\n\nOutside table.\n\n| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Text |\n| Three | Text |\n| Four | Text |\n| Five | [Roadmp](docs/roadmap.md) |\n| Keyboard | Before [Guide](docs/guide.md) after |\n| Wiki | [[guide\\|Guide]] |\n| Repeated | **Prefix** [One](same.md) + [Sec**ond**](same.md "Title") |\n']]);
window.tabMenuTest = { files, prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/table-link-caret';
await mkdir(output, { recursive: true });
const sourceCell = () => page.locator('.is-source-editing .writer-cell-editor');
async function clickTextAt(locator, offset, button = 'left') {
const point = await locator.evaluate((element, offset) => {
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
let node;
while ((node = walker.nextNode())) {
if (offset > node.textContent.length) { offset -= node.textContent.length; continue; }
const range = document.createRange();
range.setStart(node, offset); range.collapse(true);
const rect = range.getBoundingClientRect();
return { x: rect.x, y: rect.y + rect.height / 2 };
}
throw new Error('No text position');
}, offset);
await page.mouse.click(point.x, point.y, { button });
}
const selected = () => page.evaluate(() => getSelection().toString());
const caretPrefix = () => page.evaluate(() => {
const selection = getSelection(), range = document.createRange();
range.selectNodeContents(document.querySelector('.is-source-editing .writer-cell-editor'));
range.setEnd(selection.anchorNode, selection.anchorOffset);
return range.toString();
});
const documentText = () => page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
return EditorView.findFromDOM(node).state.doc.toString();
});
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme:'default', mode }), theme);
if (width < 1000) {
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 });
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');
assert.equal(await caretPrefix(), '[Roadm', 'The caret stays at the clicked label character');
await page.keyboard.type('a');
assert.equal(await sourceCell().innerText(), '[Roadmap](docs/roadmap.md)');
await page.screenshot({ path:`${output}/click-label-${theme}-${width}.png` });
await page.keyboard.press('Escape');
assert.equal(await cell.locator('a').innerText(), 'Roadmap');
await clickTextAt(cell.locator('a'), 3);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'docs/roadmap.md');
assert.equal(await page.getByRole('dialog').count(), 0);
await page.screenshot({ path:`${output}/edit-target-${theme}-${width}.png` });
await page.keyboard.type('docs/changed.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
await page.locator('.cm-line').filter({ hasText:'Outside table.' }).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/roadmap.md');
await page.keyboard.press('Control+y');
assert.equal(await cell.locator('a').getAttribute('href'), 'docs/changed.md');
await page.keyboard.press('Control+s');
assert.match(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
const keyboard = page.getByRole('cell', { name:'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');
await sourceCell().waitFor();
assert.equal(await keyboard.locator('.writer-link-target').innerText(), 'docs/guide.md');
assert.equal(await caretPrefix(), 'Before [G');
await page.screenshot({ path:`${output}/keyboard-${theme}-${width}.png` });
await page.keyboard.press('Escape');
const wiki = page.getByRole('cell', { name:'Row 8, column 2', exact:true });
await clickTextAt(wiki.locator('a'), 3);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '[[guide\\|Gui');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'guide');
await page.keyboard.type('new-guide');
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 });
await clickTextAt(repeated.locator('a').nth(1), 4);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '**Prefix** [One](same.md) + [Sec**o');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', { name:'Edit link', exact:true }).click();
assert.equal(await selected(), 'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await repeated.locator('a').first().getAttribute('href'), 'same.md');
assert.equal(await repeated.locator('a').nth(1).getAttribute('href'), 'second.md');
assert.match(await documentText(), /\[Sec\*\*ond\*\*\]\(second.md "Title"\)/);
assert.deepEqual(await page.evaluate(() => window.tabMenuTest.prompts), []);
}
assert.deepEqual(errors, []);
console.log('PASS: ordinary link click reveals Markdown, exact spelling caret, keyboard entry, inline Edit link, URL selection, wiki aliases, repeated targets, formatted labels, title preservation, save, undo/redo, both themes, and narrow windows. Native WebView acceptance remains open.');
} catch (error) {
console.error(error);
await page.screenshot({ path:`${output}/failure.png` });
console.log(await page.locator('.writer-cell-editor').allTextContents());
console.log({errors, active:await page.evaluate(() => document.activeElement?.outerHTML.slice(0,300))});
throw error;
} finally { await browser.close(); }
+411
View File
@@ -0,0 +1,411 @@
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
await mockFeaturePlugins(page);
async function quickOpen(name) {
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
await page.locator('.live-writer .cm-content').waitFor();
}
const source = '# Navigation\n\nBefore.\n\n| Name | Value | Formula |\n| --- | --- | --- |\n| Alpha | 12 | =B2*2 |\n| Beta | | tail |\n| Two<br>lines | short | end |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
const edit = page.locator('.writer-cell-editor');
async function expectCell(r, c) {
await page.waitForFunction(({ r, c }) => {
const active = document.activeElement;
const cell = active?.closest('th, td');
return active?.matches('.writer-cell-editor') && cell?.cellIndex === c && cell.parentElement.rowIndex === r;
}, { r, c });
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function at(r, c, edge = 'End') {
await cell(r, c).click();
// ProseMirror guards native selections at the start for 200ms after focus.
await page.waitForTimeout(220);
await page.keyboard.press(`Control+${edge}`);
await expectCell(r, c);
}
async function arrow(key, r, c) {
await page.keyboard.press(key);
await expectCell(r, c);
}
async function expectProse(after) {
await page.waitForFunction(after => {
const content = document.querySelector('.live-writer .cm-content');
const table = content?.querySelector('table');
const caret = document.getSelection()?.focusNode;
return content === document.activeElement && !content.querySelector('.writer-cell-editor') && table && caret &&
(table.compareDocumentPosition(caret) & (after ? Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_PRECEDING));
}, after);
}
async function caret() {
return edit.evaluate(el => {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(el);
range.setEnd(selection.focusNode, selection.focusOffset);
return { offset: range.toString().length, selected: selection.toString() };
});
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.evaluate(text => {
window.__TEST__.files.set('navigation.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['navigation.md'] });
}, source);
await quickOpen('navigation.md');
await table.waitFor();
// Reproduce the reported right-arrow escape, including formula destinations.
await at(1, 0);
await arrow('ArrowRight', 1, 1);
assert.equal((await caret()).offset, 0);
await arrow('ArrowRight', 1, 1);
assert.equal((await caret()).offset, 1);
await arrow('ArrowRight', 1, 1);
await arrow('ArrowRight', 1, 2);
assert.equal(await edit.innerText(), '=B2*2');
assert.equal((await caret()).offset, 0);
await arrow('ArrowLeft', 1, 1);
assert.equal((await caret()).offset, 2);
await arrow('ArrowLeft', 1, 1);
assert.equal((await caret()).offset, 1);
// Repeated native arrows can arrive before selectionchange is delivered.
await at(1, 1, 'Home');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await page.keyboard.press('ArrowRight');
await expectCell(1, 2);
assert.equal((await caret()).offset, 0);
// Row wrapping, empty cells, and header/body transitions.
await at(1, 2);
await arrow('ArrowRight', 2, 0);
await arrow('ArrowLeft', 1, 2);
await at(2, 0);
await arrow('ArrowRight', 2, 1);
await arrow('ArrowRight', 2, 2);
await arrow('ArrowLeft', 2, 1);
await arrow('ArrowUp', 1, 1);
await arrow('ArrowUp', 0, 1);
await arrow('ArrowDown', 1, 1);
await arrow('ArrowDown', 2, 1);
// Exit in all four directions, without adding rows or changing existing prose.
await at(0, 0, 'Home');
await page.keyboard.press('ArrowLeft');
await expectProse(false);
await at(0, 1, 'Home');
await page.keyboard.press('ArrowUp');
await expectProse(false);
await at(3, 2);
await page.keyboard.press('ArrowRight');
await expectProse(true);
await at(3, 1);
await page.keyboard.press('ArrowDown');
await expectProse(true);
assert.equal(await table.locator('tr').count(), 4);
await page.keyboard.press('Control+s');
assert.equal(await page.evaluate(() => window.__TEST__.files.get('navigation.md')), source);
// Reverse each exit using only the keyboard. Horizontal entry starts at the
// first/last cell; vertical entry uses the nearest column of the edge row.
await at(0, 0, 'Home');
await page.keyboard.press('ArrowLeft');
await expectProse(false);
await arrow('ArrowRight', 0, 0);
assert.equal((await caret()).offset, 0);
await at(0, 1, 'Home');
await page.keyboard.press('ArrowUp');
await expectProse(false);
await arrow('ArrowDown', 0, 0);
await at(3, 2);
await page.keyboard.press('ArrowRight');
await expectProse(true);
await page.keyboard.press('ArrowLeft');
await arrow('ArrowLeft', 3, 2);
assert.equal((await caret()).offset, 3);
await at(3, 1);
await page.keyboard.press('ArrowDown');
await expectProse(true);
await page.keyboard.press('ArrowUp');
await arrow('ArrowUp', 3, 0);
// Preserve the vertical goal column when crossing an empty prose line.
for (const after of [false, true]) {
await page.evaluate(async after => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(document.querySelector('.live-writer .cm-content'));
const EditorSelection = view.state.selection.constructor;
const table = view.dom.querySelector('table');
const preview = table.closest('.writer-preview');
const from = view.posAtDOM(preview);
const end = view.state.doc.toString().indexOf('\n\nAfter.');
const x = table.rows[0].cells[1].getBoundingClientRect().left + 20;
const goal = x - view.contentDOM.getBoundingClientRect().left;
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(after ? end + 1 : from - 1, 0, undefined, goal)]) });
view.focus();
}, after);
await arrow(after ? 'ArrowUp' : 'ArrowDown', after ? 3 : 0, 1);
}
// Ordinary prose cursor movement and extending a selection must stay in the
// outer editor, even when the selection crosses the whole table.
await page.locator('.cm-line').filter({ hasText: 'Before.' }).click();
await page.keyboard.press('Home');
await page.keyboard.press('ArrowRight');
await expectProse(false);
await at(0, 0, 'Home');
await page.keyboard.press('ArrowLeft');
await page.keyboard.press('Shift+ArrowDown');
assert.equal(await edit.count(), 0);
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
// Text selection and word navigation remain within the current editor.
await at(1, 0);
await arrow('Shift+ArrowLeft', 1, 0);
assert.equal((await caret()).selected, 'a');
await arrow('ArrowRight', 1, 0);
assert.equal((await caret()).selected, '');
await arrow('Control+ArrowLeft', 1, 0);
assert.equal((await caret()).offset, 0);
// Up/down traverse visual lines before crossing to another row.
await at(3, 0, 'Home');
await arrow('ArrowDown', 3, 0);
assert.ok((await caret()).offset > 0);
await arrow('ArrowUp', 3, 0);
await arrow('ArrowUp', 2, 0);
await at(2, 0);
await arrow('ArrowDown', 3, 0);
assert.ok((await caret()).offset <= 3, 'Down enters the first line');
// A wrapped cell also retains ordinary vertical caret movement.
await at(3, 1);
await edit.fill('A long sentence that wraps onto multiple visual lines in a narrow table cell.');
await page.keyboard.press('Control+Home');
await arrow('ArrowDown', 3, 1);
assert.ok((await caret()).offset > 0 && (await caret()).offset < (await edit.innerText()).length, 'Down moves into the next visual line');
await arrow('ArrowUp', 3, 1);
assert.equal((await caret()).offset, 0);
await page.keyboard.press('Control+End');
await page.keyboard.press('ArrowDown');
await expectProse(true);
// Edits commit when navigating; formulas update and undo restores the source.
await at(1, 1);
await edit.fill('15');
await arrow('ArrowRight', 1, 2);
await arrow('ArrowDown', 2, 2);
assert.equal(await cell(1, 2).locator('.md-table-formula').innerText(), '30');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => window.__TEST__.files.get('navigation.md').includes('| Alpha | 15 | =B2*2 |'));
await at(1, 1);
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '12');
await page.keyboard.press('Control+y');
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '15');
await page.keyboard.press('Tab');
await expectCell(1, 2);
await page.keyboard.press('Shift+Tab');
await expectCell(1, 1);
await page.keyboard.press('Escape');
assert.equal(await edit.count(), 0);
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
// Focusing empty and filled cells must not resize rows or columns.
const stableSource = '# Stable table\n\n| Column 2 | Column 1 | | |\n| --- | --- | --- | --- |\n| 2cm | Value | | |\n| text | 123 | | |\n| | | | |\n| LongUnbrokenCellValue | **Bold**<br>Two lines | A longer sentence wraps in a narrow table. | `code` |\n\nParagraph one.\nParagraph two.\n';
const dimensions = () => table.evaluate(el => [...el.rows].map(row => [...row.cells].map(cell => {
const rect = cell.getBoundingClientRect();
return { width: rect.width, height: rect.height };
})));
async function stableDimensions(expected, label) {
const actual = await dimensions();
for (let r = 0; r < expected.length; r++) for (let c = 0; c < expected[r].length; c++) {
for (const axis of ['width', 'height']) assert.ok(Math.abs(expected[r][c][axis] - actual[r][c][axis]) < 1,
`${label}: row ${r}, column ${c} ${axis} changed from ${expected[r][c][axis]} to ${actual[r][c][axis]}`);
}
}
for (const theme of ['dark', 'light']) for (const width of [1440, 800]) {
await page.setViewportSize({ width, height: 1000 });
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
const name = `stable-${theme}-${width}.md`;
await page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
}, { name, text: stableSource });
await quickOpen(name);
await table.waitFor();
const initial = await dimensions();
for (const [r, c] of [[1, 3], [2, 3], [3, 3], [0, 0], [1, 0], [1, 1], [4, 0], [4, 1], [4, 2], [4, 3], [2, 1]]) {
await at(r, c);
await stableDimensions(initial, `${theme} ${width} focus ${r},${c}`);
}
await arrow('Tab', 2, 2);
await stableDimensions(initial, `${theme} ${width} Tab`);
await arrow('ArrowDown', 3, 2);
await stableDimensions(initial, `${theme} ${width} ArrowDown`);
await page.keyboard.press('Escape');
await stableDimensions(initial, `${theme} ${width} blur`);
// Delete the blank line through the prose editor, then save and undo/redo.
await page.locator('.cm-line').filter({ hasText: 'Paragraph one.' }).click();
await page.keyboard.press('Home');
await page.keyboard.press('Backspace');
await page.waitForFunction(() => document.querySelectorAll('.live-writer table tr').length === 5 &&
[...document.querySelectorAll('.cm-line')].some(line => line.textContent === 'Paragraph one.'));
await page.keyboard.press('Control+s');
const joined = stableSource.replace('\n\nParagraph one.', '\nParagraph one.');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
await page.keyboard.press('Control+z');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, source }) => window.__TEST__.files.get(name) === source, { name, source: stableSource });
await page.keyboard.press('Control+y');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
assert.equal(await table.locator('tr').count(), 5);
await at(1, 0);
await edit.fill('updated');
await page.keyboard.press('Escape');
await page.keyboard.press('Control+s');
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined.replace('| 2cm |', '| updated |'), { name, joined });
}
await page.setViewportSize({ width: 1440, height: 1000 });
// A line break in a tall table keeps the caret and viewport in the active cell.
const tallSource = '# Tall table\n\nBefore.\n\n| Name | Value |\n| --- | --- |\n' +
Array.from({ length: 45 }, (_, i) => `| Row ${i + 1} | |`).join('\n') + '\n\nAfter.\n';
await page.evaluate(text => {
window.__TEST__.files.set('line-breaks.md', text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['line-breaks.md'] });
}, tallSource);
await quickOpen('line-breaks.md');
await table.waitFor();
for (const [r, c, key] of [[1, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [21, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [20, 1, 'Shift+Enter'], [0, 0, 'Shift+Enter']]) {
await at(r, c);
const before = await page.locator('.live-writer .cm-scroller').evaluate(el => el.scrollTop);
await page.keyboard.press(key);
await expectCell(r, c);
const after = await page.locator('.live-writer .cm-scroller').evaluate(el => el.scrollTop);
assert.ok(Math.abs(after - before) < 50, `${key} in row ${r}: scroll moved from ${before} to ${after}`);
await page.keyboard.type('Next line');
await expectCell(r, c);
assert.match(await edit.innerHTML(), /<br>Next line/);
}
await page.keyboard.press('Escape');
await page.keyboard.press('Control+s');
await page.waitForFunction(() => {
const source = window.__TEST__.files.get('line-breaks.md');
return source.includes('| Name<br>Next line | Value |') &&
source.includes('| Row 1<br>Next line | |') &&
source.includes('| Row 21<br>Next line | |') &&
/\| Row 20<br>Next line<br>Next line \| <br>Next line\s*\|/.test(source);
});
// A table at the document boundary still offers somewhere to type outside it.
const loneTable = '| Name |\n| --- |\n| Value |';
for (const [key, after] of [['ArrowLeft', false], ['ArrowUp', false], ['ArrowRight', true], ['ArrowDown', true]]) {
const name = `${key}.md`;
await page.evaluate(({ name, text }) => {
window.__TEST__.files.set(name, text);
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
}, { name, text: loneTable });
await quickOpen(name);
await table.waitFor();
await at(after ? 1 : 0, 0, after ? 'End' : 'Home');
await page.keyboard.press(key);
await expectProse(after);
const reverse = { ArrowLeft: 'ArrowRight', ArrowUp: 'ArrowDown', ArrowRight: 'ArrowLeft', ArrowDown: 'ArrowUp' }[key];
// Exiting added two newlines, so first cross the outer empty line.
await page.keyboard.press(reverse);
await arrow(reverse, after ? 1 : 0, 0);
await page.keyboard.press(`Control+${after ? 'End' : 'Home'}`);
await page.keyboard.press(key);
await expectProse(after);
await page.keyboard.type('Outside.');
await page.keyboard.press('Control+s');
const expected = after ? `${loneTable}\n\nOutside.` : `\nOutside.\n${loneTable}`;
await page.waitForFunction(({ name, expected }) => window.__TEST__.files.get(name) === expected, { name, expected });
}
assert.deepEqual(errors, []);
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, line breaks and scrolling in tall tables, save, undo/redo, Tab and Escape, stable cell dimensions and table/prose boundaries in both themes at wide/narrow widths');
} catch (error) {
await page.screenshot({ path: '.audit/table-navigation-failure.png' });
throw error;
} finally { await browser.close(); }
+222
View File
@@ -0,0 +1,222 @@
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(10000);
const errors = [];
await mkdir(".audit", { recursive: true });
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
page.on("pageerror", error => errors.push(error.message));
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\smoke-workspace";
const files = new Map([
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
["notes/second.md", "# Second note\n"],
["src/hello.py", "print('hello')\n"],
]);
const callbacks = new Map();
const listeners = new Map();
let sequence = 0;
const calls = [];
const emit = (event, payload) => {
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
};
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
calls.push({ command, args });
if (command === "plugin:event|listen") {
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
}
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_write") {
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
}
if (command === "workspace_list") {
const prefix = args.rel ? args.rel + "/" : "";
const entries = new Map();
for (const path of files.keys()) {
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
}
return [...entries.values()];
}
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
if (command === "workspace_search") return [];
if (command === "spelling_menu_install") return;
if (command === "pty_open") {
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
emit("pty-data", { id: args.id, data: data.slice(8) });
await new Promise(resolve => setTimeout(resolve, 50));
return;
}
if (command.startsWith("pty_")) return;
if (command === "plugin:dialog|message") return "Cancel";
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
window.__TEST__ = { files, calls, emit, root };
});
try {
await mkdir('output/todo-table', { recursive: true });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await page.keyboard.press('Control+p');
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
await page.evaluate(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
});
const source = '# Table selection\n\n| Name | Value | Notes |\n| --- | :---: | ---: |\n| Alpha | 10 | First |\n| Beta | 20 | Second |\n| Gamma | 30 | Third |\n\nAfter.\n';
const table = page.locator('.live-writer table');
const cell = (r,c) => table.locator('tr').nth(r).locator('th,td').nth(c);
const selected = table.locator('.is-cell-selected');
async function reset() {
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), source);
await table.waitFor();
}
const contents = () => page.evaluate(() => window.__CM__.state.sliceDoc());
async function drag(r,c,r2,c2) {
const start = await cell(r,c).boundingBox(), end = await cell(r2,c2).boundingBox();
await page.mouse.move(start.x+start.width/2,start.y+start.height/2);
await page.mouse.down();
await page.mouse.move(end.x+end.width/2,end.y+end.height/2,{steps:8});
await page.mouse.up();
}
await reset();
await drag(1,0,2,1);
assert.equal(await selected.count(),4);
assert.deepEqual(await selected.evaluateAll(cells => cells.map(c => c.getAttribute('data-selection-edges'))),['top left','top right','bottom left','bottom right']);
await page.keyboard.press('Delete');
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
assert.equal(await selected.count(),1);
await page.keyboard.press('Control+z');
await page.waitForFunction(source => window.__CM__.state.sliceDoc() === source,source);
await drag(2,1,1,0);
await page.keyboard.press('Backspace');
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
await reset();
await drag(1,0,2,1);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Clear cells',exact:true}).click();
assert.equal(await contents(),source.replace('Alpha','').replace('10','').replace('Beta','').replace('20',''));
assert.equal(await selected.count(),4);
await reset();
await cell(1,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
assert.equal(await selected.count(),1);
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),4);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
await reset();
await cell(1,0).click();
await cell(2,2).click({modifiers:['Shift']});
assert.equal(await selected.count(),6);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.locator('tr').count(),2);
assert.ok((await contents()).includes('Gamma'));
await reset();
await drag(0,1,3,1);
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.locator('th').count(),2);
assert.ok(!(await contents()).includes('Value'));
const emptyColumns = '# Empty columns\n\n| Column 2 | Column 1 | | | | |\n| --- | --- | --- | --- | --- | --- |\n| 2cm | Value | | | | |\n| text | 123 | | | | |\n| | | | | | |\n| | | | | | |\n\nAfter.\n';
for (const theme of ['light','dark']) for (const width of [1440,760]) {
await page.setViewportSize({width,height:900});
await page.evaluate(async theme => { const {applyAppearance} = await import('/src/lib/theme/appearance.ts'); applyAppearance({theme:'default',mode:theme}); },theme);
await reset();
await cell(0,1).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
await page.keyboard.press('Shift+ArrowRight');
for (let row = 0; row < 3; row++) await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),8);
assert.ok(await selected.evaluateAll(cells => cells.every(c => getComputedStyle(c).borderRadius === '0px')));
await page.screenshot({path:`output/todo-table/selection-${theme}-${width}.png`});
await page.keyboard.press('Shift+F10');
await page.screenshot({path:`output/todo-table/menu-${theme}-${width}.png`});
await page.keyboard.press('Escape');
assert.equal(await page.locator('.writer-table').evaluate(el => document.activeElement === el),true);
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), emptyColumns);
await table.waitFor();
await cell(0,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
for (let col = 0; col < 3; col++) await page.keyboard.press('ArrowRight');
for (let col = 0; col < 2; col++) await page.keyboard.press('Shift+ArrowRight');
for (let row = 0; row < 4; row++) await page.keyboard.press('Shift+ArrowDown');
assert.equal(await selected.count(),15);
await page.screenshot({path:`output/todo-table/empty-columns-selected-${theme}-${width}.png`});
await page.keyboard.press('Delete');
assert.equal(await table.locator('th').count(),3);
assert.equal(await table.locator('tr').count(),5);
assert.equal(await selected.count(),1);
assert.ok((await contents()).includes('| 2cm | Value | |'));
await page.screenshot({path:`output/todo-table/empty-columns-deleted-${theme}-${width}.png`});
await page.keyboard.press('Control+z');
await page.waitForFunction(source => window.__CM__.state.sliceDoc() === source,emptyColumns);
await cell(0,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
for (let col = 0; col < 3; col++) await page.keyboard.press('ArrowRight');
for (let col = 0; col < 2; col++) await page.keyboard.press('Shift+ArrowRight');
for (let row = 0; row < 4; row++) await page.keyboard.press('Shift+ArrowDown');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.locator('th').count(),3);
await reset();
await cell(2,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowDown');
await page.keyboard.press('Backspace');
assert.equal(await table.locator('tr').count(),2);
assert.ok((await contents()).includes('Alpha'));
assert.ok(!(await contents()).includes('Beta'));
await reset();
await cell(0,0).click();
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Shift+ArrowRight');
await page.keyboard.press('Delete');
assert.equal(await table.locator('th').first().innerText(),'Alpha');
await page.keyboard.press('Control+a');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
assert.equal(await table.count(),0);
assert.ok((await contents()).includes('After.'));
}
assert.deepEqual(errors,[]);
console.log('PASS: drag and Shift-click ranges, keyboard range entry and extension, Delete/Backspace remove cells, explicit clear, undo, partial/row/column/all delete, outer edges, light/dark narrow screenshots.');
} catch(error) {
await page.screenshot({path:'output/todo-table/failure.png'});
console.error(errors);
throw error;
} finally { await browser.close(); }