// 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(); if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) { await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click(); } await page.locator(".monaco-editor textarea").waitFor(); } const source = '# Navigation\n\nBefore.\n\n| Name | Value | Formula |\n| --- | --- | --- |\n| Alpha | 12 | =B2*2 |\n| Beta | | tail |\n| Two
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 page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); 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); // 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 page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click(); 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, save, undo/redo, Tab and Escape'); } catch (error) { await page.screenshot({ path: '.audit/table-navigation-failure.png' }); throw error; } finally { await browser.close(); }