Move the tests from scripts/ to tests/ by feature

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

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

The unit tests get their own type check (tests/tsconfig.json) with Node
types. pnpm check runs it after the app check. Add @types/node and fix
the three test mocks that it reported.
This commit is contained in:
Knotty Wyvern
2026-10-27 19:47:39 -07:00
parent 90d1940c73
commit e433bed28e
154 changed files with 269 additions and 227 deletions
+90
View File
@@ -0,0 +1,90 @@
import { createRequire } from "node:module";
import { mkdir, writeFile } from "node:fs/promises";
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: 720, height: 640 } });
const errors = [];
page.on("pageerror", error => errors.push(error.message));
const output = ".audit/backlinks";
await mkdir(output, { recursive: true });
await page.route("**/__backlinks__", route => route.fulfill({ contentType: "text/html", body: `<!doctype html><html><head><meta charset="UTF-8"><title>Backlinks check</title></head><body>
<aside id="fixture" style="width:320px;height:500px;display:flex;flex-direction:column;background:var(--rs-bg-elevated);margin:24px"></aside>
<script type="module">
import '/src/app.css';
import {mount,unmount} from '/node_modules/.vite/deps/svelte.js';
import Backlinks from '/src/lib/layout/Backlinks.svelte';
import {applyAppearance} from '/src/lib/theme/appearance.ts';
let component;
window.renderBacklinks = async ({mode='dark',width=320,entries=[],busy=false,error=null}={}) => {
if(component) await unmount(component);
applyAppearance({theme:'default',mode});
document.querySelector('#fixture').style.width=width+'px';
component=mount(Backlinks,{target:document.querySelector('#fixture'),props:{entries,busy,error,onOpen:entry=>window.openedBacklink=entry,onRebuild:()=>window.rebuildCount=(window.rebuildCount||0)+1}});
};
await window.renderBacklinks();
window.backlinksReady=true;
</script></body></html>` }));
const entries = Array.from({ length: 28 }, (_, index) => ({
sourcePath: `research/long-folder-name/project-${index + 1}/source-note-with-a-long-readable-title.md`,
line: index + 3, from: index * 100, to: index * 100 + 10,
text: "This source note links to [[Target|the selected note]]. Its visible excerpt can wrap within the panel.",
kind: "wiki", target: "Target",
}));
const measurements = [];
try {
await page.goto(`${process.env.SMOKE_URL || "http://127.0.0.1:1420"}/__backlinks__`);
await page.waitForFunction(() => window.backlinksReady);
const panel = page.getByRole("region", { name: "Backlinks", exact: true });
await panel.getByText("No other notes link to this file.").waitFor();
await page.screenshot({ path: `${output}/empty-dark.png` });
for (const mode of ["light", "dark"]) {
for (const width of [320, 180]) {
await page.evaluate(args => window.renderBacklinks(args), { mode, width, entries });
const toggle = panel.getByRole("button", { name: "Backlinks 28", exact: true });
await toggle.focus();
await page.keyboard.press("Enter");
assert.equal(await toggle.getAttribute("aria-expanded"), "false");
assert.equal(await panel.locator(".source").first().isVisible(), false);
await page.keyboard.press("Space");
assert.equal(await toggle.getAttribute("aria-expanded"), "true");
await page.keyboard.press("Tab");
await page.keyboard.press("Enter");
assert.ok(await page.evaluate(() => window.rebuildCount > 0));
await page.keyboard.press("Tab");
await page.keyboard.press("Enter");
assert.equal(await page.evaluate(() => window.openedBacklink.sourcePath), entries[0].sourcePath);
const metrics = await panel.evaluate(node => {
const source = node.querySelector(".source"), title = node.querySelector(".source-title"), content = node.querySelector(".content");
const style = getComputedStyle(source);
const color = value => value.match(/[\d.]+/g).slice(0, 3).map(Number);
const luminance = rgb => rgb.map(value => value / 255).map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4).reduce((sum, value, index) => sum + value * [.2126,.7152,.0722][index], 0);
const contrast = (a,b) => { const l1=luminance(color(a)),l2=luminance(color(b));return (Math.max(l1,l2)+.05)/(Math.min(l1,l2)+.05); };
const background = getComputedStyle(document.querySelector("#fixture")).backgroundColor;
return { text: style.color, accent: getComputedStyle(title).color, background,
textContrast: contrast(style.color,background), linkContrast:contrast(getComputedStyle(title).color,background),
width:node.clientWidth,scrollWidth:node.scrollWidth,scrollable:content.scrollHeight>content.clientHeight,
focusStyle:style.outlineStyle,focusColor:style.outlineColor,opacity:style.opacity };
});
assert.ok(metrics.textContrast >= 4.5, `Text contrast: ${mode} ${width}`);
assert.ok(metrics.linkContrast >= 4.5, `Link contrast: ${mode} ${width}`);
assert.ok(metrics.scrollWidth <= metrics.width, "The panel must not scroll horizontally");
assert.ok(metrics.scrollable, "Long lists must scroll inside the panel");
assert.equal(metrics.focusStyle, "solid");
assert.equal(metrics.opacity, "1");
measurements.push({ mode, width, ...metrics });
await page.screenshot({ path: `${output}/${mode}-${width}-focus.png` });
}
}
await page.evaluate(() => window.renderBacklinks({ busy:true, error:"Could not read one note. Rebuild the index to try again." }));
assert.equal(await panel.getByRole("button", { name:"Rebuild note index", exact:true }).isDisabled(), true);
await panel.getByText("Reading workspace links…").waitFor();
await page.screenshot({ path:`${output}/busy-error-dark.png` });
assert.deepEqual(errors, []);
await writeFile(`${output}/measurements.json`, JSON.stringify(measurements,null,2));
console.log("Backlinks smoke passed: themes, narrow panels, long lists, keyboard, empty, busy, error, and contrast.");
} finally { await browser.close(); }
+129
View File
@@ -0,0 +1,129 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal [guide](docs/guide.md) text.\n\n| Name | Value |\n| --- | --- |\n| [Roadmap](docs/roadmap.md) | [[guide\\|Guide]] |\n| [One](same.md) + [Two](same.md) | Empty |\n`]));
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.writer-table').waitFor();
for(const theme of ['dark','light']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}), theme);
const prose = page.locator('.writer-link').filter({hasText:'guide'}).first();
await prose.hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.equal(await prose.getAttribute('title'),null);
await page.screenshot({path:'.audit/editor-link-tooltip-'+theme+'.png'});
await page.keyboard.press('Escape');
await prose.click();
assert.equal(await page.locator('.writer-link-source').count(),1);
const colored = await page.locator('.writer-link-source').evaluate(el => ({color:getComputedStyle(el).color, parent:getComputedStyle(el.parentElement).color}));
assert.notEqual(colored.color,colored.parent);
await page.screenshot({path:'.audit/editor-link-source-'+theme+'.png'});
const cell=page.locator('.writer-table td').first();
await cell.locator('a').click({position:{x:22,y:8}});
assert.ok(await page.evaluate(()=>getSelection().anchorOffset > 0));
await cell.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.getByRole('dialog').count(),0);
assert.equal(await page.evaluate(()=>getSelection().toString()),theme === 'dark' ? 'docs/roadmap.md' : 'docs/new-roadmap.md');
await page.screenshot({path:'.audit/editor-table-source-'+theme+'.png'});
await page.keyboard.type('docs/new-roadmap.md');
await page.keyboard.press('Enter');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
if(theme === 'dark') {
await page.locator('.cm-line').filter({hasText:'Original'}).click();
await page.keyboard.press('Control+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/roadmap.md');
await page.keyboard.press('Control+Shift+z');
assert.equal(await cell.locator('a').getAttribute('href'),'docs/new-roadmap.md');
}
await cell.locator('a').click({position:{x:22,y:8}});
const selection=await page.evaluate(()=>{const s=getSelection();return {offset:s.anchorOffset,length:s.anchorNode.textContent.length};});
assert.ok(selection.offset>0 && selection.offset<selection.length,JSON.stringify(selection));
await page.keyboard.type('X');
assert.ok((await cell.innerText()).includes('X'));
await page.keyboard.press('Escape');
const wiki=page.locator('.writer-table td').nth(1);
await wiki.click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),theme==='dark'?'guide':'new-guide');
await page.keyboard.type('new-guide');
await page.keyboard.press('Enter');
assert.equal(await wiki.locator('a').getAttribute('href'),'new-guide');
}
const multi=page.locator('.writer-table td').nth(2);
await multi.locator('a').nth(1).click({button:'right'});
await page.getByRole('menuitem',{name:'Edit link',exact:true}).click();
assert.equal(await page.evaluate(()=>getSelection().toString()),'same.md');
await page.keyboard.type('second.md');
await page.keyboard.press('Enter');
assert.equal(await multi.locator('a').first().getAttribute('href'),'same.md');
assert.equal(await multi.locator('a').nth(1).getAttribute('href'),'second.md');
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.getByRole('button',{name:'Files',exact:true}).click();
await page.setViewportSize({width:620,height:700});
await page.waitForTimeout(250);
await page.locator('.table-add-row').scrollIntoViewIfNeeded();
await page.waitForTimeout(100);
await page.locator('.table-add-row').focus();
await page.locator('.rs-tooltip:popover-open').waitFor();
const rect=await page.locator('.rs-tooltip:popover-open').boundingBox();
assert.ok(rect.x>=0 && rect.x+rect.width<=620);
await page.screenshot({path:'.audit/editor-tooltip-narrow-focus.png'});
await page.keyboard.press('Escape');
assert.equal(await page.locator('.rs-tooltip:popover-open').count(),0);
assert.equal(await page.locator('.table-edit-help:visible').count(),0);
for (const mode of ['light','dark']) {
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
await page.locator('.writer-table td').nth(1).hover();
await page.locator('.rs-tooltip:popover-open').waitFor();
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(),/Row 2, column 2/);
await page.screenshot({path:'.audit/editor-cell-tooltip-narrow-'+mode+'.png'});
await page.keyboard.press('Escape');
await page.mouse.move(5,90);
}
assert.deepEqual(errors,[]);
console.log('Editor link and tooltip checks passed');
} finally { await browser.close(); }
+209
View File
@@ -0,0 +1,209 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map(["a.md", "b.md", "c.md", "d.md"].map(name => [name, `# ${name}\n\nOriginal text.\n\n\`\`\`js\nconst answer = 42;\n\`\`\`\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n`]));
files.set("a.md", "# Links\n\nSelected reading text.\n\n[Web label](https://example.com/path)\n\n[[b.md|Workspace note]]\n\n| Link | Note |\n| --- | --- |\n| [Cell web](https://example.com/cell) | [[b.md\\|Cell note]] |\n");
files.set("sample.txt", "const answer = 42;\n");
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null, opened: null, app: null, windows: [] };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
window.tabMenuTest.files = files;
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: ["Corrected"], misspelled: args.word === "Original" };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return [...(!args.rel ? [{ name: "notes", rel_path: "notes", kind: "folder" }] : []), ...[...files.keys()].filter(path => path.split("/").slice(0, -1).join("/") === (args.rel || "")).map(path => ({ name: path.split("/").at(-1), rel_path: path, kind: "file" }))];
if (command === "workspace_search") { window.tabMenuTest.searched = args.query; return []; }
if (command === "plugin:opener|open_url") { window.tabMenuTest.opened = args.url; return; }
if (command === "workspace_open_default") { window.tabMenuTest.app = args.rel; return; }
if (command === "workspace_open_window") { window.tabMenuTest.windows.push(args); return; }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
throw new Error(`Unhandled IPC: ${command}`);
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const menu = name => page.getByRole('menu', { name, exact: true });
const item = name => page.getByRole('menuitem', { name, exact: true });
const output = '.audit/editor-link-menus';
await mkdir(output, { recursive: true });
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
const report = [];
async function writerMenu(target='Web label') {
await page.locator('.cm-content').getByText('Selected reading text.', { exact: true }).click();
await page.locator('.cm-content').getByText(target, { exact: true }).click({ button: 'right' });
await menu('Markdown text actions').waitFor();
}
try {
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.evaluate(async () => {
const { pluginHost } = await import('/src/lib/plugins/registry.ts');
pluginHost.register('link-smoke', 'browser', { open: async target => { window.tabMenuTest.browser = target; return true; }, mountSettings: () => () => {}, mountBookmarks: () => () => {} });
});
for (const theme of ['dark', 'light']) {
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default', mode}); }, theme);
await writerMenu();
for (const label of ['Open link in app browser', 'Open link in default browser', 'Copy URL', 'Edit link']) assert.equal(await item(label).count(), 1);
await page.screenshot({ path: `${output}/writer-link-${theme}.png` });
await item('Copy URL').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/path');
await writerMenu(); await item('Open link in default browser').click();
await page.waitForFunction(() => window.tabMenuTest.opened === 'https://example.com/path');
await writerMenu(); await item('Open link in app browser').click();
await page.waitForFunction(() => window.tabMenuTest.browser === 'https://example.com/path');
await writerMenu(); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js'); const v = EditorView.findFromDOM(document.querySelector('.cm-content')); return v.state.sliceDoc(v.state.selection.main.from, v.state.selection.main.to); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/edit-url-${theme}.png` });
await page.keyboard.type('https://changed.example');
await page.keyboard.press('Control+z');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await writerMenu('Workspace note');
for (const label of ['Open in new tab', 'Open in new window', 'Copy path', 'Bookmark', 'Show in system explorer', 'Reveal file in navigation', 'Edit link']) assert.equal(await item(label).count(), 1);
for (const label of ['Rename…', 'Move file to…', 'Open in default app']) assert.equal(await item(label).count(), 0);
await page.screenshot({ path: `${output}/workspace-link-${theme}.png` });
await dismiss();
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:620});
await writerMenu('Workspace note'); await page.keyboard.press('End');
assert.match(await page.evaluate(() => document.activeElement.textContent), /Select all/);
await page.screenshot({path:`${output}/workspace-narrow-${theme}.png`});
await dismiss(); await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Show outline',exact:true}).click();
await writerMenu('Workspace note');
await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('Workspace path').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'b.md');
await writerMenu('Workspace note'); await item('Show in system explorer').click(); await page.waitForFunction(() => window.tabMenuTest.revealed === 'b.md');
await writerMenu('Workspace note'); await item('Reveal file in navigation').click();
await page.waitForFunction(() => document.activeElement?.getAttribute('data-tree-rel') === 'b.md');
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
const reading = page.locator('.reading');
await reading.getByText('Selected reading text.',{exact:true}).evaluate(node => { const range = document.createRange(); range.selectNodeContents(node); const s = getSelection(); s.removeAllRanges(); s.addRange(range); node.closest('.reading').focus(); });
await page.keyboard.press('Shift+F10');
await menu('Reading actions').waitFor();
await page.keyboard.press('End'); assert.match(await page.evaluate(() => document.activeElement.textContent), /^Search for/);
await page.screenshot({ path: `${output}/reading-selection-${theme}.png` });
await page.keyboard.press('Home'); await page.keyboard.press('Enter');
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'Selected reading text.');
await page.keyboard.press('Shift+F10');
await page.getByRole('menuitem', {name:/^Search for/}).click();
await page.waitForFunction(() => window.tabMenuTest.searched === 'Selected reading text.');
await page.evaluate(() => getSelection().removeAllRanges());
await reading.getByRole('link',{name:'Web label'}).click({button:'right'});
await item('Copy URL').click(); await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/path');
await page.getByRole('button', { name: 'Search', exact: true }).click();
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
await page.setViewportSize({ width: 560, height: 620 });
await reading.getByRole('link',{name:'Web label'}).click({button:'right'});
const rect=await menu('Reading actions').boundingBox(); assert.ok(rect.x>=0 && rect.x+rect.width<=560 && rect.y+rect.height<=620);
await page.screenshot({ path: `${output}/reading-narrow-${theme}.png` });
await dismiss();
assert.equal(await reading.evaluate(node => node.contains(document.activeElement)), true);
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button', { name: 'Files', exact: true }).click();
await page.getByRole('button', { name: 'Show outline', exact: true }).click();
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
await page.getByRole('button',{name:'Edit',exact:true}).click();
await page.getByRole('group', { name:'Editor layout',exact:true }).hover(); await page.getByRole('button',{name:'IDE',exact:true}).click();
await page.locator('.monaco-editor').waitFor();
await page.evaluate(async () => { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const editor=monaco.editor.getEditors()[0]; const model=editor.getModel(); const pos=model.getPositionAt(model.getValue().indexOf('Web label')+2); editor.setPosition(pos); editor.focus(); });
await page.keyboard.press('Shift+F10'); await item('Edit link').click();
assert.equal(await page.evaluate(async () => { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const editor=monaco.editor.getEditors()[0]; return editor.getModel().getValueInRange(editor.getSelection()); }), 'https://example.com/path');
await page.screenshot({ path: `${output}/ide-edit-url-${theme}.png` });
await page.getByRole('group', { name:'Editor layout',exact:true }).hover(); await page.getByRole('button',{name:'Writer',exact:true}).click();
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
const cellLink = page.locator('.writer-table a').filter({hasText:'Cell web'});
await cellLink.click({button:'right'});
await item('Edit link').waitFor();
await page.screenshot({path:`${output}/table-link-${theme}.png`});
await item('Copy URL').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard === 'https://example.com/cell');
await cellLink.click({button:'right'}); await item('Edit link').click();
const sourceCell = page.locator('.writer-table .is-source-editing .writer-cell-editor');
await sourceCell.waitFor();
assert.equal(await page.getByLabel('Edit link target').count(), 0);
assert.equal(await page.evaluate(() => getSelection().toString()), 'https://example.com/cell');
assert.equal(await sourceCell.locator('.writer-link-target').innerText(), 'https://example.com/cell');
await page.screenshot({path:`${output}/table-edit-${theme}.png`});
await page.keyboard.type('https://changed.example/cell'); await page.keyboard.press('Enter');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://changed.example/cell');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://example.com/cell');
const cellNote = page.locator('.writer-table a').filter({hasText:'Cell note'});
await cellNote.click({button:'right'}); await item('Edit link').click();
assert.equal(await page.evaluate(() => getSelection().toString()), 'b.md');
await page.keyboard.type('c.md'); await page.keyboard.press('Enter');
await page.waitForFunction(() => [...document.querySelectorAll('.writer-table a')].some(node => node.textContent === 'Cell note' && node.getAttribute('href') === 'c.md'));
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => [...document.querySelectorAll('.writer-table a')].some(node => node.textContent === 'Cell note' && node.getAttribute('href') === 'b.md'));
await cellLink.click({button:'right'}); await item('Edit link').click();
await page.keyboard.type('https://escape.example'); await page.keyboard.press('Escape');
assert.equal(await sourceCell.count(), 0);
assert.equal(await cellLink.getAttribute('href'), 'https://escape.example');
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
await page.keyboard.press('Control+z');
await page.waitForFunction(() => document.querySelector('.writer-table a')?.getAttribute('href') === 'https://example.com/cell');
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Hide outline',exact:true}).click();
await page.setViewportSize({width:560,height:620});
await cellLink.click(); await page.keyboard.press('Shift+F10'); await item('Edit link').waitFor();
await page.screenshot({path:`${output}/table-narrow-${theme}.png`});
await dismiss();
await page.setViewportSize({width:1440,height:1000});
await page.getByRole('button',{name:'Files',exact:true}).click(); await page.getByRole('button',{name:'Show outline',exact:true}).click();
await page.locator('.cm-content').getByText('Selected reading text.', {exact:true}).click();
report.push({theme,passed:['Writer and IDE edit URL selection','browser destinations','workspace file actions','Reader copy/search/link actions','inline table web/wiki link edits and undo','table source Escape and keyboard menu','keyboard focus return','narrow viewport'],nativeDesktop:'not tested'});
}
await writerMenu('Workspace note'); await item('Open in new window').click();
await page.waitForFunction(() => window.tabMenuTest.windows.length === 1);
await page.evaluate(() => { const {transfer}=window.tabMenuTest.windows[0]; dispatchEvent(new StorageEvent('storage',{key:`runestone.tab-transfer.${transfer}.accepted`,newValue:'true'})); });
assert.equal(await page.getByRole('tab',{name:/b.md/}).count(),1,'Opening a linked document in a new window keeps the source tab');
await page.locator('[data-tree-rel="a.md"]').click();
await writerMenu('Workspace note'); await item('Bookmark').click();
await page.waitForFunction(() => JSON.parse(window.tabMenuTest.files.get('.runestone/marks.json') || '{}').bookmarks?.includes('b.md'));
await writerMenu('Workspace note'); await item('Copy path').focus(); await page.keyboard.press('ArrowRight'); await item('System path').click();
await page.waitForFunction(() => window.tabMenuTest.clipboard.endsWith('\\b.md'));
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
const readerWorkspaceMenu = async () => { await page.locator('.reading').getByRole('link',{name:'Workspace note'}).click({button:'right'}); };
await readerWorkspaceMenu(); await item('Open in default app').click();
await page.waitForFunction(() => window.tabMenuTest.app === 'b.md');
await readerWorkspaceMenu(); await item('Rename…').click();
await page.getByLabel('New file name').fill('renamed.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.tabMenuTest.files.has('renamed.md') && !window.tabMenuTest.files.has('b.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.tabMenuTest.files.get('.runestone/marks.json')).bookmarks.includes('renamed.md')),true);
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Edit', exact:true }).click();
await page.locator('.cm-content').evaluate(async node => { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const view=EditorView.findFromDOM(node); const from=view.state.doc.toString().indexOf('b.md'); view.dispatch({changes:{from,to:from+4,insert:'renamed.md'}}); });
await page.getByRole('group', { name: 'Document view', exact: true }).hover(); await page.getByRole('button', { name:'Read', exact:true }).click();
await readerWorkspaceMenu(); await item('Move file to…').click();
await page.getByLabel('Move file to (workspace path, including filename)').fill('notes/moved.md'); await page.getByRole('button',{name:'Continue',exact:true}).click();
await page.waitForFunction(() => window.tabMenuTest.files.has('notes/moved.md') && !window.tabMenuTest.files.has('renamed.md'));
assert.equal(await page.evaluate(() => JSON.parse(window.tabMenuTest.files.get('.runestone/marks.json')).bookmarks.includes('notes/moved.md')),true);
assert.deepEqual(errors,[]); console.log(JSON.stringify(report,null,2));
} catch(error) { await page.screenshot({path:`${output}/failure.png`}); console.log(await page.locator('.rs-menu').allTextContents()); throw error; } finally { await browser.close(); }
+121
View File
@@ -0,0 +1,121 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.tabMenuTest.calls.push({ command, args });
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/editor-preview-links';
await mkdir(output, { recursive: true });
const installation = '# Installation\n\nOutside the list.\n\n1. Get `RuneStone_<version>_amd64.deb` and its `SHA256SUMS`.\n2. Save both files to Downloads and open Terminal in that folder.\n3. Verify the download, then install the package:\n\n ```bash\n sha256sum --check SHA256SUMS\n sudo apt install ./RuneStone_0.1.42_amd64.deb\n ```\n\n Stop if verification fails.\n4. Open RuneStone from your applications menu.\n5. Open a workspace outside the application folder.\n\nAfter the list.\n';
async function resetFile(text) {
await page.locator('.cm-content').evaluate(async (node, text) => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text }, selection: { anchor: 0 } });
}, text);
}
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height: 1000 });
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').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();
}
await resetFile(installation);
const preview = page.locator('.writer-preview').filter({ has: page.locator('ol') });
await preview.waitFor();
if (theme === 'dark' && width === 1440) {
await preview.evaluate(element => { element.style.whiteSpace = 'pre-wrap'; });
const gap = await preview.locator('li').first().evaluate(item => item.querySelector('p').getBoundingClientRect().top - item.getBoundingClientRect().top);
assert.ok(gap > 15, 'Inherited editor whitespace reproduces the reported blank line');
await page.screenshot({ path:`${output}/ordered-list-before-dark-1440.png` });
await preview.evaluate(element => { element.style.removeProperty('white-space'); });
}
const metrics = await preview.evaluate(element => {
const item = element.querySelector('li'), paragraph = item.querySelector('p');
return { whiteSpace: getComputedStyle(element).whiteSpace, itemTop: item.getBoundingClientRect().top, paragraphTop: paragraph.getBoundingClientRect().top, firstHeight: item.getBoundingClientRect().height, lineHeight: parseFloat(getComputedStyle(paragraph).lineHeight) };
});
assert.equal(metrics.whiteSpace, 'normal');
assert.ok(Math.abs(metrics.paragraphTop - metrics.itemTop) < 2, 'Number and first paragraph share one line');
assert.ok(metrics.firstHeight < metrics.lineHeight * 3, 'Short list item has no blank formatting lines');
assert.equal(await preview.locator('li').count(), 5);
assert.match(await preview.locator('code').last().innerText(), /sha256sum --check SHA256SUMS\n/);
await page.screenshot({ path:`${output}/ordered-list-${theme}-${width}.png` });
const fixture = '# Links\n\nOutside.\n\n| Task | Link |\n| --- | --- |\n| Plugin setup | [Plugin installation](<docs/plugins.md#install-a-plugin>) |\n| Wiki | [[docs/plugins.md\\|Plugin guide]] |\n';
await resetFile(fixture);
await page.evaluate(() => window.tabMenuTest.files.set('docs/plugins.md', '# Plugins\n\n## Install a plugin\n\nLocal plugin instructions.\n'));
const localLink = page.locator('.writer-table a').filter({ hasText:'Plugin installation' });
await localLink.click({ modifiers:[width === 620 ? 'Meta' : 'Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
assert.equal(page.url(), process.env.SMOKE_URL || 'http://127.0.0.1:1420/');
assert.equal(browser.contexts().flatMap(context => context.pages()).length, 1, 'Local link cannot open a browser tab');
assert.equal(await page.evaluate(() => window.tabMenuTest.calls.filter(call => /open_url|open_path/.test(call.command)).length), 0);
await page.screenshot({ path:`${output}/local-link-tab-${theme}-${width}.png` });
await page.getByRole('tab', { name:'a.md', exact:true }).click();
const wiki = page.locator('.writer-table a').filter({ hasText:'Plugin guide' });
await wiki.click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.equal(await page.getByRole('tab', { name:'plugins.md', exact:true }).count(), 1, 'Duplicate link focuses its existing document');
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await page.locator('.writer-table a').filter({ hasText:'Plugin installation' }).click();
const source = page.locator('.is-source-editing .writer-cell-editor');
await source.waitFor();
await page.screenshot({ path:`${output}/source-link-${theme}-${width}.png` });
await source.locator('.writer-link-target').click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'plugins.md', exact:true }).waitFor();
assert.match(await page.locator('.cm-content').innerText(), /Local plugin instructions/);
}
assert.deepEqual(errors, []);
console.log('PASS: nested fenced-code list spacing, preserved code newlines, rendered/table-source/wiki local links open document tabs, duplicate target focus, both themes, narrow and wide windows. Native WebView acceptance remains open.');
} catch (error) {
await page.screenshot({ path:`${output}/failure.png` });
throw error;
} finally { await browser.close(); }
+175
View File
@@ -0,0 +1,175 @@
import { createRequire } from "node:module";
import assert from "node:assert/strict";
import { mkdir } from "node:fs/promises";
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
page.setDefaultTimeout(15000);
const errors = [];
page.on("pageerror", error => errors.push(error.message));
await mkdir(".audit", { recursive: true });
await page.addInitScript(() => {
localStorage.clear();
window.isTauri = true;
const root = "C:\\tab-menu-workspace";
const files = new Map([["a.md", "# Links\n\nOriginal text.\n"]]);
window.tabMenuTest = { files, calls: [], prompts: [], answer: "Cancel", revealed: null, clipboard: null };
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
let sequence = 0;
const callbacks = new Map(), listeners = new Map();
window.spellingTest = { commands: [], emit: payload => callbacks.get(listeners.get("spelling-menu"))?.({ event: "spelling-menu", id: 1, payload }) };
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { callbacks.set(++sequence, callback); return sequence; }, unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
window.tabMenuTest.calls.push({ command, args });
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command === "plugin:window|is_maximized") return false;
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
if (command === "workspace_list") return args.rel ? [] : [{ name: "notes", rel_path: "notes", kind: "folder" }, ...[...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }))];
if (command === "workspace_search") return [];
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_rename") { files.set(args.to, files.get(args.from)); files.delete(args.from); return; }
if (command === "workspace_abs_path") return `${root}\\${args.rel}`;
if (command === "workspace_reveal") { window.tabMenuTest.revealed = args.rel; return; }
if (command === "plugin:dialog|message") { window.tabMenuTest.prompts.push(args.message); return window.tabMenuTest.answer; }
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const output = '.audit/section-links';
await mkdir(output, { recursive: true });
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420/';
const filler = Array.from({ length: 50 }, (_, i) => `Paragraph ${i}. Some text before the destination.\n`).join('\n');
const source = '# Install and start\n\nChoose [Windows setup](#windows-installer), [macOS setup](#macos-installer-apple-silicon), or [Linux setup](#linux-intelamd-64-bit).\n\n[Other document](other.md#caf%C3%A9-setup-1)\n\n[Missing section](#no-such-section)\n\n' + filler + '\n## Windows installer\n\nWindows instructions.\n\n' + filler + '\n## macOS installer (Apple Silicon)\n\nMac instructions.\n\n' + filler + '\n## Linux (Intel/AMD 64-bit)\n\nLinux instructions.\n';
const other = '# Other\n\n## Café setup\n\nFirst.\n\n' + filler + '\n## Café setup\n\nSecond.\n';
async function choose(group, value) {
const control = page.getByRole('group', { name: group, exact: true });
await control.hover();
await control.locator(`[data-value="${value}"]`).click();
}
async function writerJump(label, line) {
const link = page.locator('.cm-content .writer-link').filter({ hasText: label }).first();
await link.click({ modifiers: ['Control'] });
await page.waitForFunction(async expected => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).number === expected;
}, line);
}
async function jumpLine(label) { return source.slice(0, source.indexOf(label)).split('\n').length; }
async function top() {
await page.locator('.cm-content').evaluate(async node => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const view = EditorView.findFromDOM(node);
view.dispatch({ selection:{ anchor:0 }, effects:EditorView.scrollIntoView(0, { y:'start' }) });
view.scrollDOM.scrollTop = 0;
});
}
async function readerJump(label, text) {
await page.locator('.reading a').filter({ hasText:label }).click();
const heading = page.locator('.reading h2').filter({ hasText:text }).first();
await heading.waitFor();
await page.waitForFunction(text => {
const heading = [...document.querySelectorAll('.reading h2')].find(node => node.textContent === text);
if (!heading) return false;
const rect = heading.getBoundingClientRect(), box = heading.closest('.md-page').getBoundingClientRect();
return !heading.hidden && rect.top >= box.top && rect.bottom <= box.bottom;
}, text);
}
try {
for (const theme of ['dark', 'light']) for (const width of [1440, 620]) {
await page.setViewportSize({ width, height:1000 });
await page.goto(url);
await page.evaluate(({ source, other }) => {
window.tabMenuTest.files.set('a.md', source);
window.tabMenuTest.files.set('other.md', other);
}, { source, other });
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').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();
}
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top();
await writerJump('Windows setup', await jumpLine('## Windows installer'));
await top();
await writerJump('macOS setup', await jumpLine('## macOS installer'));
await top();
await writerJump('Linux setup', await jumpLine('## Linux'));
await page.screenshot({ path:`${output}/writer-${theme}-${width}.png` });
await top();
await page.locator('.writer-link').filter({ hasText:'Missing section' }).click({ modifiers:['Control'] });
await page.getByText('Could not open #no-such-section', { exact:true }).waitFor();
await top();
await page.locator('.writer-link').filter({ hasText:'Other document' }).click({ modifiers:['Control'] });
await page.getByRole('tab', { name:'other.md', exact:true }).waitFor();
await page.waitForFunction(async () => {
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
const node = document.querySelector('.cm-content');
const view = node ? EditorView.findFromDOM(node) : null;
return view && view.state.doc.lineAt(view.state.selection.main.head).text === '## Café setup' && view.state.selection.main.head > 100;
});
assert.equal(await page.getByRole('tab', { name:'a.md', exact:true }).count(), 1);
await page.getByRole('tab', { name:'a.md', exact:true }).click();
await top();
await choose('Document view', 'read');
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/reading-${theme}-${width}.png` });
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('macOS setup', 'macOS installer (Apple Silicon)');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'split');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Windows setup', 'Windows installer');
await page.screenshot({ path:`${output}/split-${theme}-${width}.png` });
await choose('Document view', 'edit');
await choose('Editor layout', 'Ide');
await page.locator('.monaco-editor').waitFor();
await choose('Document view', 'read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await readerJump('Linux setup', 'Linux (Intel/AMD 64-bit)');
await choose('Document view', 'edit');
await page.waitForFunction(() => {
const node = document.querySelector('.monaco-editor .view-lines');
return node?.textContent.includes('Linux');
});
await page.screenshot({ path:`${output}/ide-${theme}-${width}.png` });
assert.equal(page.url(), url);
assert.equal(await page.evaluate(() => window.tabMenuTest.files.get('a.md')), source);
}
await page.goto(url);
const folded = 'Start.\n\n[Jump to nested](#nested)\n\n[[#Nested|Wiki section]]\n\n# Parent\n\n' + filler + '\n## Nested\n\nDestination text.\n';
await page.evaluate(text => window.tabMenuTest.files.set('a.md', text), folded);
await page.locator('[data-tree-rel="a.md"]').click();
await page.locator('.cm-content').waitFor();
await page.getByRole('button', { name:'Collapse Parent', exact:true }).click();
await writerJump('Jump to nested', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await top();
await writerJump('Wiki section', folded.slice(0, folded.indexOf('## Nested')).split('\n').length);
await choose('Document view', 'read');
await page.locator('.md-page').evaluate(node => { node.scrollTop = 0; });
await page.getByRole('button', { name:'Collapse Parent', exact:true }).last().click();
await readerJump('Jump to nested', 'Nested');
await page.screenshot({ path:`${output}/folded-section-revealed.png` });
assert.deepEqual(errors, []);
console.log('Section links passed: three reported headings, cross-file encoded duplicate, four views, both themes, wide/narrow.');
} finally { await browser.close(); }
+154
View File
@@ -0,0 +1,154 @@
// 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_rename") {
if (window.__TEST__.delayRename) await new Promise(resolve => { window.__TEST__.resumeRename = resolve; });
if (!files.has(args.from)) throw new Error("File is missing");
if (files.has(args.to)) throw new Error("A file with that name already exists");
files.set(args.to, files.get(args.from)); files.delete(args.from); 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 window.__TEST__.answer ?? "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 page.addInitScript(() => {
localStorage.setItem('runestone.settings',JSON.stringify({autosaveEnabled:false}));
const {files}=window.__TEST__; files.clear();
files.set('projects/source.md','# Source\n\n[[Target]]\n');
files.set('archive/deep/Target.md','# Target\n');
files.set('other.md','# Other\n\n[Target](archive/deep/Target.md)\n');
});
async function openNote(name) {
await page.keyboard.press('Control+p');
await page.getByRole('textbox',{name:'Find a file'}).fill(name);
await page.getByRole('dialog').getByRole('button').filter({hasText:name}).first().click();
await page.getByRole('textbox',{name:'Writing editor',exact:true}).waitFor();
}
const backlink=path=>page.getByRole('button',{name:'Open '+path+', line 3',exact:true});
try {
await page.goto(process.env.SMOKE_URL||'http://127.0.0.1:1420');
await page.getByText('smoke-workspace',{exact:true}).waitFor();
await openNote('projects/source.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.getByRole('tab',{name:'Target.md',exact:true}).waitFor();
await backlink('projects/source.md').waitFor();
await backlink('other.md').waitFor();
assert.equal(await page.getByRole('tab',{name:'source.md',exact:true}).count(),1);
await page.screenshot({path:'.audit/workspace-links-dark.png'});
await backlink('projects/source.md').click();
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='projects/source.md');
const writer=page.getByRole('textbox',{name:'Writing editor',exact:true});
await writer.focus(); await page.keyboard.press('Control+Home'); await page.keyboard.press('Control+a'); await page.keyboard.type('# Source\n\nNo links now.');
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await page.waitForFunction(()=>!document.querySelector('button[aria-label="Open projects/source.md, line 3"]'));
await backlink('other.md').waitFor();
await page.evaluate(()=>{
window.__TEST__.files.set('duplicates/Target.md','# Another target');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['duplicates/Target.md']});
});
await page.waitForTimeout(350);
await openNote('other.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
await page.evaluate(()=>{
window.__TEST__.files.set('wiki.md','# Wiki\n\n[[Target]]\n');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'create',paths:['wiki.md']});
});
await openNote('wiki.md');
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.locator('.status').filter({hasText:'More than one note matches Target'}).waitFor();
assert.equal(await page.locator('.breadcrumb').textContent(),'wiki.md');
await page.evaluate(()=>{
window.__TEST__.files.delete('duplicates/Target.md');
window.__TEST__.emit('workspace-event',{root:window.__TEST__.root,kind:'remove',paths:['duplicates/Target.md']});
});
await page.waitForTimeout(350);
await page.locator('.cm-content .writer-link').filter({hasText:'Target'}).click({modifiers:['Control']});
await page.waitForFunction(()=>document.querySelector('.breadcrumb')?.textContent==='archive/deep/Target.md');
await backlink('wiki.md').waitFor();
await page.evaluate(()=>{
const {files,emit,root}=window.__TEST__;
files.set('moved/wiki.md',files.get('wiki.md')); files.delete('wiki.md');
emit('workspace-event',{root,kind:'rename',paths:['wiki.md','moved/wiki.md']});
});
await backlink('moved/wiki.md').waitFor();
assert.equal(await backlink('wiki.md').count(),0);
await page.evaluate(()=>{window.__TEST__.answer='Ok';});
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).click();
await page.keyboard.press('Control+w');
await page.getByRole('tab',{name:/^source\.md(?: •)?$/}).waitFor({state:'detached'});
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await backlink('projects/source.md').waitFor();
await page.setViewportSize({width:620,height:850});
await page.evaluate(()=>{document.documentElement.dataset.theme='light';});
await page.getByRole('tab',{name:'Target.md',exact:true}).click();
await page.screenshot({path:'.audit/workspace-links-narrow.png'});
assert.deepEqual(errors,[]);
console.log('Workspace link integration passed: workspace wiki resolution, new tabs, backlinks navigation, live edits, discarded drafts, creation, move, deletion and duplicate guard.');
}finally{await browser.close();}