// Table keyboard navigation: arrows, caret positions, entry and exit in all directions, goal columns, line breaks, stable cell sizes, saving, and undo. // @requires plugin:terminal import assert from "node:assert/strict"; import { mockTauri, runSmoke, settle, smokeUrl } from "../_harness/index.mjs"; import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs"; await runSmoke("tables/navigation", async ({ page }) => { await mockTauri(page, { commands: test => { const workspace = test.workspace({ root: "C:\\smoke-workspace", writeEvents: true }); test.files = workspace.files; return workspace; }, }); await mockFeaturePlugins(page); // Add a file after the workspace opens, as an external change would. const addFile = (name, text) => page.evaluate(({ name, text }) => { window.__TEST__.files.set(name, text); window.__TEST__.emit('workspace-event', { root: 'C:\\smoke-workspace', kind: 'create', paths: [name] }); }, { name, text }); 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
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 settle(page); } 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() }; }); } await page.goto(smokeUrl); await page.getByText('smoke-workspace', { exact: true }).waitFor(); await addFile('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**
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 addFile(name, 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 addFile('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(), /
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
Next line | Value |') && source.includes('| Row 1
Next line | |') && source.includes('| Row 21
Next line | |') && /\| Row 20
Next line
Next line \|
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 addFile(name, 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 }); } });