RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+168
View File
@@ -0,0 +1,168 @@
// Table drag handles: hover and focus grips, previews, row and column moves, undo, cancellation, keyboard moves, and auto-scroll.
import assert from "node:assert/strict";
import path from "node:path";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
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 long = '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n';
await runSmoke("tables/drag", async ({ page }) => {
const output = await outputDir("tables/drag");
await mockTauri(page, {
state: { files: { 'drag.md': source, 'long.md': long } },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: test.state.files, writeEvents: true });
test.files = workspace.files;
return workspace;
},
});
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 chooseView(page, "Source");
await page.locator(".source-editor .cm-content").waitFor();
}
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'));
}
await page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
await quickOpen('drag.md');
await chooseView(page, "Write");
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: path.join(output, '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: path.join(output, '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.
// At 760 pixels the side panes give way. The test opens both again, so the table pane stays narrow.
await page.setViewportSize({ width: 760, height: 700 });
await page.locator('aside.left').waitFor({ state: 'detached' });
await page.keyboard.press('Control+Backslash');
await page.locator('aside.left').waitFor();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.locator('aside.right').waitFor();
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: path.join(output, 'narrow.png') });
// Long tables scroll the document while the pointer stays at its lower edge.
await page.setViewportSize({ width: 1440, height: 700 });
await quickOpen('long.md');
await chooseView(page, "Write");
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);
});
+92
View File
@@ -0,0 +1,92 @@
// Table Enter and Shift+Enter, table clipboard with line breaks, task marker editing, and title Tab, in both themes and a narrow window.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/enterKey", async ({ page }) => {
const output = await outputDir("tables/enterKey");
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n" }, writeEvents: true }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
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);
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
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 shot(`${mode}-table-enter`);
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 shot(`${mode}-table-paste`);
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 shot(`${mode}-checklist-text`);
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 shot(`${mode}-checklist-source`);
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 shot(`${mode}-title-tab`);
await page.setViewportSize({ width: 600, height: 760 });
await reset();
await shot(`${mode}-narrow`);
await page.setViewportSize({ width: 1440, height: 1000 });
}
});
+160
View File
@@ -0,0 +1,160 @@
// Built-in table formulas: live recalculation, raw formula editing, Enter and Tab, undo, cycles, saving, the footer layout, the Read and Split views,
// and the general setting that turns formulas off and on.
import assert from "node:assert/strict";
import path from "node:path";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
const source = '# Table formulas\n\n| Name | Appearance | Charisma | Combined |\n| --- | ---: | ---: | ---: |\n| First | 9 | 10 | =AVERAGE(B2:C2) |\n| Second | 7 | 9 | =SUM(B3+C3)/2 |\n| Total | | | =SUM(D2:D3) |\n\nAfter.\n';
await runSmoke("tables/formulas", async ({ page }) => {
const output = await outputDir("tables/formulas");
await mockTauri(page, {
state: { files: { 'formulas.md': source } },
commands: test => {
const workspace = test.workspace({ root: "C:\\smoke-workspace", files: test.state.files, writeEvents: true });
test.files = workspace.files;
return workspace;
},
});
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(".source-editor .cm-content").waitFor();
}
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');
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
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'));
}
// 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 page.goto(smokeUrl);
await page.getByText('smoke-workspace', { exact: true }).waitFor();
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 shot('cell-hint');
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');
// Enter would start editing D4 below (src/lib/editor/tableControls.ts:283), so leave the table to render both results.
await page.keyboard.press('Control+Enter');
// The table renders again after it loses focus. Wait for that before the check.
for (const [r, c] of [[2, 3], [3, 3]]) await result(r, c).filter({ hasText: /^#CYCLE!$/ }).waitFor();
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, /\\=/);
await cell(3, 1).click();
await checkFooter();
await shot('footer');
await page.setViewportSize({ width: 850, height: 1000 });
await checkFooter();
await shot('footer-narrow');
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 shot('formulas');
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', 'Read beside']) {
await chooseView(page, mode);
const preview = page.locator('.md-page table').first();
await preview.waitFor();
// Enter in the last row added an empty row below Total (src/lib/editor/tableControls.ts:285).
const total = preview.locator('tbody tr').filter({ hasText: 'Total' });
assert.equal(await total.locator('.md-table-formula').last().innerText(), '58', `${mode} view`);
}
// The general setting turns formulas off in all views. The source text shows and the file stays the same.
const file = await page.evaluate(() => window.__TEST__.files.get('formulas.md'));
const general = await page.evaluate(() => window.__TEST__.settings('general') ?? {});
await page.evaluate(value => window.__TEST__.writeSettings('general', value), { ...general, tableFormulas: false });
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
const total = page.locator('.md-page table').first().locator('tbody tr').filter({ hasText: 'Total' });
assert.match(await total.innerText(), /=SUM\(D2:D3\)/);
assert.match(await total.innerText(), /=SUM\(B2:B3\)/);
await shot('formulas-off-split');
await chooseView(page, 'Read beside');
await table.waitFor();
assert.equal(await table.locator('.md-table-formula').count(), 0);
assert.match(await cell(3, 3).innerText(), /=SUM\(D2:D3\)/);
assert.equal(await page.locator('.table-formula-tools').count(), 0, 'Writer shows no formula help');
await shot('formulas-off-writer');
await page.evaluate(value => window.__TEST__.writeSettings('general', value), { ...general, tableFormulas: true });
await result(3, 3).waitFor();
assert.equal(await result(3, 3).innerText(), '58');
await page.locator('.table-formula-tools').first().waitFor();
assert.equal(await page.evaluate(() => window.__TEST__.files.get('formulas.md')), file);
});
+127
View File
@@ -0,0 +1,127 @@
// Links in table cells: clicks keep the caret in place, keyboard entry, inline Edit link, wiki aliases, repeated targets, save, and undo, in both themes and a narrow window.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/linkCaret", async ({ page }) => {
const output = await outputDir("tables/linkCaret");
await mockTauri(page, {
commands: test => {
localStorage.clear();
const workspace = test.workspace({
root: "C:\\tab-menu-workspace",
folders: ["notes"],
files: { "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' },
});
test.files = workspace.files;
test.prompts = [];
return {
...workspace,
spelling_menu_install: () => null,
"plugin:dialog|message": ({ message }) => { test.prompts.push(message); return "Cancel"; },
};
},
});
page.setDefaultTimeout(15000);
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();
});
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(smokeUrl);
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:'B6 · Row 6, column 2', exact:true });
await clickTextAt(cell.locator('a'), 5);
await sourceCell().waitFor();
assert.equal(await cell.locator('.writer-link-target').innerText(), 'docs/roadmap.md', 'Ordinary click reveals the URL');
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 shot(`click-label-${theme}-${width}`);
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 shot(`edit-target-${theme}-${width}`);
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.__TEST__.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
const keyboard = page.getByRole('cell', { name:'B7 · Row 7, column 2', exact:true });
await clickTextAt(keyboard, 7);
assert.equal(await sourceCell().count(), 0, 'Plain cell text remains rendered');
await page.keyboard.press('ArrowRight');
await sourceCell().waitFor();
assert.equal(await keyboard.locator('.writer-link-target').innerText(), 'docs/guide.md');
assert.equal(await caretPrefix(), 'Before [G');
await shot(`keyboard-${theme}-${width}`);
await page.keyboard.press('Escape');
const wiki = page.getByRole('cell', { name:'B8 · Row 8, column 2', exact:true });
await clickTextAt(wiki.locator('a'), 3);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '[[guide\\|Gui');
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:'B9 · Row 9, column 2', exact:true });
await clickTextAt(repeated.locator('a').nth(1), 4);
await sourceCell().waitFor();
assert.equal(await caretPrefix(), '**Prefix** [One](same.md) + [Sec**o');
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.__TEST__.prompts), []);
}
});
@@ -0,0 +1,62 @@
// A click on a link in a table cell that took focus a moment earlier. The ProseMirror focus check runs before selectionchange, and the link source still opens at the clicked character.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/linkClickAfterFocus", async ({ page }) => {
await mockTauri(page, {
commands: test => ({
...test.workspace({
root: "C:\\tab-menu-workspace",
files: { "a.md": "| Name | Value |\n| --- | --- |\n| One | Text |\n| Two | Before [Guide](docs/guide.md) after |\n" },
}),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
await page.getByRole('cell', { name:'B2 · Row 2, column 2', exact:true }).click();
await page.locator('.writer-cell-editor').waitFor();
// Force the order that load causes: the click moves the native selection, the focus check runs, and only then selectionchange reaches ProseMirror.
// The focus check is the 20 ms timer in the focus handler of prosemirror-view. Its source is the only timer source that reads currentSelection.
await page.evaluate(() => {
const setTimeout = window.setTimeout, checks = [];
const hold = event => event.stopImmediatePropagation();
window.setTimeout = (run, delay, ...rest) => {
if (delay !== 20 || !String(run).includes('currentSelection')) return setTimeout(run, delay, ...rest);
checks.push(run);
return 0;
};
document.addEventListener('selectionchange', hold, true);
window.__runFocusCheck = () => {
window.setTimeout = setTimeout;
for (const check of checks) check();
document.removeEventListener('selectionchange', hold, true);
return checks.length;
};
});
await page.keyboard.press('Enter');
const linkCell = page.getByRole('cell', { name:'B3 · Row 3, column 2', exact:true });
await linkCell.locator('.writer-cell-editor').waitFor();
// Let the other timers of the new editor run. A flush after the click reads the native selection and hides the race.
await page.waitForTimeout(100);
const point = await linkCell.locator('a').evaluate(link => {
const range = document.createRange();
range.setStart(link.firstChild, 1); range.collapse(true);
const rect = range.getBoundingClientRect();
return { x: rect.x, y: rect.y + rect.height / 2 };
});
await page.mouse.click(point.x, point.y);
assert.ok(await page.evaluate(() => window.__runFocusCheck()) > 0, 'The focus check ran after the click');
await page.locator('.is-source-editing .writer-cell-editor').waitFor();
assert.equal(await linkCell.locator('.writer-link-target').innerText(), 'docs/guide.md', 'The click opens the link source');
const caretPrefix = await 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();
});
assert.equal(caretPrefix, 'Before [G', 'The caret stays at the clicked label character');
});
+334
View File
@@ -0,0 +1,334 @@
// Table keyboard navigation: arrows, caret positions, entry and exit in all directions, goal columns, line breaks, stable cell sizes, saving, and undo.
import assert from "node:assert/strict";
import { mockTauri, runSmoke, settle, smokeUrl } from "../_harness/index.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;
},
});
// 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<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 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**<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 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(), /<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 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 });
}
});
+153
View File
@@ -0,0 +1,153 @@
// Table cell selection: drag and Shift-click ranges, keyboard ranges, and clearing or deleting cells, rows, columns, and tables, in both themes and a narrow window.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
await runSmoke("tables/selection", async ({ page }) => {
const output = await outputDir("tables/selection");
await mockTauri(page, {
commands: test => ({
...test.workspace({ root: "C:\\smoke-workspace", files: { "notes/welcome.md": "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n" }, writeEvents: true }),
spelling_menu_install: () => null,
}),
});
await page.goto(smokeUrl);
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());
const shot = name => page.screenshot({ path: path.join(output, `${name}.png`) });
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 shot(`selection-${theme}-${width}`);
await page.keyboard.press('Shift+F10');
await shot(`menu-${theme}-${width}`);
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 shot(`empty-columns-selected-${theme}-${width}`);
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 shot(`empty-columns-deleted-${theme}-${width}`);
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.'));
}
});