Files
RuneStone/scripts/tableNavigation.smoke.mjs
T

412 lines
20 KiB
JavaScript

import { mockFeaturePlugins } from "./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, '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(); }