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:
@@ -0,0 +1,40 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
|
||||
/** Load the actual compiled packages through the production Blob module loader. */
|
||||
export async function mockFeaturePlugins(surface) {
|
||||
const packages = await Promise.all(["terminal", "table-formulas"].map(async name => {
|
||||
const root = name === "terminal"
|
||||
? (process.env.RUNESTONE_TERMINAL_DIST ? pathToFileURL(resolve(process.env.RUNESTONE_TERMINAL_DIST) + "/") : new URL("../../../../RuneStone_Terminal/dist/", import.meta.url))
|
||||
: new URL(`../../../plugin-packages/${name}/`, import.meta.url);
|
||||
return {
|
||||
manifest: JSON.parse(await readFile(new URL("plugin.json", root), "utf8")),
|
||||
code: await readFile(new URL("main.js", root), "utf8"),
|
||||
css: name === "terminal" ? await readFile(new URL("style.css", root), "base64") : "",
|
||||
};
|
||||
}));
|
||||
await surface.addInitScript(packages => {
|
||||
const key = "test.installed-plugins";
|
||||
const root = "C:\\AppData\\RuneStone\\plugins";
|
||||
const defaults = packages.map(item => ({ manifest: item.manifest, hash: "test-hash", enabled: true, path: root + "\\" + item.manifest.id, error: null, removal: false }));
|
||||
const read = () => JSON.parse(localStorage.getItem(key) || JSON.stringify(defaults));
|
||||
const write = rows => { localStorage.setItem(key, JSON.stringify(rows)); window.__TEST__?.emit("plugins-changed", {}); };
|
||||
if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(defaults));
|
||||
window.addEventListener("storage", event => { if (event.key === key) window.__TEST__?.emit("plugins-changed", {}); });
|
||||
const original = window.__TAURI_INTERNALS__.invoke;
|
||||
window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => {
|
||||
if (!command.startsWith("plugins_")) return original(command, args);
|
||||
window.__TEST__?.calls.push({ command, args });
|
||||
if (command === "plugins_snapshot") return { root, plugins: read() };
|
||||
if (command === "plugins_load") return packages.find(item => item.manifest.id === args.id).code;
|
||||
if (command === "plugins_asset") return packages.find(item => item.manifest.id === args.id).css;
|
||||
if (command === "plugins_set_enabled") { write(read().map(item => item.manifest.id === args.id ? { ...item, enabled: args.enabled } : item)); return; }
|
||||
if (command === "plugins_prepare_remove") return { token: args.id, plugin: read().find(item => item.manifest.id === args.id) };
|
||||
if (command === "plugins_remove") { write(read().filter(item => item.manifest.id !== args.token)); return; }
|
||||
if (command === "plugins_data") return "null";
|
||||
if (["plugins_release", "plugins_cancel", "plugins_reveal"].includes(command)) return;
|
||||
throw new Error(`Unhandled plugin IPC: ${command}`);
|
||||
};
|
||||
}, packages);
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const output = '.audit/background-frames';
|
||||
const report = [];
|
||||
await mkdir(output, { recursive: true });
|
||||
try {
|
||||
for (const theme of ['light', 'dark']) {
|
||||
const page = await browser.newPage({ viewport: { width: 1280, height: 820 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:/background-test';
|
||||
const files = new Map([
|
||||
['welcome.md', '# Working notes\n\nKeep the image quiet behind readable text.\n\n## Next steps\n\n- Write a note\n- Review the code\n\n' + 'A paragraph with **bold text** and a [link](https://example.com).\n\n'.repeat(24)],
|
||||
['hello.ts', '// A focused code view\nexport function greet(name: string) {\n const message = `Hello ${name}`;\n return message;\n}\n'],
|
||||
]);
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, transformCallback: () => 1, unregisterCallback() {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'background-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_list') return [...files.keys()].map(name => ({ name, rel_path: name, kind: 'file' }));
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('missing'); return files.get(args.rel); }
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugins_snapshot') return { root, plugins: [] };
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
|
||||
});
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.locator('.welcome-actions button').first().waitFor();
|
||||
await page.getByText('background-test', { exact: true }).waitFor();
|
||||
await page.evaluate(async theme => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
const { backgroundHub } = await import('/src/lib/plugins/backgrounds.ts');
|
||||
const make = (first, second) => {
|
||||
const canvas = document.createElement('canvas'); canvas.width = 1200; canvas.height = 800;
|
||||
const ctx = canvas.getContext('2d'); const gradient = ctx.createLinearGradient(0, 0, 1200, 800);
|
||||
gradient.addColorStop(0, first); gradient.addColorStop(1, second); ctx.fillStyle = gradient; ctx.fillRect(0, 0, 1200, 800);
|
||||
ctx.strokeStyle = '#ffffff88'; ctx.lineWidth = 12;
|
||||
for (let x = 0; x < 1400; x += 200) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x - 300, 800); ctx.stroke(); }
|
||||
return canvas.toDataURL();
|
||||
};
|
||||
const saved = make('#bd486c', '#438f67');
|
||||
saveAppearance({ theme: 'default', mode: theme, newTabBackground: { image: saved, overlay: 0.15, position: 'center', size: 'cover' } });
|
||||
const urls = await Promise.all([make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(async url => URL.createObjectURL(await (await fetch(url)).blob())));
|
||||
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
|
||||
}, theme);
|
||||
const background = page.locator('.workarea-background');
|
||||
assert.equal(await background.count(), 1);
|
||||
assert.equal(await page.locator('.empty h1, .empty > p').count(), 0);
|
||||
assert.equal(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage), 'none');
|
||||
const bounds = await background.boundingBox();
|
||||
assert.equal(bounds.x, 0); assert.equal(bounds.y, 36); assert.equal(bounds.width, 1280); assert.equal(bounds.height, 762);
|
||||
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
|
||||
assert.match(await page.locator('.left').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
|
||||
assert.match(await page.locator('.right').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
|
||||
assert.match(await page.locator('.welcome-actions button').first().evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
|
||||
assert.doesNotMatch(await page.locator('header.header').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.82|82%)/);
|
||||
await page.locator('.welcome-actions button').first().focus();
|
||||
await page.keyboard.press('Tab');
|
||||
assert(await page.locator('.welcome-actions').evaluate(node => node.contains(document.activeElement)));
|
||||
await page.screenshot({ path: `${output}/${theme}-splash.png` });
|
||||
await page.evaluate(() => {
|
||||
const { hub, owner, urls } = window.backgroundTest;
|
||||
hub.set(owner, 'app', { url: urls[0], blurredUrl: urls[1], overlay: 0.15, position: 'top', size: 'contain' });
|
||||
});
|
||||
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
|
||||
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundPosition), '50% 50%, 50% 0%, 50% 50%');
|
||||
await page.screenshot({ path: `${output}/${theme}-portrait-layers.png` });
|
||||
await page.setViewportSize({ width: 390, height: 700 });
|
||||
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundSize), '100% 100%, contain, cover');
|
||||
await page.screenshot({ path: `${output}/${theme}-portrait-layers-narrow.png` });
|
||||
await page.setViewportSize({ width: 1280, height: 820 });
|
||||
await page.evaluate(() => {
|
||||
const { hub, owner, urls } = window.backgroundTest;
|
||||
hub.set(owner, 'app', { url: urls[1], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[0], overlay: 0.15, position: 'center', size: 'cover' }, transitionMs: 2000 });
|
||||
});
|
||||
await page.waitForTimeout(180);
|
||||
const opacity = await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity));
|
||||
assert(opacity > 0 && opacity < 1, `Fade has an intermediate opacity: ${opacity}`);
|
||||
await page.waitForTimeout(900);
|
||||
assert.ok(await background.evaluate(node => Number(getComputedStyle(node, '::after').opacity) < 1), 'The fade remains active after one second');
|
||||
await page.waitForTimeout(1100);
|
||||
assert.equal(await background.evaluate(node => getComputedStyle(node, '::after').opacity), '1');
|
||||
await page.keyboard.press('Control+p');
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
|
||||
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
assert.match(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).backgroundColor), /(?:0\.9|90%)/);
|
||||
await page.screenshot({ path: `${output}/${theme}-writer.png` });
|
||||
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
await page.locator('.md-page').waitFor();
|
||||
const beforeScroll = await background.boundingBox();
|
||||
await page.locator('.md-page').evaluate(node => { node.scrollTop = 600; });
|
||||
assert.deepEqual(await background.boundingBox(), beforeScroll);
|
||||
await page.screenshot({ path: `${output}/${theme}-reader.png` });
|
||||
await page.getByRole('button', { name: 'Split', exact: true }).click();
|
||||
await page.locator('.monaco-editor').waitFor();
|
||||
assert.equal(await page.locator('.monaco-editor-background').first().evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
|
||||
await page.screenshot({ path: `${output}/${theme}-split.png` });
|
||||
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.screenshot({ path: `${output}/${theme}-ide.png` });
|
||||
await page.setViewportSize({ width: 680, height: 720 });
|
||||
await page.getByRole('button', { name: 'Files', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
|
||||
await page.screenshot({ path: `${output}/${theme}-ide-narrow.png` });
|
||||
await page.keyboard.press('Control+t');
|
||||
await page.locator('.welcome-actions').waitFor();
|
||||
await page.setViewportSize({ width: 480, height: 640 });
|
||||
assert(await page.locator('.empty').evaluate(node => node.scrollWidth <= node.clientWidth));
|
||||
await page.screenshot({ path: `${output}/${theme}-splash-narrow.png` });
|
||||
await page.emulateMedia({ reducedMotion: 'reduce' });
|
||||
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.set(owner, 'app', { url: urls[0], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[1], overlay: 0.2, position: 'center', size: 'cover' }, transitionMs: 2000 }); });
|
||||
assert.equal(await background.evaluate(node => node.getAnimations().length), 0);
|
||||
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.removeOwner(owner); urls.forEach(URL.revokeObjectURL); });
|
||||
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), '');
|
||||
assert.match(await background.evaluate(node => getComputedStyle(node).backgroundImage), /blob:/);
|
||||
await page.evaluate(async () => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode: window.backgroundTest.theme }); });
|
||||
assert.equal(await background.evaluate(node => getComputedStyle(node).backgroundImage), 'none');
|
||||
await page.keyboard.press('Control+p');
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome');
|
||||
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
|
||||
await page.locator('.editor > .body').waitFor();
|
||||
assert.equal(await page.locator('.editor > .body').evaluate(node => getComputedStyle(node).backgroundColor), await page.locator('.shell').evaluate(node => getComputedStyle(node).backgroundColor));
|
||||
await page.screenshot({ path: output + '/' + theme + '-removed.png' });
|
||||
assert.deepEqual(errors, []);
|
||||
report.push({ theme, passed: ['saved image', 'continuous workarea', 'sidebar transparency', 'button-only splash', 'keyboard focus', 'writer', 'reader scrolling', 'split', 'IDE transparency', 'narrow layout', 'fade', 'reduced motion', 'slideshow removal', 'saved image removal'], screenshots: `${output}/${theme}-*.png`, nativeDesktop: 'not tested' });
|
||||
await page.close();
|
||||
console.log(`PASS: ${theme} workarea backgrounds, editors, keyboard, narrow layout, fade, and restoration`);
|
||||
}
|
||||
await writeFile(`${output}/report.json`, JSON.stringify(report, null, 2));
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,154 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\host-todo-test';
|
||||
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
|
||||
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
|
||||
window.__HOST_TEST__ = state;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push({ command, args });
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_list') {
|
||||
const prefix = args.rel ? args.rel + '/' : '';
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
|
||||
const tail = path.slice(prefix.length), 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('Destination exists'); files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_write') {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === 'workspace_rename') {
|
||||
if (files.has(args.to)) throw new Error('Destination exists');
|
||||
if (!files.has(args.from)) throw new Error('Missing file');
|
||||
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
|
||||
}
|
||||
if (command === 'workspace_delete') { files.delete(args.rel); return; }
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:dialog|message') return 'Ok';
|
||||
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage(), settings = await context.newPage();
|
||||
const errors = [];
|
||||
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
|
||||
await mkdir('output/appearance-pass3', { recursive: true });
|
||||
async function background() { return main.locator('.empty').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]); }
|
||||
async function decoded(page, url) {
|
||||
return page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
|
||||
}
|
||||
try {
|
||||
await main.goto(origin); await main.locator('.empty').waitFor();
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
const image = await main.evaluate(() => {
|
||||
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 700;
|
||||
const ctx = canvas.getContext('2d'), pixels = ctx.createImageData(700, 700);
|
||||
let seed = 23;
|
||||
for (let i = 0; i < pixels.data.length; i++) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; pixels.data[i] = i % 4 === 3 ? 255 : seed >>> 24; }
|
||||
ctx.putImageData(pixels, 0, 0); return canvas.toDataURL();
|
||||
});
|
||||
const bytes = Buffer.from(image.split(',')[1], 'base64');
|
||||
assert.ok(image.length > 2 ** 21 && bytes.length < 2_000_000, 'Fixture crosses the CSS limit but fits the upload limit');
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'large.png', mimeType: 'image/png', buffer: bytes });
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
let url = await background();
|
||||
assert.equal(await decoded(main, url), 700, 'The actual new-tab image decodes');
|
||||
await main.reload(); await main.locator('.empty').waitFor();
|
||||
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
|
||||
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
|
||||
const large = Buffer.concat([pixel, Buffer.alloc(50 * 1024 * 1024 - pixel.length)]);
|
||||
await writeFile('output/appearance-pass3/50MiB.png', large);
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/50MiB.png'));
|
||||
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.empty')).backgroundImage)?.[1] !== old, url);
|
||||
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
|
||||
assert.ok(await settings.evaluate(() => localStorage.getItem('runestone.appearance').length < 500), 'Image bytes stay outside localStorage');
|
||||
await main.reload(); await main.locator('.empty').waitFor();
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
|
||||
const acceptedId = await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId);
|
||||
await writeFile('output/appearance-pass3/too-large.png', Buffer.alloc(50 * 1024 * 1024 + 1));
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/too-large.png'));
|
||||
await settings.getByRole('alert').filter({ hasText: '50 MiB' }).waitFor();
|
||||
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId), acceptedId);
|
||||
assert.equal(await settings.locator('input[type=color]').count(), 0);
|
||||
await settings.getByLabel('Image overlay', { exact: true }).fill('55');
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('0.55'));
|
||||
await settings.getByLabel('Image overlay', { exact: true }).fill('-40');
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('255, 255, 255, 0.4'));
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await settings.locator('.picker').and(settings.getByRole('button', { name: 'Appearance', exact: true })).click();
|
||||
await settings.getByRole('menuitemradio', { name: mode === 'dark' ? 'Dark' : 'Light', exact: true }).click();
|
||||
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
|
||||
assert.equal(await background(), url, 'Theme changes reuse the current image URL');
|
||||
await main.screenshot({ path: `output/appearance-pass3/background-${mode}.png` });
|
||||
for (const name of ['Color theme', 'Appearance']) {
|
||||
await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).click();
|
||||
const menu = settings.getByRole('menu', { name, exact: true });
|
||||
assert.equal(await menu.evaluate(node => getComputedStyle(node).fontSize), '13px');
|
||||
assert.equal(await menu.locator(':scope > button').first().evaluate(node => getComputedStyle(node).minHeight), '30px');
|
||||
assert.equal(await menu.locator('[aria-checked="true"] svg').count(), 0);
|
||||
assert.equal(await menu.evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-menu-border)'; node.append(reference); const matches = getComputedStyle(node).borderColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true, 'Menu uses the shared border token');
|
||||
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)', 'Menus have no visible border');
|
||||
await settings.screenshot({ path: `output/appearance-pass3/${name.replaceAll(' ', '-')}-${mode}.png` });
|
||||
await settings.keyboard.press('Escape');
|
||||
assert.equal(await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).evaluate(node => node === document.activeElement), true);
|
||||
}
|
||||
}
|
||||
await settings.setViewportSize({ width: 360, height: 480 });
|
||||
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
|
||||
const box = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= 360 && box.y + box.height <= 480);
|
||||
await settings.screenshot({ path: 'output/appearance-pass3/menu-narrow.png' });
|
||||
await settings.keyboard.press('Escape');
|
||||
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
|
||||
assert.equal(await main.evaluate(async url => { try { await fetch(url); return false; } catch { return true; } }, url), true, 'Removing an image releases its URL');
|
||||
assert.equal(await settings.evaluate(async id => (await import('/src/lib/theme/backgroundImages.ts')).readBackgroundImage(id).then(Boolean), acceptedId), false, 'Removal deletes stored image bytes');
|
||||
await settings.evaluate(async () => {
|
||||
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
external.pluginTools.update(items => [...items, ...Array.from({ length: 30 }, (_, index) => ({ owner: `test.plugin${index}`, id: 'settings', title: `Plugin settings ${index}`, kind: 'view', surface: 'settings' }))]);
|
||||
});
|
||||
for (const theme of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, theme);
|
||||
await settings.setViewportSize({ width: 360, height: 600 });
|
||||
assert.equal(await settings.getByRole('navigation', { name: 'Settings categories' }).getByRole('button').count() >= 34, true);
|
||||
assert.equal(await settings.locator('.content').evaluate(node => node.clientHeight > 240 && node.clientWidth > 300), true, 'Long navigation leaves room for settings');
|
||||
await settings.screenshot({ path: `output/appearance-pass3/long-plugin-list-${theme}-narrow.png` });
|
||||
await main.setViewportSize({ width: 600, height: 700 });
|
||||
await main.keyboard.press('F1');
|
||||
await main.getByRole('dialog', { name: 'Help and about' }).waitFor();
|
||||
assert.equal(await main.locator('.help-card details[open]').count(), 0);
|
||||
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
|
||||
assert.equal(await main.locator('.help-card details[open]').count(), 1);
|
||||
await main.keyboard.press('Enter');
|
||||
await main.screenshot({ path: `output/appearance-pass3/help-${theme}-narrow.png` });
|
||||
await main.getByRole('button', { name: 'Close help', exact: true }).click();
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: large image upload, decoding, cross-window sync, reload, theme reuse, removal, shared menu dimensions, keyboard dismissal, and narrow viewport.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,76 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command) => {
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage(), settings = await context.newPage();
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
|
||||
const screenshots = [];
|
||||
await mkdir('output/todo-background', { recursive: true });
|
||||
try {
|
||||
await main.goto(origin);
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'image.png', mimeType: 'image/png', buffer: png });
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
for (const [control, choice] of [['Image position', 'Top left'], ['Image size', 'Actual size']]) {
|
||||
const button = settings.getByRole('button', { name: control, exact: true });
|
||||
await button.click();
|
||||
await settings.getByRole('menuitemradio', { name: choice, exact: true }).click();
|
||||
assert.equal(await button.evaluate(node => node === document.activeElement), true);
|
||||
}
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('0% 0%'));
|
||||
const layout = () => main.locator('.empty').evaluate(node => {
|
||||
const style = getComputedStyle(node), box = node.getBoundingClientRect();
|
||||
return { position: style.backgroundPosition, size: style.backgroundSize, width: box.width, height: box.height };
|
||||
});
|
||||
const before = await layout();
|
||||
assert.equal(before.size, '100% 100%, auto');
|
||||
await main.locator('.empty').evaluate(node => {
|
||||
const content = document.createElement('div'); content.style.cssText = 'height:2000px;flex-shrink:0;width:100%'; node.append(content);
|
||||
});
|
||||
assert.deepEqual(await layout(), before, 'Overflowing content does not resize or reposition the image surface');
|
||||
await main.reload();
|
||||
await main.locator('.empty').waitFor();
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
assert.equal((await layout()).position, before.position);
|
||||
assert.equal((await layout()).size, before.size);
|
||||
await settings.getByRole('button', { name: 'Image position', exact: true }).click();
|
||||
await settings.keyboard.press('End');
|
||||
await settings.keyboard.press('Enter');
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('100% 100%'));
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => {
|
||||
const appearance = await import('/src/lib/theme/appearance.ts');
|
||||
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
}, mode);
|
||||
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
|
||||
for (const width of [1100, 360]) {
|
||||
await settings.setViewportSize({ width, height: 700 });
|
||||
const file = `output/todo-background/settings-${mode}-${width}.png`;
|
||||
await settings.screenshot({ path: file }); screenshots.push(file);
|
||||
const pane = settings.locator('.content');
|
||||
assert.equal(await pane.evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
|
||||
}
|
||||
}
|
||||
await writeFile('output/todo-background-report.json', JSON.stringify({ card: 'ab7b1a06-fd5a-4b74-aaa1-da64eafdf71c', checks: ['Alignment and sizing choices persist across reload and windows', 'Overflow does not resize the background surface', 'Keyboard choice and focus return', 'Both themes and narrow settings'], screenshots, native: 'Desktop visual acceptance remains pending.' }, null, 2));
|
||||
console.log('PASS: background alignment, size, stable surface, persistence, keyboard, both themes, narrow settings.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async command => {
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
|
||||
const settings = await context.newPage();
|
||||
const errors = [];
|
||||
settings.on('pageerror', error => errors.push(error.message));
|
||||
await mkdir('output/round4-overlay', { recursive: true });
|
||||
try {
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({
|
||||
name: 'image.png', mimeType: 'image/png',
|
||||
buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64'),
|
||||
});
|
||||
const input = settings.getByRole('spinbutton', { name: 'Image overlay percentage' });
|
||||
const slider = settings.getByRole('slider', { name: 'Image overlay', exact: true });
|
||||
const saved = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.overlay);
|
||||
await input.fill('-37');
|
||||
assert.equal(await slider.inputValue(), '-37');
|
||||
assert.equal(await saved(), -0.37);
|
||||
await settings.reload();
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
assert.equal(await input.inputValue(), '-37');
|
||||
await input.fill('');
|
||||
assert.equal(await saved(), -0.37);
|
||||
await input.blur();
|
||||
assert.equal(await input.inputValue(), '-37');
|
||||
await input.fill('150');
|
||||
await input.blur();
|
||||
assert.equal(await input.inputValue(), '100');
|
||||
assert.equal(await saved(), 1);
|
||||
await slider.fill('24');
|
||||
assert.equal(await input.inputValue(), '24');
|
||||
assert.equal(await saved(), 0.24);
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => {
|
||||
const appearance = await import('/src/lib/theme/appearance.ts');
|
||||
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
}, mode);
|
||||
for (const width of [1100, 360]) {
|
||||
await settings.setViewportSize({ width, height: 780 });
|
||||
await input.focus();
|
||||
assert.equal(await input.evaluate(node => node === document.activeElement), true);
|
||||
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
|
||||
await settings.screenshot({ path: `output/round4-overlay/${mode}-${width}.png` });
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile('output/round4-overlay-report.json', JSON.stringify({
|
||||
card: '2d1ae11e-8142-4840-bf0a-70f682e90e53',
|
||||
hostChecks: ['Signed numeric entry and slider synchronization', 'Persistence after reload', 'Empty input retains saved value', 'Values clamp to -100 through 100', 'Both themes, keyboard focus, 360px and 1100px settings'],
|
||||
shared: ['--rs-settings-control-height', '--rs-settings-gap', '--rs-control-radius'],
|
||||
screenshotFolder: 'output/round4-overlay',
|
||||
native: 'Native desktop acceptance remains pending.',
|
||||
}, null, 2));
|
||||
console.log('PASS: numeric overlay, slider, persistence, bounds, themes, narrow settings, keyboard focus.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,231 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
|
||||
const output = '.audit/character-themes';
|
||||
const errors = [];
|
||||
await mkdir(output, { recursive: true });
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => 1, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/theme-smoke-plugins', plugins: [] };
|
||||
if (command === 'workspace_last_path') return 'C:\\theme-smoke';
|
||||
if (command === 'workspace_open') return { root: 'C:\\theme-smoke', name: 'theme-smoke', watch_mode: 'native' };
|
||||
if (command === 'workspace_list') return [{ name: 'Theme.md', rel_path: 'Theme.md', kind: 'file' }, { name: 'Theme.py', rel_path: 'Theme.py', kind: 'file' }];
|
||||
if (command === 'workspace_read' && args.rel === 'Theme.py') return '# Character colors\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n';
|
||||
if (command === 'workspace_read') return '# Theme sample\n\nA calm surface with readable text.\n\n[Link](https://example.com)\n';
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'theme_export') { window.exportedTheme = JSON.parse(args.contents); return 'C:\\theme-smoke\\my-theme.json'; }
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage();
|
||||
const settings = await context.newPage();
|
||||
const ide = await context.newPage();
|
||||
const fontSession = await context.newCDPSession(settings);
|
||||
await fontSession.send('DOM.enable');
|
||||
await fontSession.send('CSS.enable');
|
||||
for (const page of [main, settings, ide]) page.on('pageerror', error => errors.push(error.message));
|
||||
await main.goto(origin);
|
||||
await main.getByText('theme-smoke', { exact: true }).waitFor();
|
||||
await main.keyboard.press('Control+p');
|
||||
await main.getByRole('textbox', { name: 'Find a file' }).fill('Theme.md');
|
||||
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
|
||||
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
await ide.goto(origin);
|
||||
await ide.getByText('theme-smoke', { exact: true }).waitFor();
|
||||
await ide.keyboard.press('Control+p');
|
||||
await ide.getByRole('textbox', { name: 'Find a file' }).fill('Theme.py');
|
||||
await ide.getByRole('textbox', { name: 'Find a file' }).press('Enter');
|
||||
await ide.locator('.monaco-editor textarea').waitFor();
|
||||
const editorIds = () => ide.evaluate(async () => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
|
||||
});
|
||||
const initialEditors = await editorIds();
|
||||
const openSettings = async () => {
|
||||
await settings.goto(`${origin}/?settingsWindow=true`);
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
await settings.getByRole('img', { name: 'Color theme preview' }).waitFor();
|
||||
};
|
||||
const picker = name => settings.locator('.picker').and(settings.getByRole('button', { name, exact: true }));
|
||||
const choose = async (name, value) => {
|
||||
await picker(name).click();
|
||||
await settings.getByRole('menuitemradio', { name: value, exact: true }).click();
|
||||
};
|
||||
await openSettings();
|
||||
await picker('Color theme').click();
|
||||
assert.equal(await settings.getByRole('menuitemradio', { name: 'Renamon', exact: true }).count(), 0);
|
||||
assert.equal(await settings.getByRole('menuitemradio', { name: 'Asuka School Uniform', exact: true }).count(), 0);
|
||||
for (const label of ['Holo', 'Asuka Langley Soryu', 'Malfoid']) {
|
||||
assert.equal(await settings.getByRole('menuitemradio', { name: label, exact: true }).count(), 0);
|
||||
}
|
||||
await settings.keyboard.press('Escape');
|
||||
const cases = [
|
||||
['harvest-moon', 'Harvest Moon', 'dark', { ui: 'Candara', prose: 'Constantia', heading: 'Constantia' }],
|
||||
['crimson-pilot', 'Crimson Pilot', 'dark', { ui: 'Bahnschrift', prose: 'Segoe UI', heading: 'Bahnschrift' }],
|
||||
['silver-serpent', 'Silver Serpent', 'dark', { ui: 'Corbel', prose: 'Palatino Linotype', heading: 'Palatino Linotype' }],
|
||||
];
|
||||
for (const [theme, label, mode, expectedFonts] of cases) {
|
||||
await settings.setViewportSize({ width: 1100, height: 780 });
|
||||
const variant = label;
|
||||
await choose('Color theme', variant);
|
||||
for (const page of [main, settings, ide]) {
|
||||
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
|
||||
}
|
||||
const colors = await settings.evaluate(async theme => {
|
||||
const { exportAppearanceTheme } = await import('/src/lib/theme/appearance.ts');
|
||||
return exportAppearanceTheme(theme);
|
||||
}, theme);
|
||||
const actual = await settings.evaluate(keys => {
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
return Object.fromEntries(keys.map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
|
||||
}, Object.keys(colors[mode]));
|
||||
assert.deepEqual(actual, colors[mode]);
|
||||
const fonts = await settings.evaluate(() => {
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
return { ui: css.getPropertyValue('--rs-font-ui'), prose: getComputedStyle(document.querySelector('.preview-prose')).fontFamily,
|
||||
heading: getComputedStyle(document.querySelector('.preview-document strong')).fontFamily,
|
||||
code: getComputedStyle(document.querySelector('.preview-code')).fontFamily };
|
||||
});
|
||||
for (const key of ['ui', 'prose', 'heading']) assert(fonts[key].includes(expectedFonts[key]), `${theme}: ${key} uses its font`);
|
||||
assert(fonts.code.includes('Cascadia Mono'), 'Code retains the shared monospace font');
|
||||
const { root } = await fontSession.send('DOM.getDocument');
|
||||
const { nodeId } = await fontSession.send('DOM.querySelector', { nodeId: root.nodeId, selector: '.preview-prose' });
|
||||
const rendered = await fontSession.send('CSS.getPlatformFontsForNode', { nodeId });
|
||||
assert(rendered.fonts.some(item => item.glyphCount > 0), 'The font renders visible glyphs');
|
||||
console.log(`${theme} rendered fonts: ${rendered.fonts.map(item => item.familyName).join(', ')}`);
|
||||
await settings.getByRole('button', { name: 'Export theme template' }).click();
|
||||
assert.deepEqual(await settings.evaluate(() => window.exportedTheme), colors);
|
||||
await ide.waitForFunction(expected => {
|
||||
const spans = [...document.querySelectorAll('.view-line span')].filter(node => !node.children.length);
|
||||
return Object.entries(expected).every(([text, color]) => {
|
||||
const node = spans.find(node => node.textContent.replaceAll('\u00a0', ' ').includes(text));
|
||||
const probe = document.createElement('i');
|
||||
probe.style.color = color; document.body.append(probe);
|
||||
const target = getComputedStyle(probe).color; probe.remove();
|
||||
return node && getComputedStyle(node).color === target;
|
||||
});
|
||||
}, { return: colors[mode]['syntax-keyword'], RuneStone: colors[mode]['syntax-string'], 42: colors[mode]['syntax-number'], print: colors[mode]['syntax-keyword'], '# Character colors': colors[mode]['syntax-comment'] });
|
||||
assert.deepEqual(await editorIds(), initialEditors, 'Theme changes preserve the editor');
|
||||
if (theme === 'harvest-moon') {
|
||||
const normalized = await settings.evaluate(async () => {
|
||||
const { normalizeAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
return normalizeAppearance({ theme: 'harvest-moon', mode: 'light' });
|
||||
});
|
||||
assert.equal(normalized.mode, 'dark', 'Harvest Moon keeps its fixed dark appearance');
|
||||
await main.locator('[data-tree-rel="Theme.md"]').click();
|
||||
const selectedRow = await main.locator('[data-tree-rel="Theme.md"]').evaluate(node => {
|
||||
const css = getComputedStyle(node);
|
||||
return { selected: node.getAttribute('aria-selected'), fill: css.backgroundColor,
|
||||
selection: getComputedStyle(document.documentElement).getPropertyValue('--rs-item-selection-bg').trim() };
|
||||
});
|
||||
assert.equal(selectedRow.selected, 'true');
|
||||
assert.equal(selectedRow.selection, colors[mode].selection, 'File selection uses the same warm selection color');
|
||||
assert.equal(selectedRow.fill, 'rgb(72, 39, 20)', 'The selected file paints the warm fill');
|
||||
await main.screenshot({ path: `${output}/${theme}-${mode}-file-selection.png` });
|
||||
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
|
||||
node.focus();
|
||||
const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
|
||||
let text;
|
||||
while ((text = walker.nextNode()) && !text.textContent.includes('A calm surface')) {}
|
||||
const range = document.createRange(); range.selectNodeContents(text);
|
||||
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
|
||||
});
|
||||
assert.equal(await main.evaluate(() => window.getSelection().toString()), 'A calm surface with readable text.');
|
||||
await main.screenshot({ path: `${output}/${theme}-${mode}-writer-selection.png` });
|
||||
await ide.evaluate(async () => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
editor.setSelection(new monaco.Selection(1, 1, 3, 21)); editor.focus();
|
||||
});
|
||||
await ide.locator('.selected-text').first().waitFor();
|
||||
assert.equal(await ide.locator('.selected-text').first().evaluate(node => getComputedStyle(node).backgroundColor),
|
||||
'rgb(72, 39, 20)', 'IDE selection uses the same warm fill');
|
||||
await ide.screenshot({ path: `${output}/${theme}-${mode}-ide-selection.png` });
|
||||
await ide.evaluate(async () => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setPosition({ lineNumber: 1, column: 1 });
|
||||
});
|
||||
}
|
||||
await ide.screenshot({ path: `${output}/${theme}-${mode}-ide.png` });
|
||||
await settings.screenshot({ path: `${output}/${theme}-${mode}-settings.png` });
|
||||
await main.screenshot({ path: `${output}/${theme}-${mode}-document.png` });
|
||||
await settings.reload();
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
assert.equal((await picker('Color theme').textContent()).trim(), variant);
|
||||
await settings.setViewportSize({ width: 360, height: 480 });
|
||||
const content = settings.locator('dialog .content');
|
||||
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Narrow settings fit the content area');
|
||||
await picker('Color theme').scrollIntoViewIfNeeded();
|
||||
await picker('Color theme').focus();
|
||||
await settings.keyboard.press('Enter');
|
||||
const current = settings.getByRole('menuitemradio', { name: variant, exact: true });
|
||||
await current.waitFor();
|
||||
assert.equal(await current.getAttribute('aria-checked'), 'true');
|
||||
assert(await current.evaluate(node => document.activeElement === node), 'The menu focuses the current theme');
|
||||
const bounds = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
|
||||
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.y >= 0 && bounds.y + bounds.height <= 480, 'The menu stays within the viewport');
|
||||
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-menu.png` });
|
||||
await settings.keyboard.press('ArrowDown');
|
||||
await settings.keyboard.press('ArrowUp');
|
||||
assert(await current.evaluate(node => document.activeElement === node));
|
||||
await settings.keyboard.press('Escape');
|
||||
assert(await picker('Color theme').evaluate(node => document.activeElement === node), 'Dismissal returns focus');
|
||||
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-focus.png` });
|
||||
await settings.evaluate(async () => {
|
||||
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
pluginTools.set(Array.from({ length: 16 }, (_, index) => ({ owner: 'org.example.theme-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
|
||||
});
|
||||
const navigation = settings.locator('dialog aside');
|
||||
const bodyBounds = await settings.locator('dialog .body').boundingBox();
|
||||
assert((await navigation.boundingBox()).height <= bodyBounds.height * 0.4 + 1, 'Long plugin navigation leaves room for settings');
|
||||
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
|
||||
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
|
||||
await settings.screenshot({ path: `${output}/${theme}-${mode}-360-long-navigation.png` });
|
||||
await settings.evaluate(async () => { const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); pluginTools.set([]); });
|
||||
console.log(`PASS: ${theme} ${mode}, colors, fonts, IDE syntax, export, saved state, window sync, narrow menu, keyboard and focus`);
|
||||
}
|
||||
for (const [previous, theme, label] of [['holo', 'harvest-moon', 'Harvest Moon'], ['asuka', 'crimson-pilot', 'Crimson Pilot'], ['malfoid', 'silver-serpent', 'Silver Serpent']]) {
|
||||
await settings.evaluate(theme => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode: 'dark' })), previous);
|
||||
await openSettings();
|
||||
assert.equal((await picker('Color theme').textContent()).trim(), label);
|
||||
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), theme);
|
||||
await choose('Color theme', label);
|
||||
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).theme), theme);
|
||||
}
|
||||
for (const [removed, mode] of [['renamon', 'light'], ['asuka-school', 'dark']]) {
|
||||
await settings.evaluate(({ theme, mode }) => localStorage.setItem('runestone.appearance', JSON.stringify({ theme, mode })), { theme: removed, mode });
|
||||
await settings.setViewportSize({ width: 1100, height: 780 });
|
||||
await openSettings();
|
||||
for (const page of [main, settings, ide]) {
|
||||
await page.waitForFunction(mode => document.documentElement.dataset.palette === 'default' && document.documentElement.dataset.theme === mode, mode);
|
||||
}
|
||||
assert.equal((await picker('Color theme').textContent()).trim(), `RuneStone ${mode === 'light' ? 'Light' : 'Dark'}`);
|
||||
assert((await settings.evaluate(() => getComputedStyle(document.body).fontFamily)).includes('Segoe UI'), 'The default font returns after a palette change');
|
||||
await settings.screenshot({ path: `${output}/${removed}-fallback-${mode}-settings.png` });
|
||||
await settings.setViewportSize({ width: 360, height: 480 });
|
||||
assert(await settings.locator('dialog .content').evaluate(node => node.scrollWidth <= node.clientWidth));
|
||||
await settings.screenshot({ path: `${output}/default-${mode}-360-settings.png` });
|
||||
console.log(`PASS: ${removed} saved appearance restores RuneStone ${mode}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Character theme smoke passed.');
|
||||
} catch (error) {
|
||||
console.error('Page errors:', errors);
|
||||
for (const context of browser.contexts()) {
|
||||
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `${output}/failure-${index}.png` }).catch(() => {});
|
||||
}
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,104 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
|
||||
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 context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => 1, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
|
||||
if (command === "workspace_last_path") return "D:\\LayoutTest";
|
||||
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
|
||||
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
|
||||
if (command === "workspace_read") {
|
||||
if (args.rel === "note.md") return "# Layout test\n\nA note with a short paragraph.\n\nA second paragraph.\n\n| Name | Value |\n| --- | --- |\n| Alpha | 12 |\n| Beta | 24 |\n";
|
||||
throw new Error("Missing file");
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(30000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:5174";
|
||||
const row = page.locator('[data-tree-rel="note.md"]');
|
||||
try {
|
||||
await page.goto(url);
|
||||
await row.waitFor();
|
||||
await row.click();
|
||||
await page.locator('.writer-table table').waitFor();
|
||||
const alignment = await page.evaluate(() => ({header:document.querySelector('.header-left').getBoundingClientRect().right, content:document.querySelector('.center').getBoundingClientRect().left}));
|
||||
assert.ok(Math.abs(alignment.header - alignment.content) <= 1, JSON.stringify(alignment));
|
||||
const table = await page.locator('.writer-table table').evaluate(el => ({width:el.getBoundingClientRect().width, heights:[...el.rows].map(row=>row.getBoundingClientRect().height), radius:getComputedStyle(el.parentElement).borderRadius}));
|
||||
assert.ok(table.width < 400, JSON.stringify(table));
|
||||
assert.ok(table.heights.every(height => height <= 36), JSON.stringify(table));
|
||||
assert.equal(table.radius, '0px');
|
||||
await row.focus();
|
||||
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'visible');
|
||||
await page.locator('.cm-content').click({position:{x:80,y:100}});
|
||||
assert.equal(await row.locator('.selection-outline').evaluate(el=>getComputedStyle(el).visibility), 'hidden');
|
||||
assert.equal(await row.getAttribute('aria-selected'), 'true');
|
||||
const line = page.locator('.cm-line').filter({hasText:'A second paragraph.'});
|
||||
await line.hover();
|
||||
assert.equal(await line.evaluate(el=>getComputedStyle(el,'::before').width), '3px');
|
||||
assert.equal(await page.locator('.line-history').count(),0);
|
||||
await page.evaluate(async()=>{
|
||||
const {pluginHost}=await import('/src/lib/plugins/registry.ts');
|
||||
window.blameCalls=[];
|
||||
window.removeGit=pluginHost.register('ui-test','git',{blame:async(path,line)=>{
|
||||
window.blameCalls.push({path,line});
|
||||
return {commit:'123456789abcdef',author:'UI test',date:'2026-10-07T12:34:00Z',summary:`Changed line ${line}`};
|
||||
}});
|
||||
});
|
||||
await line.click();
|
||||
await page.locator('.line-history').waitFor();
|
||||
assert.match(await page.locator('.line-history').getAttribute('title'), /Line 5 · UI test/);
|
||||
await page.keyboard.type('x');
|
||||
await page.locator('.line-history').waitFor({state:'hidden'});
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.locator('.line-history').waitFor();
|
||||
for(const theme of ['dark','light']) {
|
||||
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
|
||||
const tab = await page.locator('.tab.active').evaluate(el=>({background:getComputedStyle(el).backgroundColor,border:getComputedStyle(el).borderBottomColor,shadow:getComputedStyle(el).boxShadow}));
|
||||
const pane = await page.locator('.chrome-bar').evaluate(el=>getComputedStyle(el).backgroundColor);
|
||||
assert.equal(tab.background,pane);
|
||||
assert.equal(tab.border,'rgba(0, 0, 0, 0)');
|
||||
assert.equal(tab.shadow,'none');
|
||||
await line.hover();
|
||||
await page.screenshot({path:`.audit/ui-cards/writer-${theme}.png`});
|
||||
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('ArrowRight');
|
||||
await page.locator('.md-page .reading').waitFor();
|
||||
const paragraph=page.locator('.md-page p').filter({hasText:'A second paragraph.'});
|
||||
await paragraph.hover();
|
||||
assert.equal(await paragraph.evaluate(el=>getComputedStyle(el,'::before').width),'3px');
|
||||
assert.ok((await page.locator('.md-page table').boundingBox()).width<400);
|
||||
await page.screenshot({path:`.audit/ui-cards/read-${theme}.png`});
|
||||
await page.getByRole('group',{name:'Document view'}).locator('button.current').press('Home');
|
||||
}
|
||||
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('Home');
|
||||
await page.locator('.monaco-editor').waitFor();
|
||||
await page.locator('.line-history').waitFor();
|
||||
await page.evaluate(()=>window.removeGit());
|
||||
await page.locator('.line-history').waitFor({state:'hidden'});
|
||||
await page.getByRole('group',{name:'Editor layout'}).locator('button.current').press('End');
|
||||
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
|
||||
await page.setViewportSize({width:760,height:640});
|
||||
for(const theme of ['dark','light']) {
|
||||
await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);
|
||||
const dimensions=await page.locator('.header-left .icon-btn').evaluateAll(els=>els.map(el=>({width:el.getBoundingClientRect().width,svg:el.querySelector('svg').getBoundingClientRect().width})));
|
||||
assert.ok(dimensions.every(size=>size.width>=28 && size.svg>=16),JSON.stringify(dimensions));
|
||||
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth));
|
||||
await page.screenshot({path:`.audit/ui-cards/narrow-${theme}.png`});
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: pane-aligned ribbon, compact square tables, focus-only tree border, joined tabs, Writer/Read hover marker, Git line slot lifecycle, both themes and narrow width');
|
||||
} finally {await browser.close();}
|
||||
@@ -0,0 +1,206 @@
|
||||
// Run against the development server with an isolated browser storage context.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { createRequire } from "node:module";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const errors = [];
|
||||
const findings = [];
|
||||
const output = ".audit";
|
||||
await mkdir(output, { recursive: true });
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\appearance-smoke";
|
||||
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
|
||||
const callbacks = new Map();
|
||||
let sequence = 0;
|
||||
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 = {}) => {
|
||||
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:event|listen") return args.handler;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage();
|
||||
const settings = await context.newPage();
|
||||
const secondSettings = await context.newPage();
|
||||
for (const page of [main, settings, secondSettings]) {
|
||||
page.setDefaultTimeout(10000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
}
|
||||
await main.goto(origin);
|
||||
await main.getByText("appearance-smoke", { exact: true }).waitFor();
|
||||
async function openCode(index) {
|
||||
await main.keyboard.press("Control+p");
|
||||
await main.getByRole("textbox", { name: "Find a file" }).fill(`theme-${index}.py`);
|
||||
await main.getByRole("dialog").getByRole("button").filter({ hasText: `theme-${index}.py` }).first().waitFor();
|
||||
await main.getByRole("textbox", { name: "Find a file" }).press("Enter");
|
||||
await main.locator(".monaco-editor textarea").waitFor();
|
||||
await main.waitForFunction(async file => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.uri.path.endsWith(file));
|
||||
}, `theme-${index}.py`);
|
||||
await main.locator(".view-line").filter({ hasText: `Theme sample ${index}` }).waitFor();
|
||||
}
|
||||
async function editorIds() {
|
||||
return main.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().filter(editor => editor.getDomNode()?.isConnected).map(editor => editor.getId());
|
||||
});
|
||||
}
|
||||
async function syntaxColors() {
|
||||
return main.locator(".view-line span").evaluateAll(spans => Object.fromEntries(["RuneStone", "print", "42"].map(text => {
|
||||
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
|
||||
return [text, span ? getComputedStyle(span).color : null];
|
||||
})));
|
||||
}
|
||||
async function waitForSyntax(expected = null) {
|
||||
await main.waitForFunction(expected => {
|
||||
const spans = [...document.querySelectorAll(".view-line span")];
|
||||
const colors = Object.fromEntries(["RuneStone", "print", "42"].map(text => {
|
||||
const span = spans.find(node => !node.children.length && node.textContent.includes(text));
|
||||
return [text, span ? getComputedStyle(span).color : null];
|
||||
}));
|
||||
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
|
||||
}, expected);
|
||||
}
|
||||
const themeName = (theme, mode) => theme === 'sakura' ? 'Sakura' : `${({ default: 'RuneStone', claude: 'Claude' })[theme]} ${mode === 'light' ? 'Light' : 'Dark'}`;
|
||||
const picker = (page, name) => page.locator('.picker').filter({ has: page.locator('svg') }).and(page.getByRole('button', { name, exact: true }));
|
||||
async function choose(page, theme, mode) {
|
||||
await picker(page, 'Color theme').click();
|
||||
await page.getByRole('menuitemradio', { name: themeName(theme, mode), exact: true }).click();
|
||||
}
|
||||
async function openAppearance(page) {
|
||||
await page.goto(`${origin}/?settingsWindow=true`);
|
||||
await page.getByRole("button", { name: "Appearance", exact: true }).click();
|
||||
await picker(page, "Color theme").waitFor();
|
||||
}
|
||||
await openCode(0);
|
||||
await openAppearance(settings);
|
||||
await openAppearance(secondSettings);
|
||||
async function expectAppearance(theme, mode) {
|
||||
for (const page of [settings, secondSettings, main]) {
|
||||
await page.waitForFunction(({ theme, mode }) => document.documentElement.dataset.palette === theme && document.documentElement.dataset.theme === mode, { theme, mode });
|
||||
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).colorScheme), mode);
|
||||
}
|
||||
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme, mode));
|
||||
await main.waitForFunction(() => {
|
||||
const root = document.documentElement;
|
||||
const probe = document.createElement("i");
|
||||
probe.style.backgroundColor = getComputedStyle(root).getPropertyValue("--rs-workarea-editor-bg");
|
||||
document.body.append(probe);
|
||||
const expected = getComputedStyle(probe).backgroundColor;
|
||||
probe.remove();
|
||||
const surfaces = [...document.querySelectorAll(".monaco-editor .monaco-editor-background")];
|
||||
const workarea = document.querySelector('.editor > .body');
|
||||
return surfaces.length > 0 && surfaces.every(element => getComputedStyle(element).backgroundColor === 'rgba(0, 0, 0, 0)')
|
||||
&& workarea && getComputedStyle(workarea).backgroundColor === expected;
|
||||
});
|
||||
return settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue("--rs-bg").trim());
|
||||
}
|
||||
let nextCode = 1;
|
||||
const backgrounds = new Set();
|
||||
|
||||
for (const theme of ["default", "claude", "sakura"]) {
|
||||
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
|
||||
const before = await editorIds();
|
||||
await choose(settings, theme, mode);
|
||||
backgrounds.add(await expectAppearance(theme, mode));
|
||||
assert.deepEqual(await editorIds(), before, "Existing Monaco editors keep their identity when a theme changes");
|
||||
await openCode(nextCode++);
|
||||
assert.notDeepEqual(await editorIds(), before, "A new file creates a new Monaco editor");
|
||||
await expectAppearance(theme, mode);
|
||||
await waitForSyntax();
|
||||
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.appearance"))), { theme, mode });
|
||||
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}.png` });
|
||||
await main.screenshot({ path: `${output}/appearance-editor-${theme}-${mode}.png` });
|
||||
if (theme === 'sakura') {
|
||||
const keywordColor = await main.locator('.view-line span').evaluateAll(spans => {
|
||||
const keyword = spans.find(span => !span.children.length && span.textContent.trim() === 'def');
|
||||
return keyword ? getComputedStyle(keyword).color : null;
|
||||
});
|
||||
assert.equal(keywordColor, 'rgb(152, 85, 108)', 'Sakura keywords use Plum Wine');
|
||||
}
|
||||
const typography = await settings.evaluate(() => ({
|
||||
body: getComputedStyle(document.body).fontFamily,
|
||||
heading: getComputedStyle(document.querySelector('h2')).fontFamily,
|
||||
prose: getComputedStyle(document.documentElement).getPropertyValue('--rs-font-prose').trim(),
|
||||
}));
|
||||
if (theme === 'claude') {
|
||||
assert.match(typography.body, /Lora.*Georgia/);
|
||||
assert.match(typography.prose, /Lora.*Georgia/);
|
||||
assert.match(typography.heading, /Poppins.*Arial/);
|
||||
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-accent').trim()), '#d97757');
|
||||
} else assert.doesNotMatch(typography.body, /Lora|Georgia/);
|
||||
console.log(`PASS: ${theme} ${mode}, saved state, cross-window selection, existing and new Monaco editors`);
|
||||
}
|
||||
}
|
||||
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
|
||||
await picker(settings, 'Color theme').click();
|
||||
assert.deepEqual(await settings.getByRole('menuitemradio').allTextContents(), ['RuneStone Light', 'RuneStone Dark', 'Claude Light', 'Claude Dark', 'Sakura', 'Harvest Moon', 'Crimson Pilot', 'Silver Serpent']);
|
||||
await settings.keyboard.press('Escape');
|
||||
assert.equal(await picker(settings, 'Appearance').count(), 0);
|
||||
assert.equal(await picker(secondSettings, 'Appearance').count(), 0);
|
||||
const sakura = await settings.evaluate(() => {
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
return Object.fromEntries(['bg', 'border', 'selection', 'bg-active', 'syntax-parameter', 'syntax-keyword', 'syntax-local', 'syntax-static', 'syntax-instance', 'syntax-global'].map(key => [key, css.getPropertyValue(`--rs-${key}`).trim()]));
|
||||
});
|
||||
assert.deepEqual(sakura, { bg: '#fefcfc', border: '#f8dbe6', selection: '#ffc9dc', 'bg-active': '#dbeacb', 'syntax-parameter': '#cb6b91', 'syntax-keyword': '#98556c', 'syntax-local': '#618c71', 'syntax-static': '#69a2bd', 'syntax-instance': '#607fa9', 'syntax-global': '#687788' });
|
||||
for (const [theme, savedMode, expectedTheme, mode] of [
|
||||
['gpt', 'light', 'default', 'light'],
|
||||
['terminal', 'dark', 'default', 'dark'],
|
||||
['sakura', 'dark', 'sakura', 'light'],
|
||||
]) {
|
||||
await settings.evaluate(value => localStorage.setItem('runestone.appearance', JSON.stringify(value)), { theme, mode: savedMode });
|
||||
await settings.reload();
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
await expectAppearance(expectedTheme, mode);
|
||||
assert.deepEqual(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance'))), { theme: expectedTheme, mode });
|
||||
console.log(`PASS: saved ${theme} ${savedMode} migrates to ${expectedTheme} ${mode}`);
|
||||
}
|
||||
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
|
||||
await settings.setViewportSize({ width: 1100, height: 780 });
|
||||
await choose(settings, theme, mode);
|
||||
await expectAppearance(theme, mode);
|
||||
await settings.setViewportSize({ width: 360, height: 480 });
|
||||
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), 'Narrow settings do not overflow the viewport');
|
||||
const content = settings.locator('dialog .content');
|
||||
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), 'Appearance controls do not overflow the content area');
|
||||
for (const name of ['Color theme']) {
|
||||
const control = picker(settings, name);
|
||||
await control.scrollIntoViewIfNeeded();
|
||||
const bounds = await control.boundingBox();
|
||||
assert(bounds.x >= 0 && bounds.x + bounds.width <= 360 && bounds.height >= 28, `${name} remains reachable at 360px`);
|
||||
}
|
||||
await settings.screenshot({ path: `${output}/appearance-${theme}-${mode}-360.png` });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
assert.deepEqual(findings, [], 'Appearance findings');
|
||||
await context.close();
|
||||
console.log('Appearance smoke passed: supported palettes, modes, light-only Sakura, migration, persistence, typography, cross-window sync, Monaco updates, and narrow settings.');
|
||||
} catch (error) {
|
||||
console.error('Browser errors:', errors);
|
||||
for (const [index, page] of browser.contexts().flatMap(context => context.pages()).entries()) {
|
||||
await page.screenshot({ path: `${output}/appearance-failure-${index}.png` }).catch(() => {});
|
||||
}
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const errors = [];
|
||||
await mkdir('.audit/host-ui', { recursive: true });
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\appearance-smoke";
|
||||
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
|
||||
const callbacks = new Map();
|
||||
let sequence = 0;
|
||||
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 = {}) => {
|
||||
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:event|listen") return args.handler;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.goto(`${origin}/?settingsWindow=true`);
|
||||
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
for (const [theme, mode] of [['default','dark'],['default','light'],['claude','dark'],['claude','light'],['sakura','light'],['harvest-moon','dark'],['crimson-pilot','dark'],['silver-serpent','dark']]) {
|
||||
await page.evaluate(async ({theme,mode}) => {
|
||||
(await import('/src/lib/theme/appearance.ts')).saveAppearance({theme,mode,transparency:{enabled:true,amount:18}});
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
},{theme,mode});
|
||||
const slider = page.locator('#surface-transparency');
|
||||
await slider.fill('100');
|
||||
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount),100);
|
||||
await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(),'0');
|
||||
await page.keyboard.press('End'); assert.equal(await slider.inputValue(),'100');
|
||||
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-focus.png`});
|
||||
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).uncheck();
|
||||
assert(await slider.isDisabled());
|
||||
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-disabled.png`});
|
||||
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).check();
|
||||
await page.setViewportSize({width:360,height:740}); await slider.scrollIntoViewIfNeeded();
|
||||
assert(await page.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth));
|
||||
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-narrow.png`});
|
||||
await page.setViewportSize({width:1100,height:800});
|
||||
}
|
||||
await page.evaluate(async () => {
|
||||
const {installTheme} = await import('/src/lib/theme/customThemes.ts');
|
||||
const {saveAppearance,exportAppearanceTheme} = await import('/src/lib/theme/appearance.ts');
|
||||
const theme = exportAppearanceTheme('default'); theme.fonts = {ui:'Arial, sans-serif',prose:'Georgia, serif',heading:'Georgia, serif',mono:'Consolas, monospace'};
|
||||
installTheme(theme); saveAppearance({theme:'custom:my-theme',mode:'dark'}); window.dispatchEvent(new Event('focus'));
|
||||
});
|
||||
assert.match(await page.locator('.preview-prose').evaluate(node => getComputedStyle(node).fontFamily),/Georgia/);
|
||||
assert.match(await page.evaluate(async () => (await import('/src/lib/theme/appearance.ts')).exportAppearanceTheme('custom:my-theme').fonts.ui),/Arial/);
|
||||
await page.screenshot({path:'.audit/host-ui/custom-fonts.png'});
|
||||
const main = await context.newPage(); await main.goto(origin);
|
||||
await main.bringToFront();
|
||||
await main.getByRole('button',{name:'Files',exact:true}).waitFor();
|
||||
await main.evaluate(async () => {
|
||||
const loaded = performance.getEntriesByType('resource').map(entry => entry.name).find(name => new URL(name).pathname === '/src/lib/plugins/external.ts');
|
||||
const {pluginTools,refreshPlugins} = await import(loaded || '/src/lib/plugins/external.ts');
|
||||
await refreshPlugins();
|
||||
const invoke = window.__TAURI_INTERNALS__.invoke;
|
||||
window.__TAURI_INTERNALS__.invoke = (command,args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command,args);
|
||||
const commands = [{owner:'runestone.background-slideshow',id:'next-image',title:'Next background image',kind:'command',surface:'commands',icon:'skip-forward'},{owner:'runestone.background-slideshow',id:'pause-resume',title:'Pause or resume background slideshow',kind:'command',surface:'commands',icon:'pause'}];
|
||||
pluginTools.set(commands);
|
||||
});
|
||||
for (const mode of ['dark','light']) {
|
||||
await main.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
|
||||
const button = main.getByRole('button',{name:'Commands',exact:true});
|
||||
assert.equal(await button.getAttribute('title'),null);
|
||||
await button.hover(); await main.waitForTimeout(1100);
|
||||
assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
|
||||
await main.screenshot({path:`.audit/host-ui/${mode}-single-tooltip.png`});
|
||||
await main.keyboard.press('Escape'); assert.equal(await main.locator('[role=tooltip]:visible').count(),0);
|
||||
await main.mouse.move(400,400);
|
||||
await button.evaluate(node => node.blur());
|
||||
await button.focus(); await main.waitForTimeout(600); assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
|
||||
await button.click(); await main.getByRole('menu').waitFor();
|
||||
const paths = await main.locator('.rs-menu svg').evaluateAll(nodes => nodes.map(node => node.innerHTML));
|
||||
assert(paths.some(path => path.includes('M7 4v16'))); assert(paths.some(path => path.includes('m4 4 12 8')));
|
||||
await main.screenshot({path:`.audit/host-ui/${mode}-slideshow-command-icons.png`}); await main.keyboard.press('Escape');
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,166 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
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:window|is_maximized') return false;
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/theme-test-plugins', plugins: [] };
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await mkdir('output/october15-appearance', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
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();
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=' } });
|
||||
}, mode);
|
||||
const tab = page.getByRole('tab', { name: /welcome\.md/ });
|
||||
assert.equal(await tab.getAttribute('title'), null);
|
||||
await page.mouse.move(600, 600);
|
||||
await tab.hover();
|
||||
await page.locator('.rs-tooltip:popover-open').waitFor();
|
||||
assert.match(await page.locator('.rs-tooltip:popover-open').innerText(), /welcome\.md/);
|
||||
await page.screenshot({ path: `output/october15-appearance/${mode}-tab-tooltip.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
|
||||
await tab.focus();
|
||||
await page.locator('.rs-tooltip:popover-open').waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
const writer = page.getByRole('textbox', { name: 'Writing editor', exact: true });
|
||||
await writer.click(); await page.keyboard.press('Control+a');
|
||||
const colors = await writer.evaluate(node => {
|
||||
const root = getComputedStyle(document.documentElement);
|
||||
return { selection: root.getPropertyValue('--rs-selection'), bg: getComputedStyle(node, '::selection').backgroundColor,
|
||||
text: getComputedStyle(node).color, image: root.getPropertyValue('--rs-new-tab-image'), pluginBg: root.getPropertyValue('--rs-workarea-plugin-bg') };
|
||||
});
|
||||
assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i);
|
||||
assert.match(colors.bg, /0\.65/);
|
||||
assert.notEqual(colors.image.trim(), 'none');
|
||||
assert.equal(colors.pluginBg.trim(), 'transparent');
|
||||
console.log(mode, colors);
|
||||
await page.screenshot({ path: `output/october15-appearance/${mode}-selection.png` });
|
||||
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
|
||||
await page.locator('.empty').waitFor();
|
||||
await page.screenshot({ path: `output/october15-appearance/${mode}-zero-background.png` });
|
||||
await page.getByRole('tab', { name: /welcome\.md/ }).click();
|
||||
}
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => {
|
||||
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode });
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
}, mode);
|
||||
const slider = page.locator('#surface-transparency');
|
||||
for (const width of [1100, 390]) {
|
||||
await page.setViewportSize({ width, height: 800 });
|
||||
await slider.fill('0'); const zero = await slider.boundingBox();
|
||||
for (const amount of ['1', '9', '11', '18', '99', '100']) {
|
||||
await slider.fill(amount); const current = await slider.boundingBox();
|
||||
assert.equal(current.x, zero.x); assert.equal(current.width, zero.width);
|
||||
}
|
||||
await page.screenshot({ path: `output/october15-appearance/${mode}-${width}-slider.png` });
|
||||
}
|
||||
}
|
||||
await page.evaluate(() => {
|
||||
const invoke = window.__TAURI_INTERNALS__.invoke;
|
||||
window.__TAURI_INTERNALS__.invoke = (command, args) => command === 'plugins_choose'
|
||||
? Promise.resolve([{ token: 'theme-test', source: 'C:/Downloads/example.zip', error: null,
|
||||
manifest: { id: 'example', name: 'Theme example', version: '0.1.0', description: 'Theme control test', author: 'RuneStone', entry: 'main.js' } }])
|
||||
: invoke(command, args);
|
||||
});
|
||||
await page.getByRole('button', { name: 'Plug-ins', exact: true }).click();
|
||||
for (const [theme, mode] of [['harvest-moon', 'dark'], ['default', 'light']]) {
|
||||
await page.evaluate(async ({ theme, mode }) => {
|
||||
(await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme, mode }); window.dispatchEvent(new Event('focus'));
|
||||
}, { theme, mode });
|
||||
await page.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
|
||||
const checkbox = page.getByRole('checkbox', { name: 'Theme example', exact: true });
|
||||
await checkbox.waitFor();
|
||||
assert.equal(await checkbox.evaluate(node => getComputedStyle(node).accentColor), await page.evaluate(() => {
|
||||
const probe = document.createElement('span'); probe.style.color = 'var(--rs-accent)'; document.body.append(probe);
|
||||
const color = getComputedStyle(probe).color; probe.remove(); return color;
|
||||
}));
|
||||
await checkbox.focus();
|
||||
await page.screenshot({ path: `output/october15-appearance/${theme}-${mode}-install-checkbox.png` });
|
||||
await page.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: exact tab tooltips, translucent text selection, retained zero-transparency background, stable slider, themed installation checkbox.');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: 'output/october15-appearance/failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,145 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
|
||||
const output = '.audit/theme-typography';
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const errors = [];
|
||||
const report = [];
|
||||
await mkdir(output, { recursive: true });
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => 1, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/font-smoke-plugins', plugins: [] };
|
||||
if (command === 'workspace_last_path') return 'C:\\font-smoke';
|
||||
if (command === 'workspace_open') return { root: 'C:\\font-smoke', name: 'font-smoke', watch_mode: 'native' };
|
||||
if (command === 'workspace_list') return [{ name: 'Typography.md', rel_path: 'Typography.md', kind: 'file' }];
|
||||
if (command === 'workspace_read') return '# A place for your ideas\n\nRead the next chapter, collect clear notes, and keep your work close. Small letters, open spaces, and steady lines help each sentence stay readable.\n\n## Details worth keeping\n\nThe quick brown fox jumps over the lazy dog. Il1 O0 rn m, 0123456789.\n\n`const name = "RuneStone";`\n';
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage();
|
||||
const settings = await context.newPage();
|
||||
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
|
||||
await main.goto(origin);
|
||||
await main.getByText('font-smoke', { exact: true }).waitFor();
|
||||
await main.keyboard.press('Control+p');
|
||||
await main.getByRole('textbox', { name: 'Find a file' }).fill('Typography.md');
|
||||
await main.getByRole('textbox', { name: 'Find a file' }).press('Enter');
|
||||
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
await settings.goto(`${origin}/?settingsWindow=true`);
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
const sessions = new Map();
|
||||
async function rendered(page, selector) {
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
let session = sessions.get(page);
|
||||
if (!session) {
|
||||
session = await context.newCDPSession(page);
|
||||
await session.send('DOM.enable'); await session.send('CSS.enable'); sessions.set(page, session);
|
||||
}
|
||||
const { root } = await session.send('DOM.getDocument');
|
||||
const { nodeId } = await session.send('DOM.querySelector', { nodeId: root.nodeId, selector });
|
||||
assert(nodeId, selector);
|
||||
const { fonts } = await session.send('CSS.getPlatformFontsForNode', { nodeId });
|
||||
const style = await page.locator(selector).first().evaluate(node => {
|
||||
const css = getComputedStyle(node);
|
||||
return { family: css.fontFamily, size: css.fontSize, weight: css.fontWeight, lineHeight: css.lineHeight };
|
||||
});
|
||||
return { ...style, rendered: fonts.filter(font => font.glyphCount).map(({ familyName, postScriptName, glyphCount, isCustomFont }) => ({ familyName, postScriptName, glyphCount, isCustomFont })) };
|
||||
}
|
||||
const cases = [
|
||||
['harvest-moon', 'Harvest Moon', 'Constantia', 'Candara', 'Constantia', 'Constantia'],
|
||||
['crimson-pilot', 'Crimson Pilot', 'Bahnschrift', 'Bahnschrift', 'Segoe UI', 'Bahnschrift'],
|
||||
['silver-serpent', 'Silver Serpent', 'Palatino Linotype', 'Corbel', 'Palatino Linotype', 'Palatino Linotype'],
|
||||
];
|
||||
for (const [theme, label, oldFont, ui, prose, heading] of cases) {
|
||||
await settings.setViewportSize({ width: 1100, height: 780 });
|
||||
const picker = settings.locator('.picker').and(settings.getByRole('button', { name: 'Color theme', exact: true }));
|
||||
await picker.click();
|
||||
await settings.getByRole('menuitemradio', { name: label, exact: true }).click();
|
||||
await main.waitForFunction(theme => document.documentElement.dataset.palette === theme, theme);
|
||||
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).press('Control+Home');
|
||||
await main.evaluate(() => { getSelection().removeAllRanges(); document.activeElement?.blur(); });
|
||||
for (const page of [main, settings]) {
|
||||
await page.evaluate(font => {
|
||||
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.setProperty(`--rs-font-${role}`, `"${font}"`);
|
||||
}, oldFont);
|
||||
await page.screenshot({ path: `${output}/${theme}-before-${page === main ? 'document' : 'settings'}.png` });
|
||||
await page.evaluate(() => {
|
||||
for (const role of ['ui', 'prose', 'heading']) document.documentElement.style.removeProperty(`--rs-font-${role}`);
|
||||
});
|
||||
}
|
||||
const roles = {
|
||||
ui: await rendered(settings, '.picker[aria-label="Color theme"]'),
|
||||
prose: await rendered(main, '.cm-line:not(.writer-heading):not(.writer-blank)'),
|
||||
heading: await rendered(main, '.writer-h1'),
|
||||
mono: await rendered(settings, '.preview-code'),
|
||||
};
|
||||
for (const [role, family] of Object.entries({ ui, prose, heading })) {
|
||||
assert(roles[role].family.includes(family), `${theme}: ${role} CSS family`);
|
||||
assert(roles[role].rendered.some(font => font.familyName === family), `${theme}: ${role} actually renders ${family}: ${JSON.stringify(roles[role])}`);
|
||||
}
|
||||
assert.equal(roles.ui.size, '13px');
|
||||
assert.equal(roles.prose.size, '15px');
|
||||
assert(roles.mono.family.includes('Cascadia Mono'));
|
||||
assert(roles.mono.rendered.some(font => font.familyName === 'Cascadia Mono'));
|
||||
await settings.screenshot({ path: `${output}/${theme}-after-settings.png` });
|
||||
await main.screenshot({ path: `${output}/${theme}-after-document.png` });
|
||||
await main.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate(node => {
|
||||
node.focus();
|
||||
const paragraph = [...node.querySelectorAll('.cm-line')].find(line => line.textContent.includes('Read the next chapter'));
|
||||
const range = document.createRange(); range.selectNodeContents(paragraph);
|
||||
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
|
||||
});
|
||||
assert((await main.evaluate(() => getSelection().toString())).includes('Read the next chapter'));
|
||||
await main.screenshot({ path: `${output}/${theme}-selected-prose.png` });
|
||||
await settings.setViewportSize({ width: 360, height: 480 });
|
||||
const content = settings.locator('dialog .content');
|
||||
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth), `${theme}: narrow overflow`);
|
||||
await picker.scrollIntoViewIfNeeded(); await picker.focus(); await settings.keyboard.press('Enter');
|
||||
const current = settings.getByRole('menuitemradio', { name: label, exact: true });
|
||||
await current.waitFor();
|
||||
assert(await current.evaluate(node => node === document.activeElement));
|
||||
await settings.screenshot({ path: `${output}/${theme}-narrow-menu.png` });
|
||||
await settings.keyboard.press('Escape');
|
||||
assert(await picker.evaluate(node => node === document.activeElement));
|
||||
await settings.evaluate(async () => {
|
||||
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
pluginTools.set(Array.from({ length: 16 }, (_, index) => ({ owner: 'org.example.font-check', id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: 'settings' })));
|
||||
});
|
||||
const bodyBounds = await settings.locator('dialog .body').boundingBox();
|
||||
assert((await settings.locator('dialog aside').boundingBox()).height <= bodyBounds.height * .4 + 1);
|
||||
await settings.getByRole('button', { name: 'Plugin settings 16', exact: true }).scrollIntoViewIfNeeded();
|
||||
assert(await content.evaluate(node => node.scrollWidth <= node.clientWidth));
|
||||
await settings.screenshot({ path: `${output}/${theme}-narrow-long-plugins.png` });
|
||||
await settings.evaluate(async () => {
|
||||
const { pluginTools } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); pluginTools.set([]);
|
||||
});
|
||||
const fallback = {};
|
||||
for (const [role, page, selector] of [['ui', settings, '.picker[aria-label="Color theme"]'], ['prose', main, '.cm-line:not(.writer-heading):not(.writer-blank)'], ['heading', main, '.writer-h1']]) {
|
||||
await page.evaluate(role => {
|
||||
const css = getComputedStyle(document.documentElement);
|
||||
const stack = css.getPropertyValue(`--rs-font-${role}`);
|
||||
document.documentElement.style.setProperty(`--rs-font-${role}`, stack.slice(stack.indexOf(',') + 1));
|
||||
}, role);
|
||||
fallback[role] = await rendered(page, selector);
|
||||
assert(fallback[role].rendered.length > 0);
|
||||
await page.evaluate(role => document.documentElement.style.removeProperty(`--rs-font-${role}`), role);
|
||||
}
|
||||
report.push({ theme, oldFont, roles, fallback });
|
||||
console.log(`PASS ${theme}: real UI and prose sizes, rendered fonts, shared monospace, selection, narrow settings, keyboard focus, long plugin navigation`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile(`${output}/rendered-fonts.json`, JSON.stringify(report, null, 2));
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,109 @@
|
||||
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 context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(); let next = 0;
|
||||
const snapshot = { profiles: [{ id: 'user', name: 'Existing user' }], tabs: [], bookmarks: [{ id: 'saved', profileId: 'user', title: 'Existing bookmark', url: 'https://example.com' }], settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] } };
|
||||
window.builtinCheck = { loads: [], commands: [], legacy: false, removed: false, mounts: [], cleanups: [] };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'browser_connect') return 'window-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'workspace_last_path') return null;
|
||||
if (command === 'workspace_recent') return [];
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [
|
||||
{ manifest: { schemaVersion: 1, id: 'org.test.boards', name: 'Boards', author: 'Test', description: '', version: '0.1.0', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'fixture', enabled: true, installedAt: 1, path: '', error: null, removal: false },
|
||||
...(window.builtinCheck.legacy && !window.builtinCheck.removed ? [{ manifest: { schemaVersion: 1, id: 'runestone.browser', name: 'Browser', author: 'Test', description: '', version: '0.1.6', apiVersion: 1, entry: 'main.js', access: 'full-app' }, hash: 'old', enabled: true, installedAt: 1, path: '', error: null, removal: false }] : [])
|
||||
] };
|
||||
if (command === 'plugins_load') {
|
||||
window.builtinCheck.loads.push(args.id);
|
||||
if (args.id === 'runestone.browser') throw Error('The old browser package must not load');
|
||||
return `export function activate(api) {
|
||||
for (const id of ['board-a', 'board-b']) api.registerView({ id, title: id, placement: 'editor', mount(el) {
|
||||
window.builtinCheck.mounts.push(id); el.textContent = id;
|
||||
if (id === 'board-a') { const b = document.createElement('button'); b.textContent = 'Select board B'; b.onclick = () => api.replaceView('board-a', 'board-b'); el.append(b); }
|
||||
return () => { window.builtinCheck.cleanups.push(id); };
|
||||
}});
|
||||
api.registerView({ id:'source-control', title:'Source control', placement:'sidebar', navigation:true, icon:'git', mount(el) { el.textContent='Git sidebar fixture'; }});
|
||||
}`;
|
||||
}
|
||||
if (command === 'browser_request') {
|
||||
if (args.session !== 'window-session') throw Error('Missing browser session');
|
||||
window.builtinCheck.commands.push(args.command);
|
||||
if (args.command === 'newTab') { const tabId = 'native-' + (++next); snapshot.tabs.push({ id: tabId, profileId: args.args.profileId || 'user', url: 'about:blank', title: 'Browser', loading: false, blocked: 0, canBack: false, canForward: false }); return { tabId }; }
|
||||
if (args.command === 'closeTab') snapshot.tabs = snapshot.tabs.filter(tab => tab.id !== args.args.tabId);
|
||||
if (args.command === 'navigate') { const tab = snapshot.tabs.find(tab => tab.id === args.args.tabId); tab.url = args.args.input; tab.title = 'Example'; }
|
||||
if (args.command === 'settings') Object.assign(snapshot.settings, args.args);
|
||||
return structuredClone(snapshot);
|
||||
}
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
throw Error('Unhandled IPC: ' + command);
|
||||
}
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
});
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5174');
|
||||
await page.waitForFunction(async () => { const { pluginHost } = await import('/src/lib/plugins/registry.ts'); return !!pluginHost.get('browser'); });
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).fill('https://example.com');
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).press('Enter');
|
||||
await page.waitForFunction(() => window.builtinCheck.commands.includes('navigate'));
|
||||
await page.getByRole('button', { name: 'Browser profile' }).click();
|
||||
assert.equal(await page.getByRole('menuitemradio', { checked: true }).count(), 1);
|
||||
await page.keyboard.press('Escape');
|
||||
await page.evaluate(async () => { window.builtinCheck.legacy = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
|
||||
assert.equal(await page.evaluate(() => window.builtinCheck.loads.includes('runestone.browser')), false);
|
||||
await page.evaluate(async () => { window.builtinCheck.removed = true; const { refreshPlugins } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); await refreshPlugins(); });
|
||||
assert.equal(await page.locator('[data-browser-state="ready"]').count(), 1);
|
||||
await page.evaluate(async () => { const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); openPluginView('org.test.boards', 'board-a'); });
|
||||
const before = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
|
||||
await page.getByRole('button', { name: 'Select board B' }).click();
|
||||
await page.getByRole('tabpanel', { name: 'board-b', exact: true }).waitFor();
|
||||
await page.waitForFunction(() => window.builtinCheck.mounts.includes('board-b') && window.builtinCheck.cleanups.includes('board-a'));
|
||||
const after = await page.evaluate(async () => { const { get } = await import('/node_modules/.vite/deps/svelte_store.js'); const { pluginEditors } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name); return get(pluginEditors).map(view => view.key); });
|
||||
assert.deepEqual(after, before);
|
||||
await page.getByRole('button', { name: 'Source control', exact: true }).click();
|
||||
await page.getByText('Git sidebar fixture', { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole('tabpanel', { name: 'board-b', exact: true }).count(), 1);
|
||||
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
await page.screenshot({ path: `.audit/cards-2026-10-08-next/builtin-browser-${theme}.png` });
|
||||
}
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:5174') + '/?settingsWindow=true');
|
||||
await page.getByRole('button', { name: 'Browser', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Save browser settings' }).waitFor({ state: 'visible' });
|
||||
assert.match(await page.getByRole('button', { name: 'Profile', exact: true }).innerText(), /Existing user/);
|
||||
await page.setViewportSize({ width: 360, height: 800 });
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-settings-${theme}.png` });
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Built-in browser, legacy package independence, same-tab replacement and plugin sidebar checks passed.');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
console.error(await page.evaluate(async () => {
|
||||
const m = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
const read = store => { let value; store.subscribe(x => value = x)(); return value; };
|
||||
return { state: window.builtinCheck, text: document.body.innerText, errors: read(m.externalErrors), views: read(m.pluginEditors), tools: read(m.pluginTools) };
|
||||
}).catch(reason => ({ diagnosticError: String(reason) })), errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,153 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import assert from 'node:assert/strict';
|
||||
const runtime = path.resolve('browser-runtime');
|
||||
const require = createRequire(path.join(runtime, 'package.json'));
|
||||
const { chromium } = require('playwright');
|
||||
const electron = require('electron');
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
|
||||
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
|
||||
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
|
||||
});
|
||||
let sequence = 0, page, pendingFrame, painting = false;
|
||||
const pending = new Map();
|
||||
const commands = [];
|
||||
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
|
||||
const id = ++sequence;
|
||||
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
|
||||
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
|
||||
child.send({ id, command, args });
|
||||
});
|
||||
async function paint() {
|
||||
if (painting || !page || !pendingFrame) return;
|
||||
painting = true;
|
||||
const frame = pendingFrame; pendingFrame = undefined;
|
||||
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
|
||||
painting = false;
|
||||
if (pendingFrame) void paint();
|
||||
}
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
child.on('error', reject);
|
||||
child.on('message', message => {
|
||||
if (message.ready) resolve();
|
||||
if (message.id) {
|
||||
const callback = pending.get(message.id); pending.delete(message.id);
|
||||
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
|
||||
}
|
||||
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
|
||||
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
|
||||
});
|
||||
});
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
|
||||
const errors = [];
|
||||
try {
|
||||
await ready;
|
||||
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(), listeners = new Map(); let next = 0;
|
||||
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
|
||||
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
|
||||
if (command === 'browser_connect') return 'test-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
|
||||
if (command === 'workspace_last_path') return null;
|
||||
if (command === 'workspace_recent') return [];
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
throw Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
|
||||
});
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
const surface = page.getByRole('application', { name: 'Web page', exact: true });
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
|
||||
const evaluate = code => rpc('testEvaluate', { tabId, code });
|
||||
async function expectRemote(code, expected) {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
if (await evaluate(code) === expected) return;
|
||||
await page.waitForTimeout(50);
|
||||
}
|
||||
assert.equal(await evaluate(code), expected);
|
||||
}
|
||||
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><textarea id="other" style="position:absolute;left:40px;top:140px;width:300px;height:80px"></textarea><div id="rich" contenteditable="true" style="position:absolute;left:40px;top:280px;width:300px;height:80px;border:1px solid">Rich text</div>'; true;`);
|
||||
await page.locator('.surface img').waitFor();
|
||||
await page.waitForTimeout(300);
|
||||
const box = await surface.boundingBox();
|
||||
await page.mouse.click(box.x + 100, box.y + 60);
|
||||
await page.waitForTimeout(150);
|
||||
assert.deepEqual(await evaluate('({active:document.activeElement.id,focused:document.hasFocus()})'), { active: 'typing', focused: true });
|
||||
await mkdir('.audit/browser-fields', { recursive: true });
|
||||
await page.waitForFunction(() => {
|
||||
const image = document.querySelector('.surface img');
|
||||
if (!image?.complete || !image.naturalWidth) return false;
|
||||
const surface = document.querySelector('.surface');
|
||||
const ratio = image.naturalWidth / surface.clientWidth;
|
||||
const canvas = document.createElement('canvas'); canvas.width = 12; canvas.height = 28;
|
||||
const context = canvas.getContext('2d');
|
||||
context.drawImage(image, 42 * ratio, 46 * ratio, 12 * ratio, 28 * ratio, 0, 0, 12, 28);
|
||||
const pixels = context.getImageData(0, 0, 12, 28).data;
|
||||
let dark = 0;
|
||||
for (let offset = 0; offset < pixels.length; offset += 4) if (pixels[offset] < 100 && pixels[offset + 1] < 100 && pixels[offset + 2] < 100) dark++;
|
||||
return dark >= 8;
|
||||
}, null, { timeout: 5000, polling: 50 });
|
||||
await page.screenshot({ path: `.audit/browser-fields/caret-${process.env.BROWSER_TEST_SCALE || 1}x.png` });
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).focus();
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await evaluate('document.hasFocus()'), false, 'The toolbar removes focus from the page');
|
||||
await page.mouse.click(box.x + 100, box.y + 60);
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await evaluate('document.hasFocus()'), true, 'A page click restores focus');
|
||||
await page.keyboard.type('Hello World!');
|
||||
await expectRemote('document.querySelector("#typing").value', 'Hello World!');
|
||||
await page.mouse.move(box.x + 50, box.y + 60);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(box.x + 100, box.y + 60, { steps: 8 });
|
||||
await page.mouse.up();
|
||||
await page.waitForTimeout(200);
|
||||
assert(await evaluate('document.querySelector("#typing").selectionEnd > document.querySelector("#typing").selectionStart'), 'Dragging selects text in the embedded field');
|
||||
await page.mouse.click(box.x + 100, box.y + 170);
|
||||
await page.keyboard.type('Second field');
|
||||
await expectRemote('document.querySelector("#other").value', 'Second field');
|
||||
await page.mouse.click(box.x + 100, box.y + 310);
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.type('Edited rich text');
|
||||
await expectRemote('document.querySelector("#rich").textContent', 'Edited rich text');
|
||||
await evaluate(`document.body.insertAdjacentHTML('beforeend', '<iframe id="frame" style="position:absolute;left:40px;top:390px;width:300px;height:100px" srcdoc="<input id=framed style=width:200px;height:40px>"></iframe>'); true;`);
|
||||
await page.waitForTimeout(200);
|
||||
await page.mouse.click(box.x + 100, box.y + 415);
|
||||
await page.keyboard.type('Frame input');
|
||||
await expectRemote('document.querySelector("#frame").contentDocument.querySelector("#framed").value', 'Frame input');
|
||||
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), true);
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).focus();
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await evaluate('document.querySelector("#frame").contentDocument.hasFocus()'), false);
|
||||
await rpc('navigate', { tabId, input: 'about:blank' });
|
||||
await page.waitForTimeout(100);
|
||||
await evaluate(`document.body.innerHTML='<input id="after-navigation" style="position:absolute;left:40px;top:40px;width:300px;height:40px">'; true;`);
|
||||
await page.waitForTimeout(400);
|
||||
await page.mouse.click(box.x + 100, box.y + 60);
|
||||
await page.keyboard.type('After navigation');
|
||||
await page.waitForTimeout(500);
|
||||
assert.equal(await evaluate('devicePixelRatio'), Number(process.env.BROWSER_TEST_SCALE || 1), 'Navigation preserves the host pixel ratio');
|
||||
await expectRemote('document.querySelector("#after-navigation").value', 'After navigation');
|
||||
assert.equal(await evaluate('document.hasFocus()'), true);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: visible caret, page focus, toolbar blur, input, textarea, contenteditable, iframe and navigation');
|
||||
} finally {
|
||||
await browser.close();
|
||||
await rpc('shutdown').catch(() => {}); child.kill();
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, mkdir, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
import assert from 'node:assert/strict';
|
||||
const runtime = path.resolve('browser-runtime');
|
||||
const require = createRequire(path.join(runtime, 'package.json'));
|
||||
const { chromium } = require('playwright');
|
||||
const electron = require('electron');
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), 'runestone-browser-ui-'));
|
||||
const child = spawn(electron, [path.join(runtime, 'test/interaction-engine.mjs')], {
|
||||
windowsHide: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], env: { ...process.env, RS_INTERACTION_ROOT: root },
|
||||
});
|
||||
let sequence = 0, page, pendingFrame, painting = false;
|
||||
const pending = new Map();
|
||||
const commands = [];
|
||||
const rpc = (command, args = {}) => new Promise((resolve, reject) => {
|
||||
const id = ++sequence;
|
||||
const timeout = setTimeout(() => { pending.delete(id); reject(Error(`Runtime timeout: ${command}`)); }, 15000);
|
||||
pending.set(id, { resolve: value => { clearTimeout(timeout); resolve(value); }, reject: error => { clearTimeout(timeout); reject(error); } });
|
||||
child.send({ id, command, args });
|
||||
});
|
||||
async function paint() {
|
||||
if (painting || !page || !pendingFrame) return;
|
||||
painting = true;
|
||||
const frame = pendingFrame; pendingFrame = undefined;
|
||||
await page.evaluate(value => window.browserEmit?.('browser-frame', value), frame).catch(() => {});
|
||||
painting = false;
|
||||
if (pendingFrame) void paint();
|
||||
}
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
child.on('error', reject);
|
||||
child.on('message', message => {
|
||||
if (message.ready) resolve();
|
||||
if (message.id) {
|
||||
const callback = pending.get(message.id); pending.delete(message.id);
|
||||
if (message.error) callback?.reject(Error(message.error)); else callback?.resolve(message.result);
|
||||
}
|
||||
if (message.event?.event === 'frame') { pendingFrame = message.event; void paint(); }
|
||||
else if (message.event && page) void page.evaluate(value => window.browserEmit?.('browser-state', value), message.event).catch(() => {});
|
||||
});
|
||||
});
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
|
||||
const errors = [];
|
||||
try {
|
||||
await ready;
|
||||
page = await browser.newPage({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: Number(process.env.BROWSER_TEST_SCALE || 1) });
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.exposeFunction('browserRpc', async (command, args) => { const entry = { command, args, start: Date.now() }; commands.push(entry); const result = await rpc(command, args); entry.elapsed = Date.now() - entry.start; return result; });
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(), listeners = new Map(); let next = 0;
|
||||
window.browserEmit = (event, payload) => { for (const [id, entry] of listeners) if (entry.event === event) callbacks.get(entry.handler)?.({ event, id, payload }); };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: fn => { const id = ++next; callbacks.set(id, fn); return id; }, unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') { const id = ++next; listeners.set(id, args); return id; }
|
||||
if (command === 'plugin:event|unlisten') { listeners.delete(args.eventId); return; }
|
||||
if (command === 'browser_connect') return 'test-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'browser_request') return window.browserRpc(args.command, args.args);
|
||||
if (command === 'workspace_last_path') return null;
|
||||
if (command === 'workspace_recent') return [];
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
throw Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => listeners.delete(id) };
|
||||
});
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1451');
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
const surface = page.getByRole('application', { name: 'Web page', exact: true });
|
||||
await page.locator('[data-browser-state="ready"]').waitFor();
|
||||
assert.equal(await page.getByRole('button', { name: 'New browser tab', exact: true }).count(), 0);
|
||||
const tabId = await page.locator('[data-browser-state="ready"]').getAttribute('data-browser-tab');
|
||||
const evaluate = code => rpc('testEvaluate', { tabId, code });
|
||||
await evaluate(`document.body.innerHTML='<input id="typing" style="position:absolute;left:40px;top:40px;width:300px;height:40px"><a href="https://example.com/" style="position:absolute;left:40px;top:130px">Example link</a><p style="position:absolute;left:40px;top:200px">Page text</p>';true;`);
|
||||
const initialBox = await surface.boundingBox();
|
||||
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
|
||||
await page.keyboard.type('Hello World!');
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!');
|
||||
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+c');
|
||||
await page.keyboard.press('End'); await page.keyboard.press('Control+v');
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").value'), 'Hello World!Hello World!');
|
||||
await page.getByRole('textbox', { name: 'Web page text input' }).evaluate(node => {
|
||||
node.dispatchEvent(new CompositionEvent('compositionstart', { bubbles: true }));
|
||||
node.dispatchEvent(new CompositionEvent('compositionend', { bubbles: true, data: '日本語' }));
|
||||
});
|
||||
await page.waitForTimeout(100);
|
||||
assert.ok((await evaluate('document.querySelector("#typing").value')).endsWith('日本語'));
|
||||
await page.mouse.click(initialBox.x + 100, initialBox.y + 60, { button: 'right' });
|
||||
await page.getByRole('menu', { name: 'Browser page actions' }).waitFor();
|
||||
await page.getByRole('menuitem', { name: 'Select all Ctrl+A', exact: true }).click();
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").selectionEnd - document.querySelector("#typing").selectionStart'), 27);
|
||||
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.getByRole('menu', { name: 'Browser page actions' }).count(), 0);
|
||||
await page.mouse.click(initialBox.x + 70, initialBox.y + 138, { button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Copy link address', exact: true }).click();
|
||||
await page.mouse.click(initialBox.x + 100, initialBox.y + 60);
|
||||
await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await evaluate('document.querySelector("#typing").value'), 'https://example.com/');
|
||||
await evaluate(`document.body.innerHTML='<canvas width="1000" height="700"></canvas>'; const c=document.querySelector('canvas').getContext('2d'); let n=0; window.testAnimate=true; function draw(){ c.fillStyle='#fff';c.fillRect(0,0,1000,700);c.fillStyle='#5482ff';c.fillRect(n++*5%900,200,80,80);if(window.testAnimate)requestAnimationFrame(draw); } draw();true;`);
|
||||
await page.locator('.surface img').waitFor();
|
||||
await page.evaluate(() => { window.decodedFrames = 0; document.querySelector('.surface img').addEventListener('load', () => window.decodedFrames++); });
|
||||
await page.waitForTimeout(3000);
|
||||
const decodedFps = await page.evaluate(() => window.decodedFrames / 3);
|
||||
assert.ok(decodedFps >= 24, `The host image surface must decode at least 24 FPS: ${decodedFps}`);
|
||||
const beforeWheels = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length;
|
||||
await surface.evaluate(node => {
|
||||
const bounds = node.getBoundingClientRect();
|
||||
for (let index = 0; index < 500; index++) node.dispatchEvent(new WheelEvent('wheel', {
|
||||
bubbles: true, cancelable: true, clientX: bounds.x + 100, clientY: bounds.y + 100, deltaY: index < 250 ? 80 : -80,
|
||||
}));
|
||||
});
|
||||
await page.waitForTimeout(200);
|
||||
const wheelBurstCalls = commands.filter(call => call.command === 'input' && call.args.input.type === 'mouseWheel').length - beforeWheels;
|
||||
assert.ok(wheelBurstCalls <= 3, `Animated pages must not accumulate wheel input: ${wheelBurstCalls}`);
|
||||
await evaluate('window.testAnimate=false;true;');
|
||||
await evaluate(`document.body.innerHTML='<div style="width:4000px;height:6000px;background:linear-gradient(45deg,white,steelblue)"><h1>Native scroll fixture</h1></div>'; true;`);
|
||||
await page.locator('.surface img').waitFor();
|
||||
const box = await surface.boundingBox();
|
||||
const x = box.x + 220, y = box.y + 180;
|
||||
await page.mouse.click(x, y, { button: 'middle' });
|
||||
await page.mouse.move(x + 90, y + 120);
|
||||
await page.waitForTimeout(1500);
|
||||
const scrolled = await evaluate('({x:scrollX,y:scrollY})');
|
||||
assert.ok(scrolled.x > 50 && scrolled.y > 100, `Middle-button motion must scroll real Chromium: ${JSON.stringify({ scrolled, anchor: await page.locator('.scroll-anchor').count(), wheels: commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseWheel'), errors })}`);
|
||||
await page.keyboard.press('Escape');
|
||||
await page.waitForTimeout(350);
|
||||
const stopped = await evaluate('scrollY');
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await evaluate('scrollY'), stopped);
|
||||
assert.equal(await page.locator('.scroll-anchor').count(), 0);
|
||||
await page.mouse.move(x, y); await page.mouse.down({ button: 'middle' }); await page.mouse.move(x, y - 90);
|
||||
await page.waitForTimeout(300); await page.mouse.up({ button: 'middle' });
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Release after a middle-button drag stops scrolling.');
|
||||
assert.ok(await evaluate('scrollY') < stopped, 'Moving above the anchor scrolls upward.');
|
||||
await page.mouse.click(x, y, { button: 'middle' });
|
||||
await page.mouse.click(x, y, { button: 'left' });
|
||||
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'A click stops latched scrolling.');
|
||||
await page.mouse.click(x, y, { button: 'middle' });
|
||||
await page.getByRole('textbox', { name: 'Address or search' }).focus();
|
||||
assert.equal(await page.locator('.scroll-anchor').count(), 0, 'Focus loss stops scrolling.');
|
||||
const beforeMotion = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length;
|
||||
await surface.dispatchEvent('mousemove', { clientX: x, clientY: y });
|
||||
await page.evaluate(({ x, y }) => { const node = document.querySelector('.surface'); for (let i=0;i<500;i++) node.dispatchEvent(new MouseEvent('mousemove', { clientX:x+i%20, clientY:y, bubbles:true })); }, { x,y });
|
||||
await page.waitForTimeout(100);
|
||||
const motionCount = commands.filter(c => c.command === 'input' && c.args.input.type === 'mouseMove').length - beforeMotion;
|
||||
assert.ok(motionCount < 10, `Pointer bursts must not queue hundreds of native calls: ${motionCount}`);
|
||||
await mkdir('output', { recursive: true });
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode }); }, theme);
|
||||
await page.mouse.click(x, y, { button: 'middle' });
|
||||
await page.screenshot({ path: `output/browser-interaction-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
await page.setViewportSize({ width: 420, height: 650 });
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await page.keyboard.press('Control+t');
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('[data-browser-state="ready"]').length >= 2);
|
||||
assert.equal((await rpc('state')).tabs.length, 2, 'The center new-tab path must still open a browser tab.');
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile(`output/browser-interaction-${process.env.BROWSER_TEST_SCALE || 1}x.json`, JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
|
||||
console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
|
||||
} finally {
|
||||
await browser.close();
|
||||
await rpc('shutdown').catch(() => {}); child.kill();
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const { chromium } = createRequire(import.meta.url)(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: 1100, height: 850 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const snapshot = {
|
||||
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
|
||||
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
|
||||
};
|
||||
window.browserMenuTest = { snapshot, calls: [] };
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'browser_connect') return 'menu-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
|
||||
const details = args.args || {};
|
||||
window.browserMenuTest.calls.push({ command: args.command, ...details });
|
||||
if (args.command === 'webData') return { profileId: details.profileId, cookies: [], history: [] };
|
||||
if (args.command === 'settings') Object.assign(snapshot.settings, details);
|
||||
return structuredClone(snapshot);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const menu = name => page.getByRole('menu', { name, exact: true });
|
||||
const trigger = name => page.getByRole('button', { name, exact: true });
|
||||
try {
|
||||
await mkdir('output/todo-menus', { recursive: true });
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
await trigger('Browser').click();
|
||||
await trigger('Search engine').waitFor();
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await trigger('Search engine').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
const engines = menu('Search engine');
|
||||
await engines.waitFor();
|
||||
assert.equal(await engines.getByRole('menuitemradio', { name: 'DuckDuckGo' }).getAttribute('aria-checked'), 'true');
|
||||
assert.equal(await engines.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
|
||||
await page.screenshot({ path: `output/todo-menus/search-${mode}.png` });
|
||||
await page.keyboard.press('End');
|
||||
await page.keyboard.press('Space');
|
||||
assert.equal(await trigger('Search engine').innerText(), 'Bing');
|
||||
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
|
||||
await trigger('Search engine').click();
|
||||
await page.keyboard.press('Home');
|
||||
await page.keyboard.press('Enter');
|
||||
await trigger('Profile').focus();
|
||||
await page.keyboard.press('Space');
|
||||
await menu('Profile').waitFor();
|
||||
await page.screenshot({ path: `output/todo-menus/profile-${mode}.png` });
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.waitForFunction(() => document.querySelector('button[aria-label="Profile"]')?.textContent === 'Work');
|
||||
await page.waitForFunction(() => window.browserMenuTest.calls.some(call => call.command === 'webData' && call.profileId === 'work'));
|
||||
await trigger('Profile').click();
|
||||
await page.keyboard.press('Home');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.setViewportSize({ width: 520, height: 700 });
|
||||
await trigger('Search engine').click();
|
||||
const bounds = await engines.boundingBox();
|
||||
assert.ok(bounds.x >= 8 && bounds.x + bounds.width <= 512);
|
||||
await page.screenshot({ path: `output/todo-menus/narrow-${mode}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
|
||||
await page.setViewportSize({ width: 1100, height: 850 });
|
||||
}
|
||||
await trigger('Search engine').click();
|
||||
await menu('Search engine').getByRole('menuitemradio', { name: 'Google', exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.browserMenuTest.calls.filter(call => call.command === 'settings').length), 0, 'A choice does not submit the form');
|
||||
await trigger('Save browser settings').click();
|
||||
await page.waitForFunction(() => window.browserMenuTest.snapshot.settings.search === 'google');
|
||||
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.browserMenuTest.snapshot; snapshot.profiles.push(...Array.from({ length: 60 }, (_, i) => ({ id: 'p' + i, name: 'Profile ' + i }))); state.set(structuredClone(snapshot)); });
|
||||
await page.setViewportSize({ width: 520, height: 700 });
|
||||
await trigger('Profile').click();
|
||||
const profiles = menu('Profile');
|
||||
assert.equal(await profiles.evaluate(node => node.scrollHeight > node.clientHeight), true, 'Long profile lists scroll');
|
||||
await page.keyboard.press('End');
|
||||
assert.equal(await profiles.getByRole('menuitemradio', { name: 'Profile 59', exact: true }).evaluate(node => node === document.activeElement), true);
|
||||
await page.screenshot({ path: 'output/todo-menus/profile-long-narrow.png' });
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await trigger('Profile').evaluate(node => node === document.activeElement), true);
|
||||
await trigger('Profile').click();
|
||||
await trigger('Profile').evaluate(node => {
|
||||
let parent = node.parentElement;
|
||||
while (parent && parent.scrollHeight <= parent.clientHeight) parent = parent.parentElement;
|
||||
if (!parent) throw Error('Settings need a scroll area');
|
||||
parent.scrollTop -= 40;
|
||||
});
|
||||
await profiles.waitFor({ state: 'detached' });
|
||||
await trigger('Search engine').click();
|
||||
await trigger('General').click();
|
||||
assert.equal(await page.locator('.rs-menu').count(), 0, 'Leaving Browser closes the menu');
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: browser choices, persistence, keyboard selection and dismissal, long profiles, both themes, narrow layout, and cleanup.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,218 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir } 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: 1100, height: 850 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const snapshot = {
|
||||
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }],
|
||||
tabs: [{ id: 'open-tab', profileId: 'user', url: 'https://example.com', title: 'Keep open', loading: false, blocked: 0, canBack: false, canForward: false }],
|
||||
bookmarks: [],
|
||||
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
|
||||
};
|
||||
const longUrl = 'https://very-long-domain.example/' + 'long-path-segment-'.repeat(30);
|
||||
const data = {
|
||||
user: {
|
||||
profileId: 'user',
|
||||
cookies: [
|
||||
{ id: 'shared-cookie', name: 'session', domain: 'personal.example', path: '/account' },
|
||||
{ id: 'second-cookie', name: '', domain: 'another.example', path: '/settings' },
|
||||
{ id: 'long-cookie', name: 'Long cookie ' + 'value'.repeat(30), domain: 'long.example', path: '/' + 'path'.repeat(30) },
|
||||
],
|
||||
history: [
|
||||
{ id: 'shared-visit', title: 'Personal guide', url: 'https://personal.example/guide', at: 1700000000000 },
|
||||
{ id: 'second-visit', title: '', url: 'https://another.example/document', at: 1700000001000 },
|
||||
{ id: 'long-visit', title: 'Long visit ' + 'title'.repeat(30), url: longUrl, at: 1700000002000 },
|
||||
],
|
||||
},
|
||||
work: {
|
||||
profileId: 'work',
|
||||
cookies: [{ id: 'shared-cookie', name: 'session', domain: 'work.example', path: '/account' }],
|
||||
history: [{ id: 'shared-visit', title: 'Work guide', url: 'https://work.example/guide', at: 1700000000000 }],
|
||||
},
|
||||
};
|
||||
const check = window.webDataTest = { data, snapshot, calls: [], hold: [], pending: [], failNext: {} };
|
||||
let sequence = 0;
|
||||
const callbacks = new Map();
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'browser_connect') return 'web-data-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
|
||||
if (args.session !== 'web-data-session') throw Error('Missing browser session');
|
||||
const operation = args.command, details = args.args || {}, key = `${operation}:${details.profileId}`;
|
||||
check.calls.push({ operation, ...details });
|
||||
if (check.failNext[key]) { const message = check.failNext[key]; delete check.failNext[key]; throw Error(message); }
|
||||
const nextData = operation === 'webData' ? structuredClone(data[details.profileId]) : null;
|
||||
if (check.hold.includes(key)) await new Promise((resolve, reject) => check.pending.push({ key, resolve, reject }));
|
||||
if (operation === 'webData') return nextData;
|
||||
if (operation === 'removeCookie') data[details.profileId].cookies = data[details.profileId].cookies.filter(item => item.id !== details.id);
|
||||
else if (operation === 'removeHistory') data[details.profileId].history = data[details.profileId].history.filter(item => item.id !== details.id);
|
||||
else if (!['state', 'settings'].includes(operation)) throw Error('Unhandled browser operation: ' + operation);
|
||||
return structuredClone(snapshot);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
});
|
||||
const section = page.getByRole('region', { name: 'Individual web data', exact: true });
|
||||
const profile = page.getByRole('button', { name: 'Profile', exact: true });
|
||||
async function selectProfile(id) {
|
||||
await profile.click();
|
||||
await page.getByRole('menuitemradio', { name: id === 'work' ? 'Work' : 'Personal', exact: true }).click();
|
||||
}
|
||||
const kind = section.getByRole('button', { name: 'Web data type', exact: true });
|
||||
async function selectKind(value) { await kind.click(); await page.getByRole('menuitemradio', { name: value === 'cookies' ? 'Cookies' : 'History', exact: true }).click(); }
|
||||
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
|
||||
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
|
||||
const personalCookie = () => section.getByRole('button', { name: 'Remove cookie session from personal.example at /account', exact: true });
|
||||
const workCookie = () => section.getByRole('button', { name: 'Remove cookie session from work.example at /account', exact: true });
|
||||
const settle = () => section.locator('.entries[aria-busy="false"]').waitFor();
|
||||
async function hold(key) { await page.evaluate(key => { window.webDataTest.hold.push(key); }, key); }
|
||||
async function pending(key) { await page.waitForFunction(key => window.webDataTest.pending.some(item => item.key === key), key); }
|
||||
async function release(key, error) {
|
||||
await page.evaluate(({ key, error }) => {
|
||||
const check = window.webDataTest;
|
||||
check.hold = check.hold.filter(item => item !== key);
|
||||
const index = check.pending.findIndex(item => item.key === key), item = check.pending.splice(index, 1)[0];
|
||||
if (!item) throw Error('No pending request for ' + key);
|
||||
if (error) item.reject(Error(error)); else item.resolve();
|
||||
}, { key, error });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
try {
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
await page.getByRole('button', { name: 'Browser', exact: true }).click();
|
||||
await personalCookie().waitFor();
|
||||
assert.equal(await section.locator('.entry').count(), 3);
|
||||
assert.equal(await section.getByText('(unnamed cookie)', { exact: true }).count(), 1);
|
||||
await filter.fill('PERSONAL.EXAMPLE');
|
||||
assert.equal(await section.locator('.entry').count(), 1);
|
||||
await filter.fill('/settings');
|
||||
assert.equal(await section.locator('.entry').count(), 1);
|
||||
await filter.fill('no matches');
|
||||
await section.getByText('No matching cookies.', { exact: true }).waitFor();
|
||||
await filter.fill('session');
|
||||
await personalCookie().click();
|
||||
await settle();
|
||||
await section.getByText('No matching cookies.', { exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 1, 'Removing a cookie preserves another profile with the same ID');
|
||||
await selectKind('history');
|
||||
await filter.fill('GUIDE');
|
||||
await section.getByRole('button', { name: 'Remove history entry Personal guide', exact: true }).click();
|
||||
await settle();
|
||||
await section.getByText('No matching history.', { exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.data.work.history.length), 1);
|
||||
await filter.fill('another.example/document');
|
||||
await section.getByRole('button', { name: 'Remove history entry https://another.example/document', exact: true }).waitFor();
|
||||
assert.equal(await section.locator('.entry').count(), 1);
|
||||
await selectProfile('work');
|
||||
await settle();
|
||||
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
|
||||
await section.getByText('Work guide', { exact: true }).waitFor();
|
||||
await selectKind('cookies');
|
||||
await workCookie().waitFor();
|
||||
|
||||
// A delayed successful response from the previous profile must not replace the current rows.
|
||||
await hold('webData:work');
|
||||
await refresh.click();
|
||||
await pending('webData:work');
|
||||
assert.equal(await workCookie().isDisabled(), true);
|
||||
await selectProfile('user');
|
||||
await settle();
|
||||
await release('webData:work');
|
||||
assert.equal(await workCookie().count(), 0);
|
||||
assert.equal(await section.locator('.entry').count(), 2);
|
||||
|
||||
// The same guard must ignore an old request error.
|
||||
await hold('webData:user');
|
||||
await refresh.click();
|
||||
await pending('webData:user');
|
||||
await selectProfile('work');
|
||||
await workCookie().waitFor();
|
||||
await settle();
|
||||
await release('webData:user', 'Stale personal error');
|
||||
assert.equal(await section.getByRole('alert').count(), 0);
|
||||
assert.equal(await refresh.isEnabled(), true);
|
||||
|
||||
// Removal finishes for its original profile without refreshing the selected profile.
|
||||
await hold('removeCookie:work');
|
||||
await workCookie().click();
|
||||
await pending('removeCookie:work');
|
||||
await selectProfile('user');
|
||||
await settle();
|
||||
const readsBefore = await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length);
|
||||
await release('removeCookie:work');
|
||||
assert.equal(await profile.innerText(), 'Personal');
|
||||
assert.equal(await section.locator('.entry').count(), 2);
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.calls.filter(item => item.operation === 'webData').length), readsBefore);
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.data.work.cookies.length), 0);
|
||||
|
||||
await page.evaluate(() => { window.webDataTest.failNext['webData:user'] = 'Cannot read personal data'; });
|
||||
await refresh.click();
|
||||
await section.getByRole('alert').filter({ hasText: 'Cannot read personal data' }).waitFor();
|
||||
assert.equal(await refresh.isEnabled(), true);
|
||||
await refresh.click();
|
||||
await settle();
|
||||
assert.equal(await section.getByRole('alert').count(), 0);
|
||||
await page.evaluate(() => { window.webDataTest.failNext['removeCookie:user'] = 'Cannot remove this cookie'; });
|
||||
const unnamed = section.getByRole('button', { name: 'Remove cookie from another.example at /settings', exact: true });
|
||||
await unnamed.click();
|
||||
await section.getByRole('alert').filter({ hasText: 'Cannot remove this cookie' }).waitFor();
|
||||
assert.equal(await unnamed.isEnabled(), true);
|
||||
await unnamed.click();
|
||||
await settle();
|
||||
assert.equal(await unnamed.count(), 0);
|
||||
assert.equal(await section.getByRole('alert').count(), 0);
|
||||
assert.deepEqual(await page.evaluate(() => window.webDataTest.snapshot.tabs.map(tab => tab.id)), ['open-tab']);
|
||||
assert.equal(await page.evaluate(() => window.webDataTest.calls.some(item => ['closeTab', 'clearData'].includes(item.operation))), false);
|
||||
|
||||
await mkdir('.audit/cards-2026-10-08-next', { recursive: true });
|
||||
await page.setViewportSize({ width: 360, height: 800 });
|
||||
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);
|
||||
assert.equal(await page.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), theme === 'light' ? '#f3f3f3' : '#141414');
|
||||
for (const dataType of ['cookies', 'history']) {
|
||||
await selectKind(dataType);
|
||||
await section.scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: `.audit/cards-2026-10-08-next/browser-web-data-${dataType}-${theme}.png` });
|
||||
const overflow = await section.evaluate(node => {
|
||||
const elements = [node, node.querySelector('.entries'), ...node.querySelectorAll('input, select, button')];
|
||||
return elements.filter(element => element.scrollWidth > element.clientWidth + 1).map(element => ({ tag: element.tagName, className: element.className, width: element.clientWidth, scrollWidth: element.scrollWidth }));
|
||||
});
|
||||
assert.deepEqual(overflow, [], `${dataType} fits the narrow ${theme} settings view`);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
|
||||
const controls = await section.locator('input,select,button').evaluateAll(nodes => nodes.map(node => {
|
||||
const rect = node.getBoundingClientRect(), style = getComputedStyle(node);
|
||||
return { width: rect.width, height: rect.height, radius: parseFloat(style.borderRadius) };
|
||||
}));
|
||||
assert.ok(controls.every(control => control.height >= 28 && control.radius > 0));
|
||||
await filter.focus();
|
||||
await page.keyboard.press('Tab');
|
||||
assert.equal(await refresh.evaluate(node => node === document.activeElement), true);
|
||||
assert.notEqual(await refresh.evaluate(node => getComputedStyle(node).outlineStyle), 'none');
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: cookie/history lists and removal, filters, profile isolation, stale success/error/removal guards, recovery, open-tab preservation, and 360px controls in both themes.');
|
||||
} catch (error) {
|
||||
console.error(await page.locator('body').innerText());
|
||||
console.error('Page errors:', errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,149 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await mkdir('output/editor-clipboard-checklist', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
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 = '# Clipboard and tasks\n\n- [ ] CCNA lab\n- [x] CCNA course\n\nPaste here.\n';
|
||||
const reset = async () => page.evaluate(source => {
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.indexOf('CCNA lab') } });
|
||||
window.__CM__.focus();
|
||||
}, source);
|
||||
const count = () => page.locator('.writer-checkbox').count();
|
||||
const clipboard = '<html><body><!--StartFragment--><table><thead><tr><th>Ticker</th><th>Name</th></tr></thead><tbody><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></tbody></table><!--EndFragment--></body></html>';
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
|
||||
for (const width of [1440, 600]) {
|
||||
if (width === 600) {
|
||||
await page.getByRole('button', { name: 'Files', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
|
||||
}
|
||||
await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 });
|
||||
await reset();
|
||||
assert.equal(await count(), 2, 'Caret at task text keeps both checkboxes');
|
||||
await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-task-text.png` });
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
assert.equal(await count(), 1, 'ArrowLeft from text reveals the marker');
|
||||
await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-task-marker.png` });
|
||||
await page.keyboard.press('Home');
|
||||
assert.equal(await count(), 1, 'Home keeps the marker editable');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('Delete');
|
||||
await page.keyboard.type('x');
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[x\] CCNA lab/);
|
||||
await page.keyboard.press('Home');
|
||||
for (let i = 0; i < 6; i++) await page.keyboard.press('ArrowRight');
|
||||
assert.equal(await count(), 2, 'Leaving the marker restores the checkbox');
|
||||
await page.keyboard.type('New ');
|
||||
assert.equal(await count(), 2, 'Typing task text keeps the checkbox');
|
||||
await page.locator('.writer-checkbox').first().click();
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /- \[ \] New CCNA lab/);
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ selection: { anchor: view.state.sliceDoc().indexOf('Paste here.') } }); view.focus();
|
||||
});
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).evaluate((node, html) => {
|
||||
const data = new DataTransfer(); data.setData('text/html', html); data.setData('text/plain', 'Ticker\tName\nADBE.US\tAdobe\nADSK.US\tAutodesk');
|
||||
node.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
|
||||
}, clipboard);
|
||||
await page.locator('.live-writer table').waitFor();
|
||||
const pasted = await page.evaluate(() => window.__CM__.state.sliceDoc());
|
||||
assert.doesNotMatch(pasted, /Fragment|<!--|-->/);
|
||||
assert.match(pasted, /\| Ticker \| Name \|/);
|
||||
assert.equal(await page.locator('.live-writer table tr').count(), 3);
|
||||
await page.screenshot({ path: `output/editor-clipboard-checklist/${mode}-${width}-table-paste.png` });
|
||||
if (width === 600) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: keyboard marker entry, task text, checkbox toggle, Windows HTML clipboard fragments, both themes and narrow layouts.');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: 'output/editor-clipboard-checklist/failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,135 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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 contents = () => page.evaluate(() => window.__CM__.state.sliceDoc());
|
||||
const cursor = () => page.evaluate(() => window.__CM__.state.selection.main.head);
|
||||
async function select(anchor, head = anchor) {
|
||||
await page.evaluate(({ anchor, head }) => {
|
||||
window.__CM__.dispatch({ selection: { anchor, head }, scrollIntoView: true });
|
||||
window.__CM__.focus();
|
||||
}, { anchor, head });
|
||||
}
|
||||
for (const block of ["```js\nconst value = 123;\nsecond line\n```", "~~~text\nconst value = 123;\nsecond line\n~~~", " const value = 123;\n second line"]) {
|
||||
const original = `Above.\n\n${block}\n\nBelow.\n`;
|
||||
await page.evaluate(value => {
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } });
|
||||
}, original);
|
||||
await page.locator(".writer-code-line").first().click();
|
||||
await page.locator(".writer-code-source").first().waitFor();
|
||||
const position = original.indexOf("123") + 1;
|
||||
await select(position);
|
||||
await page.keyboard.press("Backspace");
|
||||
assert.equal(await contents(), original.slice(0, position - 1) + original.slice(position));
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await contents(), original);
|
||||
await select(position);
|
||||
await page.keyboard.press("Delete");
|
||||
assert.equal(await contents(), original.slice(0, position) + original.slice(position + 1));
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await contents(), original);
|
||||
await select(position);
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await cursor(), position + 1);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
assert.equal(await cursor(), position);
|
||||
await page.keyboard.type("X");
|
||||
assert.equal(await contents(), original.slice(0, position) + "X" + original.slice(position));
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await contents(), original);
|
||||
await select(position - 1, position + 2);
|
||||
await page.keyboard.press("Backspace");
|
||||
const edited = original.slice(0, position - 1) + original.slice(position + 2);
|
||||
assert.equal(await contents(), edited);
|
||||
await select(0);
|
||||
assert.ok((await page.locator(".writer-code-line").allTextContents()).join("\n").includes("const value = ;"));
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, edited);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: Fenced and indented code editing, character deletion, selection deletion, cursor movement, undo, preview and save.");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
await page.screenshot({ path: ".audit/code-blocks-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,138 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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();
|
||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
await writer.waitFor();
|
||||
const dividers = "content\n___\ncontent\n***\n\n---\n\n* * *\n\n_ _ _\n\n- - -\n\nHeading\n---\n\n`___`\n\n```text\n___\n```\n\n ***\n\nEnd\n";
|
||||
await page.evaluate(async value => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } });
|
||||
}, dividers);
|
||||
await page.waitForFunction(() => document.querySelectorAll(".writer-divider").length === 6);
|
||||
assert.equal(await page.getByRole("separator").and(page.locator(".writer-divider")).count(), 6);
|
||||
const dividerStyle = await page.locator(".writer-divider").first().evaluate(node => ({
|
||||
width: node.getBoundingClientRect().width,
|
||||
lineWidth: node.parentElement.getBoundingClientRect().width,
|
||||
border: getComputedStyle(node, "::after").borderTopWidth,
|
||||
color: getComputedStyle(node, "::after").borderTopColor,
|
||||
}));
|
||||
assert.ok(Math.abs(dividerStyle.width - dividerStyle.lineWidth) < 2);
|
||||
assert.equal(dividerStyle.border, "1px");
|
||||
assert.notEqual(dividerStyle.color, "rgba(0, 0, 0, 0)");
|
||||
await page.setViewportSize({ width: 1100, height: 900 });
|
||||
await page.screenshot({ path: ".audit/markdown-dividers.png" });
|
||||
|
||||
await page.locator(".writer-divider").first().click();
|
||||
assert.equal(await page.locator(".writer-divider").count(), 5);
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text), "___");
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("Backspace");
|
||||
await page.keyboard.press("Control+Home");
|
||||
assert.equal(await page.locator(".writer-divider").count(), 5);
|
||||
assert.ok((await writer.textContent()).includes("__"));
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+Home");
|
||||
assert.equal(await page.locator(".writer-divider").count(), 6);
|
||||
await page.keyboard.press("ArrowDown");
|
||||
assert.equal(await page.locator(".writer-divider").count(), 5);
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text), "___");
|
||||
await page.keyboard.press("Control+a");
|
||||
assert.equal(await page.locator(".writer-divider").count(), 0);
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), dividers);
|
||||
await page.keyboard.press("Control+Home");
|
||||
assert.equal(await page.locator(".writer-divider").count(), 6);
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, dividers);
|
||||
|
||||
await page.evaluate(() => {
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "Above\n\n ___\n\n> ***\n\nEnd" }, selection: { anchor: 0 } });
|
||||
});
|
||||
assert.equal(await page.locator(".writer-divider").count(), 2);
|
||||
for (const divider of await page.locator(".writer-divider").all()) {
|
||||
assert.ok(await divider.evaluate(node => node.getBoundingClientRect().right <= node.parentElement.getBoundingClientRect().right + 1));
|
||||
}
|
||||
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: Divider syntax, width, source editing, keyboard navigation, selection, undo and save.");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
await page.screenshot({ path: ".audit/markdown-dividers-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,181 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
try {
|
||||
await mkdir('output/round4-editor-menu', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5187');
|
||||
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 menu = () => page.getByRole('menu', { name: 'Markdown text actions', exact: true });
|
||||
async function setSource(value, anchor = 0, head = anchor) {
|
||||
await page.evaluate(({value,anchor,head}) => window.__CM__.dispatch({changes:{from:0,to:window.__CM__.state.doc.length,insert:value},selection:{anchor,head}}), {value,anchor,head});
|
||||
}
|
||||
async function openKeyboard() { await page.locator('.cm-content').focus(); await page.keyboard.press('Shift+F10'); await menu().waitFor(); }
|
||||
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
|
||||
for (const theme of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); }, theme);
|
||||
await setSource('');
|
||||
await page.locator('.cm-line').first().click({button:'right'});
|
||||
await menu().waitFor();
|
||||
for (const label of ['Add link','Add external link','Format','Paragraph','Insert','Paste','Paste as plain text','Select all']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Cut',exact:true}).isDisabled(),true);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Copy',exact:true}).isDisabled(),true);
|
||||
await page.screenshot({path:`output/round4-editor-menu/empty-${theme}.png`});
|
||||
await menu().getByRole('menuitem',{name:'Format',exact:true}).focus();
|
||||
await page.keyboard.press('ArrowRight');
|
||||
const format = page.getByRole('menu',{name:'Format',exact:true});
|
||||
for (const label of ['Bold','Italic','Strikethrough','Highlight','Code','Math','Comment','Clear formatting']) assert.equal(await format.getByRole('menuitem',{name:label,exact:true}).count(),1);
|
||||
await page.keyboard.press('End');
|
||||
assert.equal(await page.getByRole('menuitem',{name:'Comment',exact:true}).evaluate(el=>el===document.activeElement),true);
|
||||
await page.screenshot({path:`output/round4-editor-menu/format-${theme}.png`});
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.locator('.cm-content').evaluate(el=>el===document.activeElement),true);
|
||||
await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Paragraph',exact:true}).click();
|
||||
await page.getByRole('menu',{name:'Paragraph',exact:true}).getByRole('menuitem',{name:'Heading 6',exact:true}).click();
|
||||
assert.equal(await source(),'###### ');
|
||||
await setSource(''); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Insert',exact:true}).click();
|
||||
await page.screenshot({path:`output/round4-editor-menu/insert-${theme}.png`});
|
||||
await page.getByRole('menu',{name:'Insert',exact:true}).getByRole('menuitem',{name:'Code block',exact:true}).click();
|
||||
assert.match(await source(),/^```\nCode\n```/);
|
||||
await setSource(''); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
|
||||
assert.equal(await source(),'[]()');
|
||||
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),1);
|
||||
assert.equal(await page.getByRole('dialog').count(),0);
|
||||
await setSource('label',0,5); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
|
||||
assert.equal(await source(),'[label]()');
|
||||
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),8);
|
||||
await setSource(''); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
|
||||
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
|
||||
await page.screenshot({path:`output/round4-editor-menu/workspace-picker-${theme}.png`});
|
||||
await page.keyboard.press('Enter');
|
||||
await page.getByRole('dialog').waitFor({state:'detached'});
|
||||
assert.equal(await source(),'[[/notes/second.md]]');
|
||||
await setSource('Keep this text'); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
|
||||
await page.getByRole('textbox',{name:'Find a file'}).waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await page.getByRole('dialog').waitFor({state:'detached'});
|
||||
assert.equal(await source(),'Keep this text');
|
||||
await setSource('Populated paragraph\n\n');
|
||||
await page.locator('.cm-line').last().click({button:'right'});
|
||||
await menu().waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await setSource('');
|
||||
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
|
||||
await page.setViewportSize({width:560,height:420});
|
||||
await page.locator('.cm-scroller').click({button:'right',position:{x:60,y:180}});
|
||||
await menu().waitFor();
|
||||
const box = await menu().boundingBox(); assert.ok(box.x>=8 && box.y>=8 && box.x+box.width<=552 && box.y+box.height<=412);
|
||||
await page.screenshot({path:`output/round4-editor-menu/narrow-${theme}.png`});
|
||||
await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({width:1440,height:1000});
|
||||
await page.getByRole('button',{name:'Show outline',exact:true}).click();
|
||||
}
|
||||
await page.getByRole('group',{name:'Editor layout'}).hover();
|
||||
await page.getByRole('button',{name:'IDE',exact:true}).click();
|
||||
await page.locator('.monaco-editor').waitFor();
|
||||
await page.locator('.monaco-editor textarea').focus();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await menu().waitFor();
|
||||
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
|
||||
assert.equal(await page.getByRole('dialog').count(),0);
|
||||
await page.locator('.monaco-editor textarea').focus();
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.press('Backspace');
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
|
||||
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.getByRole('dialog').waitFor({state:'detached'});
|
||||
await page.screenshot({path:'output/round4-editor-menu/ide-links.png'});
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: empty and whitespace Writer menus, full submenus, disabled actions, links, picker, selection, keyboard focus, two themes, narrow viewport and IDE.');
|
||||
} catch(error) {
|
||||
await page.screenshot({path:'output/round4-editor-menu/failure.png'});
|
||||
console.error('Browser errors:',errors); throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,182 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await mkdir("output/editor-october12", { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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();
|
||||
async function editor() {
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
}
|
||||
await editor();
|
||||
const source = "# First section\n\nParent text.[^long]\n\n## Child section\n\nChild content.\n\n### Nested section\n\nNested content.\n\n# Second section\n\nSecond content.[^long]\n\n## Last section\n\nFinal content.\n\n[^long]: A **bold** footnote.\n Continued on another line.\n";
|
||||
async function setSource(value) {
|
||||
await page.evaluate(value => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } }), value);
|
||||
}
|
||||
await setSource(source);
|
||||
const structural = "# Parent\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\n```md\n# Not a heading\n```\n\n## Child\n\nText\n\n# Next\n\nNext text\n";
|
||||
await setSource(structural);
|
||||
assert.equal(await page.getByRole("button", { name: "Collapse Not a heading", exact: true }).count(), 0);
|
||||
await page.getByRole("button", { name: "Collapse Parent", exact: true }).click();
|
||||
assert.equal(await page.locator(".writer-table").count(), 0);
|
||||
assert.equal(await page.getByRole("button", { name: "Collapse Child", exact: true }).count(), 0);
|
||||
await page.getByRole("button", { name: "Expand Parent", exact: true }).click();
|
||||
await page.locator(".writer-table").waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), structural);
|
||||
await setSource("Setext heading\n==============\n\nBody\n\n# Next\n\nNext body");
|
||||
await page.getByRole("button", { name: "Collapse Setext heading", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Setext heading", exact: true }).click();
|
||||
await setSource(source);
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
|
||||
assert.equal(await page.locator(".cm-content").textContent().then(text => text.includes("Child content.")), false);
|
||||
await page.getByRole("button", { name: "Collapse First section", exact: true }).click();
|
||||
assert.equal(await page.getByRole("button", { name: "Expand Child section", exact: true }).count(), 0);
|
||||
await page.getByRole("button", { name: "Expand First section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Collapse Child section');
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), source);
|
||||
|
||||
// Insert from the real shared menu and edit the selected definition.
|
||||
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 20 } }); window.__CM__.focus(); });
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await page.getByRole("menuitem", { name: "Insert", exact: true }).hover();
|
||||
await page.getByRole("menuitem", { name: "Footnote", exact: true }).click();
|
||||
await page.keyboard.type("New footnote");
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /\[\^1\]: New footnote/);
|
||||
await page.keyboard.press("Control+z");
|
||||
await setSource(source);
|
||||
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await page.evaluate(async theme => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode: theme }); }, theme);
|
||||
await page.setViewportSize({ width: 760, height: 900 });
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
|
||||
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
|
||||
const bounds = button.getBoundingClientRect();
|
||||
const pane = button.closest('.cm-scroller').getBoundingClientRect();
|
||||
return bounds.left >= pane.left && bounds.right <= pane.right;
|
||||
}));
|
||||
await page.screenshot({ path: `output/editor-october12/writer-${theme}-narrow.png` });
|
||||
await page.keyboard.press("Space");
|
||||
const borders = await page.locator(".writer-heading").evaluateAll(headings => headings.map(heading => getComputedStyle(heading).borderBottomWidth));
|
||||
assert.ok(borders.every(border => border === "0px"));
|
||||
assert.ok(await page.locator(".writer-heading").first().evaluate(heading => parseFloat(getComputedStyle(heading).paddingTop) > 8));
|
||||
await page.getByRole("group", { name: "Document view" }).hover();
|
||||
await page.getByRole("button", { name: "Read", exact: true }).click();
|
||||
await page.locator(".md-footnotes").waitFor();
|
||||
assert.equal(await page.locator(".md-footnote-ref").count(), 2);
|
||||
assert.equal(await page.locator(".md-footnotes li").count(), 1);
|
||||
assert.equal(await page.locator(".md-footnote-back").count(), 2);
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
|
||||
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
|
||||
const bounds = button.getBoundingClientRect();
|
||||
const pane = button.closest('.reading').parentElement.getBoundingClientRect();
|
||||
return bounds.left >= pane.left && bounds.right <= pane.right;
|
||||
}));
|
||||
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), false);
|
||||
await page.screenshot({ path: `output/editor-october12/reader-${theme}-narrow.png` });
|
||||
await page.keyboard.press("Space");
|
||||
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), true);
|
||||
await page.getByRole("button", { name: "Collapse Last section", exact: true }).click();
|
||||
await page.locator(".md-footnote-ref a").first().click();
|
||||
assert.equal(await page.locator(".md-footnotes").isVisible(), true);
|
||||
await page.locator(".md-footnote-back").first().click();
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), "rs-fnref-1-1");
|
||||
await page.getByRole("group", { name: "Document view" }).hover();
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
|
||||
await editor();
|
||||
}
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, source);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: footnote menu, Writer edits, Reader numbering and backlinks, nested folding, keyboard toggles, source preservation, light/dark narrow screenshots.");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
await page.screenshot({ path: "output/editor-october12/failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
␍
|
||||
@@ -0,0 +1,209 @@
|
||||
// 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 svg = '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="#486077"/><circle cx="320" cy="180" r="110" fill="#93cab5"/></svg>';
|
||||
files.set("images/picture (#1).svg", btoa(svg));
|
||||
files.set("images/replacement.svg", btoa(svg));
|
||||
files.set("notes/welcome.md", "Above.\n\nBelow.\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_write_bytes") {
|
||||
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
|
||||
if (window.__TEST__.failWrite) throw new Error("Image write failed");
|
||||
files.set(args.rel, args.base64); return;
|
||||
}
|
||||
if (command === "workspace_read_data_url") {
|
||||
if (!files.has(args.rel)) throw new Error("missing image");
|
||||
return "data:image/svg+xml;base64," + files.get(args.rel);
|
||||
}
|
||||
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_reveal") return;
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
|
||||
async function writer() {
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
}
|
||||
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
|
||||
async function dragFromTree(selector = ".cm-content", cancel = false) {
|
||||
const row = page.locator('[data-tree-rel="images/picture (#1).svg"]');
|
||||
const from = await row.boundingBox(), to = await page.locator(selector).boundingBox();
|
||||
await page.mouse.move(from.x + 60, from.y + from.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to.x + 40, to.y + 10, { steps: 12 });
|
||||
await page.getByText("Insert image", { exact: true }).waitFor();
|
||||
assert.equal(await page.locator(".image-drop-target").count(), 1);
|
||||
if (cancel) await page.keyboard.press("Escape");
|
||||
await page.mouse.up();
|
||||
}
|
||||
async function imageMenu() {
|
||||
await page.locator(".md-image-frame").first().click({ button: "right" });
|
||||
await page.getByRole("menu", { name: "Image actions" }).waitFor();
|
||||
}
|
||||
try {
|
||||
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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" }).click();
|
||||
await writer();
|
||||
await page.locator('[data-tree-rel="images"]').click();
|
||||
await dragFromTree();
|
||||
await page.locator(".md-image-frame img").waitFor();
|
||||
const linked = await source();
|
||||
assert.ok(linked.startsWith("\n\nAbove."), linked);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => ["workspace_write_bytes", "workspace_rename"].includes(c.command)).length), 0);
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
|
||||
// Neither caret movement nor selection exposes an image's Markdown.
|
||||
await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: 0, head: 38 } }));
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
|
||||
await page.locator(".md-image-frame img").click();
|
||||
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await page.getByRole("menu", { name: "Image actions" }).waitFor();
|
||||
assert.equal(await page.locator(".md-image-frame.is-selected").count(), 1);
|
||||
await page.screenshot({ path: ".audit/image-context-menu.png" });
|
||||
await page.getByRole("menuitem", { name: "Copy Markdown", exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => navigator.clipboard.readText()), "");
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Copy image", exact: true }).click();
|
||||
await page.waitForFunction(async () => (await navigator.clipboard.read()).some(item => item.types.includes("image/png")));
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Show in Explorer", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "workspace_reveal" && c.args.rel === "images/picture (#1).svg"));
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Remove image", exact: true }).click();
|
||||
assert.ok(!(await source()).includes("picture%20"));
|
||||
assert.ok(await page.evaluate(() => window.__TEST__.files.has("images/picture (#1).svg")));
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await source(), linked);
|
||||
|
||||
await page.locator(".md-image-frame").hover();
|
||||
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
|
||||
await page.locator(".cm-line").filter({ hasText: "picture%20" }).waitFor();
|
||||
assert.equal(await page.locator(".md-image-frame img").count(), 1);
|
||||
await page.getByRole("button", { name: "Hide image source", exact: true }).click();
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "picture%20" }).count(), 0);
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Swap image…", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Image path relative to this note, or https URL" }).fill("../images/replacement.svg");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__CM__.state.doc.toString().includes("replacement.svg"));
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "replacement.svg" }).count(), 0);
|
||||
await imageMenu();
|
||||
await page.getByRole("menuitem", { name: "Open in new tab", exact: true }).click();
|
||||
await page.getByRole("tab", { name: "replacement.svg", exact: true }).waitFor();
|
||||
await page.getByRole("tab", { name: /welcome.md/ }).click();
|
||||
await writer();
|
||||
|
||||
const beforeCancel = await source();
|
||||
await dragFromTree(".cm-content", true);
|
||||
assert.equal(await source(), beforeCancel);
|
||||
assert.equal(await page.locator(".image-drop-target").count(), 0);
|
||||
// Inline images remain independently selectable without hiding adjacent prose.
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "Before  between ![[../images/replacement.svg]] after.\n" }, selection: { anchor: 0 } });
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelectorAll(".md-image-frame").length === 2);
|
||||
assert.ok((await page.locator(".cm-content").innerText()).includes("Before"));
|
||||
assert.ok(!(await page.locator(".cm-content").innerText()).includes("![]"));
|
||||
await page.locator(".md-image-frame img").nth(1).click();
|
||||
await page.keyboard.press("Delete");
|
||||
assert.equal(await source(), "Before  between after.\n");
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.ok((await source()).includes("![[../images/replacement.svg]]"));
|
||||
// Reference-image editing affects only the selected embed, not its definition.
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "![Reference][pic]\n\nBelow.\n\n[pic]: ../images/replacement.svg\n" }, selection: { anchor: 0 } });
|
||||
});
|
||||
await page.locator(".md-image-frame").hover();
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
|
||||
await page.getByRole("button", { name: "Edit image source", exact: true }).click();
|
||||
await page.locator(".cm-line").filter({ hasText: "![Reference]" }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await page.locator(".cm-line").filter({ hasText: "![Reference]" }).count(), 0);
|
||||
// The same navigator drag works in the source editor.
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await dragFromTree(".monaco-editor .view-lines");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").includes("picture%20"));
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_write_bytes").length), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Navigator image drag, hidden source, selection, copy, swap, remove, open, reveal, cancel and source mode passed.");
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: ".audit/image-navigation-failure.png" });
|
||||
console.error(errors); throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,250 @@
|
||||
// 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_write_bytes") {
|
||||
if (window.__TEST__.delay) await new Promise(resolve => { window.__TEST__.resume = resolve; });
|
||||
if (window.__TEST__.failWrite) throw new Error("Image write failed");
|
||||
files.set(args.rel, args.base64); return;
|
||||
}
|
||||
if (command === "workspace_read_data_url") {
|
||||
if (!files.has(args.rel)) throw new Error("missing image");
|
||||
return "data:image/svg+xml;base64," + files.get(args.rel);
|
||||
}
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
async function openNote(name = "welcome.md") {
|
||||
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(".cm-content").waitFor();
|
||||
}
|
||||
async function source() {
|
||||
return page.evaluate(() => window.__CM__.state.doc.toString());
|
||||
}
|
||||
async function save() {
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForTimeout(100);
|
||||
return page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
|
||||
}
|
||||
async function drop(count = 1, selector = ".cm-content") {
|
||||
await page.locator(selector).evaluate((element, count) => {
|
||||
const data = new DataTransfer();
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="600"><rect width="900" height="600" fill="#536174"/><circle cx="450" cy="260" r="140" fill="#99c9b5"/><text x="450" y="480" text-anchor="middle" font-size="40" fill="white">Image drop test</text></svg>';
|
||||
for (let i = 0; i < count; i++) data.items.add(new File([svg], "picture.svg", { type: "" }));
|
||||
const rect = element.getBoundingClientRect();
|
||||
element.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, dataTransfer: data, clientX: rect.left + 20, clientY: rect.top + 8 }));
|
||||
}, count);
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await openNote();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "First paragraph.\n\nLast paragraph.\n" } });
|
||||
});
|
||||
const original = await source();
|
||||
const acceptsDrag = await page.locator(".cm-content").evaluate(element => {
|
||||
const data = new DataTransfer(); data.items.add(new File(["x"], "test.svg"));
|
||||
const event = new DragEvent("dragover", { bubbles: true, cancelable: true, dataTransfer: data });
|
||||
element.dispatchEvent(event); return event.defaultPrevented;
|
||||
});
|
||||
assert.ok(acceptsDrag);
|
||||
await drop(2);
|
||||
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 2);
|
||||
await page.locator(".md-image-frame img").first().waitFor();
|
||||
assert.equal(await page.locator(".md-image-frame img").count(), 2);
|
||||
const inserted = await source();
|
||||
assert.ok(inserted.indexOf("![]") < inserted.indexOf("First paragraph."), "drop inserts at pointer, not stale cursor");
|
||||
const paths = [...inserted.matchAll(/!\[\]\(([^)]+)\)/g)].map(match => match[1]);
|
||||
assert.notEqual(paths[0], paths[1]);
|
||||
assert.ok(paths.every(path => path.startsWith("../attachments/")));
|
||||
assert.equal(await save(), inserted);
|
||||
|
||||
// Selecting and editing Markdown leaves the image visible and updates its alt text.
|
||||
await page.locator(".md-image-frame").first().hover();
|
||||
await page.getByRole("button", { name: "Edit image source", exact: true }).first().click();
|
||||
assert.equal(await page.locator(".md-image-frame img").count(), 2);
|
||||
assert.ok((await page.locator(".cm-line").allTextContents()).some(line => line.includes(paths[0])));
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__, from = view.state.doc.toString().indexOf("![]") + 2;
|
||||
view.dispatch({ changes: { from, insert: "Edited alt" }, selection: { anchor: from + 10 } });
|
||||
});
|
||||
await page.locator('img[alt="Edited alt"]').waitFor();
|
||||
await page.screenshot({ path: ".audit/images-editing.png" });
|
||||
await page.locator(".md-image-frame").first().hover();
|
||||
await page.getByRole("button", { name: "Zoom in", exact: true }).first().click();
|
||||
const zoom = page.getByRole("dialog", { name: "Image zoom" });
|
||||
await zoom.waitFor();
|
||||
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
|
||||
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "100%");
|
||||
await zoom.getByRole("button", { name: "Zoom in", exact: true }).click();
|
||||
assert.equal(await zoom.locator(".image-lightbox-scale").textContent(), "200%");
|
||||
await page.screenshot({ path: ".audit/images-zoom.png" });
|
||||
await zoom.getByRole("button", { name: "Fit image", exact: true }).click();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await page.getByRole("dialog").count(), 0);
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Zoom in");
|
||||
|
||||
// Undo the alt edit and the complete drop as separate operations.
|
||||
await page.locator(".cm-line").filter({ hasText: "![Edited alt]" }).click();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await source(), original);
|
||||
await page.keyboard.press("Control+y");
|
||||
assert.equal(await source(), inserted);
|
||||
|
||||
// Type and move the cursor during a slow import; the drop follows its original position.
|
||||
await page.evaluate(() => { window.__TEST__.delay = true; });
|
||||
await drop();
|
||||
await page.waitForFunction(() => !!window.__TEST__.resume);
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: 0, insert: "Typed while saving.\n\n" }, selection: { anchor: view.state.doc.length } });
|
||||
window.__TEST__.delay = false; window.__TEST__.resume(); window.__TEST__.resume = null;
|
||||
});
|
||||
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 3);
|
||||
assert.ok((await source()).startsWith("Typed while saving.\n\n![]"));
|
||||
|
||||
// Typed local image paths load without changing views, including wiki syntax.
|
||||
await page.evaluate(path => {
|
||||
window.__TEST__.files.set("attachments/typed.svg", [...window.__TEST__.files].find(([key]) => key.startsWith("attachments/"))[1]);
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ changes: { from: view.state.doc.length, insert: `\n![[${path}|Wiki image]]\n` }, selection: { anchor: view.state.doc.length } });
|
||||
}, "../attachments/typed.svg");
|
||||
await page.locator('img[alt="Wiki image"]').waitFor();
|
||||
await save();
|
||||
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Edit", exact: true }).focus();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await page.locator(".md-page .md-image-frame").first().hover();
|
||||
await page.locator(".md-page").getByRole("button", { name: "Zoom in", exact: true }).first().click();
|
||||
await page.getByRole("dialog", { name: "Image zoom" }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
// Source mode uses the same drop flow; the batch is one undo step.
|
||||
await page.getByRole("group", { name: "Document view" }).getByRole("button", { name: "Read", exact: true }).focus();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Control+e");
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
window.__MONACO__ = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
});
|
||||
const sourceBefore = await page.evaluate(() => window.__MONACO__.getValue());
|
||||
await drop(2, ".monaco-editor .view-lines");
|
||||
await page.waitForFunction(() => (window.__MONACO__.getValue().match(/!\[\]/g) || []).length === 5);
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), sourceBefore);
|
||||
await page.keyboard.press("Control+y");
|
||||
assert.equal((await save()).match(/!\[\]/g).length, 5);
|
||||
// A failed write leaves source unchanged and surfaces an error.
|
||||
const beforeFailure = await page.evaluate(() => window.__MONACO__.getValue());
|
||||
await page.evaluate(() => { window.__TEST__.failWrite = true; });
|
||||
await drop(1, ".monaco-editor .view-lines");
|
||||
await page.getByText("Image write failed", { exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.getValue()), beforeFailure);
|
||||
await page.evaluate(() => { window.__TEST__.failWrite = false; });
|
||||
|
||||
// File drops over a rendered widget are handled by the editor's capture listener.
|
||||
await page.keyboard.press("Control+e");
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
await drop(1, ".md-image-frame img >> nth=0");
|
||||
await page.waitForFunction(() => (window.__CM__.state.doc.toString().match(/!\[\]/g) || []).length === 6);
|
||||
|
||||
// Switching tabs while a write is pending cannot insert into the new document.
|
||||
await page.evaluate(() => { window.__TEST__.delay = true; });
|
||||
await drop();
|
||||
await page.waitForFunction(() => !!window.__TEST__.resume);
|
||||
await openNote("second.md");
|
||||
await page.evaluate(() => { window.__TEST__.delay = false; window.__TEST__.resume(); });
|
||||
await page.waitForTimeout(100);
|
||||
assert.ok(!(await page.locator(".cm-content").textContent()).includes("attachments/"));
|
||||
// Clipboard images are inserted and remain a single undo operation too.
|
||||
await page.locator(".cm-content").evaluate(element => {
|
||||
const data = new DataTransfer();
|
||||
data.items.add(new File(['<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"/>'], "pasted.svg", { type: "image/svg+xml" }));
|
||||
element.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData: data }));
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector(".md-image-frame img"));
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/second.md").includes("pasted.svg"));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Image drops, unique attachments, live source, zoom, async insertion, source mode and undo passed.");
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: ".audit/images-failure.png" });
|
||||
console.error(errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,152 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdir } 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: 1280, height: 900 }, permissions: ["clipboard-read", "clipboard-write"] });
|
||||
page.setDefaultTimeout(15000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\editor-interactions-smoke";
|
||||
const files = new Map([
|
||||
["note.md", "# Stack\n\nHardware can be reused.\nAssume speeds of 1 Gb/s.\n\n## Hardware\n\n### Router\n\n- [ ] First task\n- [ ] Second task\n\n[Local](other.md) and [Web](https://example.com) and [[other|Wiki]]\n\n```sh\npnpm install --frozen-lockfile\npnpm check\npnpm test\n```\n\n" + Array.from({ length: 80 }, (_, i) => `Paragraph ${i}.\n\n`).join("") + "```js\nconst preserve = 42;\nconsole.log(preserve);\n```\n"],
|
||||
["other.md", "# Other document\n\nKeep the original tab.\n"],
|
||||
]);
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
let sequence = 0;
|
||||
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
|
||||
window.editorTest = { files, calls: [], emit };
|
||||
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.editorTest.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") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "editor-interactions-smoke", 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") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".runestone/")).map(path => ({ name: path, rel_path: path, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:opener|open_url" || command.startsWith("spelling_menu_")) return;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
async function writer() {
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.writerView = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
}
|
||||
async function top() {
|
||||
await writer();
|
||||
await page.evaluate(() => { window.writerView.dispatch({ selection: { anchor: 0 } }); window.writerView.scrollDOM.scrollTop = 0; });
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.locator('[data-tree-rel="note.md"]').dblclick();
|
||||
await writer();
|
||||
const code = page.locator(".writer-code-line").filter({ hasText: "pnpm install" });
|
||||
await code.scrollIntoViewIfNeeded();
|
||||
const points = await page.evaluate(() => {
|
||||
const view = window.writerView, from = view.state.doc.toString().indexOf("pnpm install");
|
||||
return { from: view.coordsAtPos(from), to: view.coordsAtPos(from + 12) };
|
||||
});
|
||||
await page.mouse.move(points.from.left + 1, (points.from.top + points.from.bottom) / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(points.to.left, (points.to.top + points.to.bottom) / 2, { steps: 8 });
|
||||
await page.mouse.up();
|
||||
assert.match(await page.evaluate(() => { const view = window.writerView; return view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to); }), /pnpm install/);
|
||||
await page.getByRole("button", { name: "Copy code", exact: true }).first().click();
|
||||
assert.equal((await page.evaluate(() => navigator.clipboard.readText())).replace(/\r\n/g, "\n"), "pnpm install --frozen-lockfile\npnpm check\npnpm test\n");
|
||||
console.log("PASS: first drag selects code and the copy button copies only the code body");
|
||||
|
||||
await page.evaluate(() => { const view = window.writerView; view.dispatch({ selection: { anchor: view.state.doc.toString().indexOf("preserve =") + 5 }, scrollIntoView: true }); view.focus(); });
|
||||
await page.keyboard.type("X");
|
||||
await page.waitForTimeout(250);
|
||||
const saved = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
|
||||
assert.ok(saved.scroll > 1000);
|
||||
await page.locator('[data-tree-rel="other.md"]').dblclick();
|
||||
await writer();
|
||||
await page.getByRole("tab", { name: "note.md", exact: true }).click();
|
||||
await writer();
|
||||
await page.waitForTimeout(250);
|
||||
const restored = await page.evaluate(() => ({ head: window.writerView.state.selection.main.head, scroll: window.writerView.scrollDOM.scrollTop, doc: window.writerView.state.sliceDoc(), height: window.writerView.scrollDOM.scrollHeight, caret: window.writerView.coordsAtPos(window.writerView.state.selection.main.head) }));
|
||||
assert.equal(restored.head, saved.head);
|
||||
assert.equal(restored.doc, saved.doc);
|
||||
assert.ok(Math.abs(restored.caret.top - saved.caret.top) < 3, JSON.stringify({ saved, restored }));
|
||||
await page.evaluate(() => { window.dispatchEvent(new Event("blur")); window.dispatchEvent(new Event("focus")); });
|
||||
await page.waitForTimeout(150);
|
||||
assert.equal(await page.evaluate(() => window.writerView.state.selection.main.head), saved.head);
|
||||
console.log("PASS: code edit, caret, and scroll survive tab and window focus changes");
|
||||
|
||||
await top();
|
||||
await page.locator('.writer-link[data-href="other.md"]').click({ modifiers: ["Control"] });
|
||||
await page.getByRole("tab", { name: "other.md", exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("tab", { name: "note.md", exact: true }).count(), 1);
|
||||
await page.getByRole("tab", { name: "note.md", exact: true }).click();
|
||||
await top();
|
||||
await page.locator('.writer-link[data-href="https://example.com"]').click({ modifiers: ["Control"] });
|
||||
await page.waitForFunction(() => window.editorTest.calls.some(call => call.command === "plugin:opener|open_url" && call.args.url === "https://example.com"));
|
||||
await page.keyboard.press("Control+e");
|
||||
await page.locator(".monaco-editor").waitFor();
|
||||
const linkPoint = await page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
|
||||
const position = view.getModel().getPositionAt(view.getValue().indexOf("[Local]") + 3);
|
||||
view.revealPositionInCenter(position);
|
||||
view.setPosition(position); view.focus();
|
||||
return position;
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
const point = await page.evaluate(async position => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const view = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected), rect = view.getDomNode().getBoundingClientRect(), coords = view.getScrolledVisiblePosition(position);
|
||||
return { x: rect.left + coords.left + 2, y: rect.top + coords.top + coords.height / 2 };
|
||||
}, linkPoint);
|
||||
await page.keyboard.down("Control"); await page.mouse.click(point.x, point.y); await page.keyboard.up("Control");
|
||||
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.includes("other.md"));
|
||||
console.log("PASS: Writer and IDE Ctrl+click open workspace links while retaining the source tab");
|
||||
|
||||
await page.getByRole("tab", { name: "note.md", exact: true }).click();
|
||||
await page.keyboard.press("Control+e");
|
||||
await top();
|
||||
await mkdir(".audit", { recursive: true });
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => {
|
||||
const { applyAppearance, parseAppearance } = await import("/src/lib/theme/appearance.ts");
|
||||
applyAppearance({ ...parseAppearance(null), mode });
|
||||
}, theme);
|
||||
const writing = await page.locator(".writer-h1").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
|
||||
await page.screenshot({ path: `.audit/editor-typography-${theme}.png` });
|
||||
await page.getByRole("group", { name: "Document view", exact: true }).hover();
|
||||
await page.getByRole("button", { name: "Read", exact: true }).click();
|
||||
const reading = await page.locator(".reading h1:not(.document-title)").first().evaluate(node => { const style = getComputedStyle(node); return { size: style.fontSize, line: style.lineHeight, family: style.fontFamily, weight: style.fontWeight }; });
|
||||
assert.deepEqual(writing, reading);
|
||||
await page.screenshot({ path: `.audit/reader-typography-${theme}.png` });
|
||||
await page.getByRole("group", { name: "Document view", exact: true }).hover();
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).click();
|
||||
await top();
|
||||
}
|
||||
await page.setViewportSize({ width: 640, height: 750 });
|
||||
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
|
||||
await page.screenshot({ path: ".audit/editor-typography-narrow.png" });
|
||||
assert.ok(await page.locator(".cm-content").evaluate(node => node.getBoundingClientRect().width <= node.closest(".cm-scroller").getBoundingClientRect().width + 1));
|
||||
const spelling = await page.evaluate(async () => {
|
||||
const { isSpellingTarget } = await import("/src/lib/editor/spellingMenu.ts");
|
||||
const area = document.createElement("textarea"); area.spellcheck = true; document.body.append(area);
|
||||
const active = isSpellingTarget(area); area.readOnly = true; const readOnly = isSpellingTarget(area); area.remove();
|
||||
return { active, readOnly };
|
||||
});
|
||||
assert.deepEqual(spelling, { active: true, readOnly: false });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: shared heading typography in both themes, narrow Writer, and textarea spelling target");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,207 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } 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(10000);
|
||||
const errors = [];
|
||||
const showcase = await readFile(new URL("../../../fixtures/reader-showcase.md", import.meta.url), "utf8");
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
await page.getByRole("tab", { selected: true }).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Source mode", exact: true }).click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
async function contents() {
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
|
||||
});
|
||||
}
|
||||
async function waitForText(text) {
|
||||
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
|
||||
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
|
||||
}
|
||||
async function focusEditor() {
|
||||
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
|
||||
}
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await quickOpen("welcome.md");
|
||||
const source = "First paragraph.\n\nSecond paragraph.\n";
|
||||
await page.evaluate(async value => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
editor.setValue(value);
|
||||
editor.setSelection(new monaco.Selection(1, 1, 1, 6)); editor.focus();
|
||||
}, source);
|
||||
const menu = page.getByRole("menu", { name: "Markdown text actions", exact: true });
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.waitFor();
|
||||
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Bold", exact: true }).click();
|
||||
await waitForText("**First** paragraph.\n\nSecond paragraph.\n");
|
||||
await page.keyboard.press("Control+z"); await waitForText(source);
|
||||
await page.getByRole("tab", { selected: true }).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Writing mode", exact: true }).click();
|
||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
await writer.click(); await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Control+Shift+ArrowRight");
|
||||
await page.keyboard.press("Shift+F10"); await menu.waitFor();
|
||||
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Italic", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "*First* paragraph.\n\nSecond paragraph.\n");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Heading 2", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("## First paragraph."));
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Table", exact: true }).click();
|
||||
await page.locator(".live-writer table").waitFor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Control+Shift+ArrowRight");
|
||||
// Mouse invocation must preserve the selection, too.
|
||||
await page.locator(".cm-line").filter({ hasText: "First paragraph." }).click({ button: "right", position: { x: 12, y: 10 } });
|
||||
await menu.waitFor();
|
||||
await menu.getByRole("menuitem", { name: "Format", exact: true }).hover();
|
||||
await menu.getByRole("menuitem", { name: "Highlight", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("==First== paragraph."));
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.locator(".writer-highlight").waitFor();
|
||||
assert.equal(await page.locator(".writer-highlight").textContent(), "First");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Insert", exact: true }).hover();
|
||||
await page.screenshot({ path: ".audit/markdown-insert-menu.png" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.setViewportSize({ width: 760, height: 600 });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
await writer.focus();
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paragraph", exact: true }).focus();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Bullet list");
|
||||
const rect = await menu.getByRole("menu", { name: "Paragraph", exact: true }).boundingBox();
|
||||
assert.ok(rect.x >= 0 && rect.y >= 0 && rect.x + rect.width <= 760 && rect.y + rect.height <= 600);
|
||||
await page.screenshot({ path: ".audit/markdown-paragraph-menu.png" });
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), "Paragraph");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Control+Home");
|
||||
await page.keyboard.press("Control+Shift+ArrowRight");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Add external link", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "External link URL" }).fill("https://example.com/a(b)");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[First](https://example.com/a%28b%29) paragraph."));
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Extract current selection…", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Extract selection to a new note (workspace relative path)" }).fill("notes/extracted.md");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("[[/notes/extracted.md|First]] paragraph."));
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/extracted.md")), "First\n");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.context().grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await page.evaluate(() => navigator.clipboard.writeText("Pasted"));
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector(".cm-content")?.textContent.includes("Pasted paragraph."));
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md").startsWith("Pasted paragraph."));
|
||||
await page.evaluate(() => { navigator.clipboard.readText = () => new Promise(resolve => { window.__finishPaste = resolve; }); });
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await menu.getByRole("menuitem", { name: "Paste as plain text", exact: true }).click();
|
||||
await writer.focus(); await page.keyboard.press("End"); await page.keyboard.type(" kept");
|
||||
await page.evaluate(async () => { window.__finishPaste("STALE"); await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); });
|
||||
assert.ok(!(await writer.textContent()).includes("STALE"));
|
||||
assert.ok((await writer.textContent()).includes("kept"));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: Markdown menus in source/writing modes, selection retention, formatting, paragraph conversion, table insertion, undo, keyboard navigation, narrow viewport, links, extraction, clipboard and stale-selection guards.");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
|
||||
await page.screenshot({ path: ".audit/markdown-menu-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,112 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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/.vite/deps/@codemirror_view.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
for (const count of [3, 1000, 5000]) {
|
||||
const result = await page.evaluate(async count => {
|
||||
const { EditorView } = await import("/node_modules/.vite/deps/@codemirror_view.js");
|
||||
const view = window.__CM__;
|
||||
const source = Array.from({ length: count }, (_, i) => "## Heading " + i + "\n\n**Bold** and *italic*\n\n").join("");
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "" } });
|
||||
view.focus();
|
||||
const clipboardData = new DataTransfer();
|
||||
clipboardData.setData("text/plain", source);
|
||||
view.contentDOM.dispatchEvent(new ClipboardEvent("paste", { bubbles: true, cancelable: true, clipboardData }));
|
||||
view.dispatch({ selection: { anchor: 0 } });
|
||||
const { forceParsing, syntaxTree } = await import("/node_modules/.vite/deps/@codemirror_language.js");
|
||||
forceParsing(view, view.state.doc.length, 5000);
|
||||
const nodes = [];
|
||||
syntaxTree(view.state).iterate({ enter(node) { if (node.name === "StrongEmphasis") nodes.push(node.from); } });
|
||||
const marks = [];
|
||||
for (const set of view.state.facet(EditorView.decorations)) {
|
||||
if (typeof set !== "function") set.between(0, view.state.doc.length, (from, to, decoration) => { if (decoration.spec.class === "writer-strong") marks.push(from); });
|
||||
}
|
||||
return { correctSource: view.state.sliceDoc() === source, nodes: nodes.length, marks: marks.length };
|
||||
}, count);
|
||||
console.log({ count, ...result });
|
||||
assert.equal(result.correctSource, true);
|
||||
assert.equal(result.nodes, count);
|
||||
assert.equal(result.marks, count);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,145 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function open(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();
|
||||
}
|
||||
async function writer() {
|
||||
await page.locator('.cm-content').waitFor();
|
||||
return page.evaluate(async () => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
|
||||
return window.__WRITER__.state.sliceDoc();
|
||||
});
|
||||
}
|
||||
async function expectWriter(expected) {
|
||||
await writer();
|
||||
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expectedLength: expected.length, actualLength: (await writer()).length, errors }); throw error; }
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5173');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
const formatted = '# Copied heading\n\n## Links\n\n[Reference](https://example.com) and [[second|Another note]]\n\n**Bold**, *italic*, and `code`.\n\n- A list item\n';
|
||||
await page.evaluate(text => { window.__TEST__.files.set('notes/source.md', text); window.__TEST__.files.set('notes/pasted.md', ''); }, formatted);
|
||||
await open('source.md');
|
||||
await writer();
|
||||
await page.locator('.cm-content').click();
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.press('Control+c');
|
||||
await open('pasted.md');
|
||||
await writer();
|
||||
for (let iteration = 0; iteration < 12; iteration++) {
|
||||
await page.locator('.cm-content').click();
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.press('Backspace');
|
||||
await expectWriter('');
|
||||
await page.keyboard.press('Control+v');
|
||||
await expectWriter(formatted);
|
||||
assert.equal(await page.locator('.live-writer .cm-editor').count(), 1, 'One mounted editor');
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('notes/pasted.md').replace(/\r\n?/g, '\n')), formatted);
|
||||
if (iteration === 5) {
|
||||
await page.keyboard.press('Control+e');
|
||||
await page.locator('.monaco-editor textarea').waitFor();
|
||||
await page.keyboard.press('Control+e');
|
||||
await expectWriter(formatted);
|
||||
}
|
||||
await open('second.md');
|
||||
await writer();
|
||||
await page.getByRole('tab', { name: 'pasted.md', exact: true }).click();
|
||||
await expectWriter(formatted);
|
||||
}
|
||||
// Clipboard formats can use different line endings than the destination.
|
||||
for (const lineBreak of ['\n', '\r\n', '\r']) {
|
||||
await page.evaluate(({ text, lineBreak }) => {
|
||||
const view = window.__WRITER__;
|
||||
view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } });
|
||||
const clipboardData = new DataTransfer();
|
||||
clipboardData.setData('text/plain', text.replace(/\n/g, lineBreak));
|
||||
view.contentDOM.dispatchEvent(new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData }));
|
||||
}, { text: formatted, lineBreak });
|
||||
await expectWriter(formatted);
|
||||
assert.equal(await page.evaluate(() => window.__WRITER__.state.doc.lines), formatted.split('\n').length);
|
||||
await page.keyboard.press('Control+s');
|
||||
const synchronized = await page.evaluate(async () => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
const model = monaco.editor.getModels().find(model => model.uri.path.endsWith('/pasted.md'));
|
||||
const source = window.__WRITER__.state.doc.sliceString(0, undefined, model.getEOL());
|
||||
return source === model.getValue() && source === window.__TEST__.files.get('notes/pasted.md');
|
||||
});
|
||||
assert.equal(synchronized, true, 'Writer, model, and saved source agree');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: formatted Markdown copied across notes stays exact through 12 paste/delete cycles, saves, tab reopen, IDE reopen, and LF/CRLF/CR clipboard replacement');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,121 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await mkdir("output/editor-october12", { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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.locator('.md-properties').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 original = await page.evaluate(() => window.__CM__.state.sliceDoc());
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.selection.main.head), original.indexOf('\n\n') + 1);
|
||||
await page.locator('.md-properties summary').click();
|
||||
assert.equal(await page.locator('.md-properties').getAttribute('open'), '');
|
||||
assert.match(await page.locator('.md-properties pre').textContent(), /title: Welcome/);
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => {
|
||||
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
applyAppearance({ theme: 'default', mode });
|
||||
}, mode);
|
||||
await page.setViewportSize({ width: 760, height: 900 });
|
||||
await page.screenshot({ path: `output/editor-october12/properties-${mode}-narrow.png` });
|
||||
}
|
||||
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 11 } }); window.__CM__.focus(); });
|
||||
assert.equal(await page.locator('.md-properties').count(), 0);
|
||||
await page.keyboard.type('New ');
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /title: New Welcome/);
|
||||
await page.keyboard.press('Control+z');
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), original);
|
||||
await page.evaluate(() => window.__CM__.dispatch({ selection: { anchor: window.__CM__.state.doc.length } }));
|
||||
await page.locator('.md-properties').waitFor();
|
||||
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 11 } }); window.__CM__.focus(); });
|
||||
await page.getByRole('group', { name: 'Document view' }).hover();
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
await page.locator('.reading .md-properties').waitFor();
|
||||
await page.getByRole('group', { name: 'Document view' }).hover();
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
assert.equal(await page.locator('.writer-preview .md-properties').count(), 0);
|
||||
assert.equal(errors.length, 0, errors.join('\n'));
|
||||
console.log('Properties first-open, editing, undo, saved selection, and both themes passed.');
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
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("sample.txt", "const answer = 42;\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: ["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()].map(name => ({ name, rel_path: name, kind: "file" }))];
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
|
||||
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-surfaces';
|
||||
await mkdir(output, { recursive: true });
|
||||
const report = [];
|
||||
const dismiss = async () => { await page.keyboard.press('Escape'); await page.locator('.rs-menu').waitFor({ state: 'detached' }); };
|
||||
const styles = panel => panel.evaluate(node => {
|
||||
const row = node.querySelector(':scope > button');
|
||||
const a = getComputedStyle(node), b = getComputedStyle(row);
|
||||
return [a.backgroundColor, a.borderRadius, a.padding, b.minHeight, b.padding, b.font];
|
||||
});
|
||||
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();
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.evaluate(async mode => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 800; canvas.height = 600;
|
||||
const c = canvas.getContext('2d');
|
||||
const g = c.createLinearGradient(0, 0, 800, 600);
|
||||
g.addColorStop(0, '#628ba8'); g.addColorStop(1, '#b47796');
|
||||
c.fillStyle = g; c.fillRect(0, 0, 800, 600);
|
||||
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: .15, position: 'center', size: 'cover' } });
|
||||
}, theme);
|
||||
await page.locator('[data-tree-rel="a.md"]').click({ button: 'right' });
|
||||
const reference = await styles(menu('File actions'));
|
||||
await dismiss();
|
||||
const text = page.getByText('Original text.', { exact: true });
|
||||
await text.click({ button: 'right', position: { x: 20, y: 8 } });
|
||||
const writer = menu('Markdown text actions');
|
||||
assert.deepEqual(await styles(writer), reference);
|
||||
for (const name of ['Add link', 'Add external link', 'Format', 'Paragraph', 'Insert', 'Paste', 'Select all']) assert.equal(await item(name).count(), 1);
|
||||
await item('Corrected').waitFor();
|
||||
assert.equal(await item('Spelling').count(), 0, 'Corrections appear directly in the main menu');
|
||||
assert.equal(await writer.locator(':scope > button').first().textContent(), 'Corrected');
|
||||
await page.screenshot({ path: `${output}/writer-menu-${theme}.png` });
|
||||
await item('Corrected').focus(); await page.keyboard.press('Enter');
|
||||
await page.getByText('Corrected text.', { exact: true }).waitFor();
|
||||
await page.keyboard.press('Control+z');
|
||||
await text.waitFor();
|
||||
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 text.click({ button: 'right', position: { x: 20, y: 8 } });
|
||||
await item('Corrected').waitFor();
|
||||
await page.keyboard.press('Home');
|
||||
assert.equal(await item('Corrected').evaluate(node => node === document.activeElement), true);
|
||||
const spellingBounds = await writer.boundingBox();
|
||||
assert.ok(spellingBounds.x >= 8 && spellingBounds.x + spellingBounds.width <= 552);
|
||||
await page.screenshot({ path: `${output}/spelling-narrow-${theme}.png` });
|
||||
await page.keyboard.press('Enter');
|
||||
await page.getByText('Corrected text.', { exact: true }).waitFor();
|
||||
await page.keyboard.press('Control+z');
|
||||
await text.waitFor();
|
||||
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').click({ button: 'right', position: { x: 600, y: 150 } });
|
||||
assert.deepEqual(await styles(writer), reference, 'Blank space uses the same actions');
|
||||
await item('Format').focus(); await page.keyboard.press('ArrowRight');
|
||||
await item('Bold').click();
|
||||
await page.locator('.cm-content').click({ button: 'right', position: { x: 600, y: 150 } });
|
||||
await page.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click();
|
||||
assert.equal(await page.locator('.cm-content').textContent().then(s => s.includes('**')), false, 'Undo reverses the menu edit');
|
||||
const tint = await page.locator('.writer-code-line').first().evaluate(node => getComputedStyle(node).backgroundColor);
|
||||
assert.ok(tint.includes('/ 0.82') || /rgba\(.+, 0\.82\)/.test(tint), `Writer code tint: ${tint}`);
|
||||
await page.screenshot({ path: `${output}/writer-code-${theme}.png` });
|
||||
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
const readingTint = await page.locator('pre.md-code').evaluate(node => getComputedStyle(node).backgroundColor);
|
||||
assert.equal(readingTint, tint, 'Reader and Writer use the same code tint');
|
||||
await page.screenshot({ path: `${output}/reader-code-${theme}.png` });
|
||||
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.locator('.monaco-host').click({ button: 'right', position: { x: 500, y: 400 } });
|
||||
assert.deepEqual(await styles(writer), reference, 'Markdown IDE retains the same menu');
|
||||
await dismiss();
|
||||
await page.locator('[data-tree-rel="sample.txt"]').click();
|
||||
await page.locator('.monaco-host').click({ button: 'right', position: { x: 500, y: 400 } });
|
||||
const code = menu('Code text actions');
|
||||
assert.deepEqual(await styles(code), reference, 'Code IDE uses the host menu');
|
||||
assert.equal(await page.locator('.monaco-menu').count(), 0);
|
||||
await page.screenshot({ path: `${output}/ide-menu-${theme}.png` });
|
||||
await page.getByRole('menuitem', { name: 'Command palette F1', exact: true }).click();
|
||||
const palette = page.locator('.quick-input-widget');
|
||||
await palette.waitFor({ state: 'visible' });
|
||||
const paletteMetrics = () => palette.evaluate(node => {
|
||||
const row = node.querySelector('.monaco-list-row.focused');
|
||||
const field = node.querySelector('.monaco-inputbox');
|
||||
const a = getComputedStyle(row), b = getComputedStyle(field);
|
||||
const probe = document.createElement('div');
|
||||
probe.style.background = 'var(--rs-item-selection-bg)'; probe.style.color = 'var(--rs-item-selection-border)';
|
||||
node.append(probe); const expected = getComputedStyle(probe);
|
||||
const result = { fill: a.backgroundColor, expectedFill: expected.backgroundColor, outline: a.outlineColor, expectedOutline: expected.color, radius: a.borderRadius, inputRadius: b.borderRadius, inputOutline: b.outlineColor, inputOutlineWidth: b.outlineWidth };
|
||||
probe.remove(); return result;
|
||||
});
|
||||
let p = await paletteMetrics();
|
||||
assert.equal(p.fill, p.expectedFill);
|
||||
assert.equal(p.outline, p.expectedOutline);
|
||||
assert.equal(p.radius, '5px'); assert.equal(p.inputRadius, '5px');
|
||||
assert.equal(p.inputOutline, p.expectedOutline); assert.equal(p.inputOutlineWidth, '2px');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
p = await paletteMetrics(); assert.equal(p.fill, p.expectedFill);
|
||||
await page.screenshot({ path: `${output}/palette-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
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 page.locator('.monaco-host').click({ button: 'right', position: { x: 100, y: 300 } });
|
||||
await code.waitFor();
|
||||
const bounds = await code.boundingBox();
|
||||
assert.ok(bounds.x >= 0 && bounds.x + bounds.width <= 560);
|
||||
await page.keyboard.press('End');
|
||||
assert.equal(await page.getByRole('menuitem', { name: 'Command palette F1', exact: true }).evaluate(n => n === document.activeElement), true);
|
||||
await page.screenshot({ path: `${output}/ide-narrow-${theme}.png` });
|
||||
await page.keyboard.press('Enter');
|
||||
await palette.waitFor({ state: 'visible' });
|
||||
await page.screenshot({ path: `${output}/palette-narrow-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
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('[data-tree-rel="a.md"]').click();
|
||||
await page.getByRole('group', { name: 'Editor layout', exact: true }).hover();
|
||||
await page.getByRole('button', { name: 'Writer', exact: true }).click();
|
||||
report.push({ theme, passed: ['word and blank menu parity', 'spelling correction and undo', 'Writer/IDE parity', 'undo menu action', 'code menu host styles', 'transparent code in Writer/Reader', 'palette selection/focus', 'narrow keyboard menu/palette'], nativeDesktop: 'not tested' });
|
||||
}
|
||||
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(); }
|
||||
@@ -0,0 +1,155 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
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) || (!prefix && path.startsWith(".runestone/"))) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await mkdir('output/editor-template-hyphen', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
// Save the empty task lines from the reported template, then create through
|
||||
// the normal note action so the filename receives the initial focus.
|
||||
await page.evaluate(async () => {
|
||||
const { saveNoteTemplate } = await import('/src/lib/workspace/templates.ts');
|
||||
await saveNoteTemplate('To Do', '- [ ] \n'.repeat(10));
|
||||
});
|
||||
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'New note', exact: true }).last().click();
|
||||
await page.getByRole('menuitem', { name: 'To Do', exact: true }).click();
|
||||
const title = page.getByRole('textbox', { name: 'Note filename', exact: true });
|
||||
await title.waitFor();
|
||||
await page.waitForFunction(() => document.activeElement?.getAttribute('aria-label') === 'Note filename');
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
|
||||
});
|
||||
const count = () => page.locator('.writer-checkbox').count();
|
||||
const expectCount = async expected => {
|
||||
await page.waitForFunction(expected => document.querySelectorAll('.writer-checkbox').length === expected, expected);
|
||||
assert.equal(await count(), expected);
|
||||
};
|
||||
const setSource = source => page.evaluate(source => {
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: source.length } });
|
||||
window.__CM__.focus();
|
||||
}, source);
|
||||
const plain = 'Some generic mobs or factions,\n-';
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({ theme: 'default', mode }), mode);
|
||||
for (const width of [1440, 600]) {
|
||||
await page.setViewportSize({ width, height: width === 600 ? 760 : 1000 });
|
||||
if (width === 600) {
|
||||
await page.getByRole('button', { name: 'Files', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
|
||||
}
|
||||
if (!(await title.isVisible())) await page.getByRole('button', { name: 'Rename note', exact: true }).click();
|
||||
await title.focus();
|
||||
await expectCount(10);
|
||||
await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-template-title.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
await page.evaluate(() => {
|
||||
const view = window.__CM__;
|
||||
view.dispatch({ selection: { anchor: 0 } }); view.focus();
|
||||
});
|
||||
await expectCount(9);
|
||||
await page.keyboard.press('End');
|
||||
await page.keyboard.type('First task');
|
||||
await expectCount(10);
|
||||
await page.locator('.writer-checkbox').first().click();
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /^- \[x\] First task/);
|
||||
await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-template-edit.png` });
|
||||
|
||||
await setSource(plain);
|
||||
assert.equal(await page.locator('.writer-h2').count(), 0, 'A lone hyphen must not enlarge preceding prose');
|
||||
await page.screenshot({ path: `output/editor-template-hyphen/${mode}-${width}-single-hyphen.png` });
|
||||
await page.keyboard.type(' Item');
|
||||
assert.equal(await page.locator('.writer-h2').count(), 0, 'The hyphen continues into a list');
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), plain + ' Item');
|
||||
await setSource(plain + '-');
|
||||
assert.equal(await page.locator('.writer-h2').count(), 1, 'Two hyphens retain Setext heading support');
|
||||
await setSource('A normal heading\n===\n');
|
||||
assert.equal(await page.locator('.writer-h1').count(), 1);
|
||||
// Restore the template for the next theme and size without an active body caret.
|
||||
await setSource('- [ ] \n'.repeat(10));
|
||||
await page.getByRole('button', { name: 'Rename note', exact: true }).click();
|
||||
if (width === 600) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: template creation, filename focus, keyboard task entry, checkbox toggle, lone hyphen, list continuation, and Setext headings in both themes and narrow layouts.');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: 'output/editor-template-hyphen/failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,175 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function open(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();
|
||||
}
|
||||
async function writer() {
|
||||
await page.locator('.cm-content').waitFor();
|
||||
return page.evaluate(async () => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
window.__WRITER__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
|
||||
return window.__WRITER__.state.sliceDoc();
|
||||
});
|
||||
}
|
||||
async function expectWriter(expected) {
|
||||
await writer();
|
||||
try { await page.waitForFunction(text => window.__WRITER__.state.sliceDoc() === text, expected); } catch (error) { console.log({ expected, actual: await writer(), errors }); throw error; }
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await open('welcome.md');
|
||||
const original = await writer();
|
||||
await page.locator('.cm-content').click();
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.type(' first edit');
|
||||
await expectWriter(original + ' first edit');
|
||||
await page.keyboard.press('Control+s');
|
||||
await open('second.md');
|
||||
await writer();
|
||||
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
|
||||
await expectWriter(original + ' first edit');
|
||||
await page.keyboard.press('Control+z');
|
||||
await expectWriter(original);
|
||||
await page.keyboard.press('Control+y');
|
||||
await expectWriter(original + ' first edit');
|
||||
console.log('PASS: saved Writer edit survives tab switch with undo and redo');
|
||||
await page.evaluate(() => window.dispatchEvent(new Event('focus')));
|
||||
await page.keyboard.press('Control+z');
|
||||
await expectWriter(original);
|
||||
await page.keyboard.press('Control+y');
|
||||
await expectWriter(original + ' first edit');
|
||||
assert.equal(await page.evaluate(() => window.__WRITER__.state.selection.main.head), (original + ' first edit').length);
|
||||
console.log('PASS: Writer undo and redo survive window focus refresh and restore the caret');
|
||||
await page.keyboard.press('Control+e');
|
||||
await page.locator('.monaco-editor textarea').waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
|
||||
editor.setPosition({ lineNumber: editor.getModel().getLineCount(), column: editor.getModel().getLineMaxColumn(editor.getModel().getLineCount()) });
|
||||
editor.focus();
|
||||
window.__IDE__ = editor;
|
||||
});
|
||||
await page.keyboard.type(' second edit');
|
||||
assert.equal(await page.evaluate(() => window.__IDE__.getDomNode()?.isConnected), true, 'Typing keeps the same IDE editor mounted');
|
||||
assert.equal(await page.evaluate(() => window.__IDE__.getValue()), original + ' first edit second edit');
|
||||
await page.keyboard.press('Control+e');
|
||||
await expectWriter(original + ' first edit second edit');
|
||||
await page.locator('.cm-content').click();
|
||||
await page.keyboard.press('Control+z');
|
||||
await expectWriter(original + ' first edit second');
|
||||
await page.keyboard.press('Control+z');
|
||||
await expectWriter(original + ' first edit');
|
||||
await page.keyboard.press('Control+z');
|
||||
await expectWriter(original);
|
||||
await page.keyboard.press('Control+y');
|
||||
await expectWriter(original + ' first edit');
|
||||
await page.keyboard.press('Control+y');
|
||||
await expectWriter(original + ' first edit second');
|
||||
await page.keyboard.press('Control+y');
|
||||
await expectWriter(original + ' first edit second edit');
|
||||
console.log('PASS: Writer undo includes edits from IDE mode');
|
||||
const tableSource = '# Table\n\n| A | B |\n| --- | --- |\n| One | Two |\n\nTail.\n';
|
||||
await page.evaluate(source => {
|
||||
window.__TEST__.files.set('table.md', source);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table.md'] });
|
||||
}, tableSource);
|
||||
await open('table.md');
|
||||
await writer();
|
||||
const cells = page.locator('.writer-table tbody td');
|
||||
await cells.nth(0).click();
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.type('Alpha');
|
||||
await cells.nth(1).click();
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.type('Beta');
|
||||
await page.keyboard.press('Escape');
|
||||
const editedTable = await writer();
|
||||
assert.ok(editedTable.includes('Alpha') && editedTable.includes('Beta'));
|
||||
await page.getByRole('tab', { name: 'welcome.md', exact: true }).click();
|
||||
await writer();
|
||||
await page.getByRole('tab', { name: 'table.md', exact: true }).click();
|
||||
await writer();
|
||||
await page.keyboard.press('Control+z');
|
||||
await expectWriter(editedTable.replace('Beta', 'Two'));
|
||||
await page.keyboard.press('Control+z');
|
||||
await expectWriter(tableSource);
|
||||
await page.keyboard.press('Control+y');
|
||||
await expectWriter(editedTable.replace('Beta', 'Two'));
|
||||
await page.keyboard.press('Control+y');
|
||||
await expectWriter(editedTable);
|
||||
console.log('PASS: table cell typing stays grouped per cell across tab switches');
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,200 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
const output = ".audit/todo-2026-10-14/unified-find";
|
||||
await mkdir(output, { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
const sample = "# Alpha\n\nAlpha alpha alphabet\n\n| Name | Value |\n| --- | --- |\n| Alpha | One |\n| Beta | Two |\n\nLast Alpha paragraph.\n";
|
||||
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
|
||||
const replace = page.getByRole("textbox", { name: "Replace with", exact: true });
|
||||
async function mode(group, value) {
|
||||
await page.getByRole("group", { name: group, exact: true }).hover();
|
||||
await page.getByRole("button", { name: value, exact: true }).click();
|
||||
}
|
||||
async function onePanel() {
|
||||
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
|
||||
assert.equal(await page.locator('.find-widget.visible').count(), 0, 'No Monaco floating find widget');
|
||||
const bar = await page.locator('.rs-find-bar:visible').boundingBox();
|
||||
const pane = await page.locator('.editor.pane-active').boundingBox();
|
||||
assert.ok(Math.abs(bar.width - pane.width) < 3, 'Find spans the document pane');
|
||||
}
|
||||
async function sourceEditor() {
|
||||
await page.waitForFunction(() => !!document.querySelector('.monaco-editor'));
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
window.__MONACO__ = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected && view.getDomNode().getBoundingClientRect().width > 0);
|
||||
window.__MONACO__.focus();
|
||||
});
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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();
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await page.evaluate(async theme => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
saveAppearance({ theme: 'default', mode: theme });
|
||||
}, theme);
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
await page.evaluate(async sample => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector('.live-writer > .cm-editor .cm-content'));
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: sample }, selection: { anchor: 0 } });
|
||||
window.__CM__.focus();
|
||||
}, sample);
|
||||
await page.keyboard.press('Control+f');
|
||||
await find.fill('Alpha');
|
||||
await onePanel();
|
||||
await page.screenshot({ path: `${output}/writer-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('.live-writer td').first().dblclick();
|
||||
await page.locator('.writer-cell-editor').waitFor();
|
||||
await page.keyboard.press('Control+f');
|
||||
await onePanel();
|
||||
assert.equal(await find.evaluate(node => node === document.activeElement), true, 'Table focus opens the document find');
|
||||
assert.equal(await page.locator('.writer-cell-editor .rs-find-bar').count(), 0);
|
||||
await find.fill('Last Alpha');
|
||||
await page.keyboard.press('Enter');
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc(window.__CM__.state.selection.main.from, window.__CM__.state.selection.main.to)), /Last Alpha/);
|
||||
await page.screenshot({ path: `${output}/table-focus-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
await mode('Editor layout', 'IDE');
|
||||
await sourceEditor();
|
||||
await page.evaluate(() => { window.__MONACO__.getModel().setValue('Alpha alpha alphabet\r\nAlpha second\r\nAlpha third'); window.__MONACO__.setPosition({ lineNumber: 1, column: 1 }); });
|
||||
await page.keyboard.press('Control+f');
|
||||
await find.fill('Alpha');
|
||||
await onePanel();
|
||||
await page.keyboard.press('Enter');
|
||||
const first = await page.evaluate(() => window.__MONACO__.getSelection().toString());
|
||||
await page.keyboard.press('Enter');
|
||||
assert.notEqual(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
|
||||
await page.keyboard.press('Shift+Enter');
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.getSelection().toString()), first);
|
||||
await page.getByRole('checkbox', { name: 'Match case' }).check();
|
||||
await page.getByRole('checkbox', { name: 'Whole word' }).check();
|
||||
await replace.fill('Gamma');
|
||||
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.getValue().replace(/\r\n/g, '\n')), 'Gamma alpha alphabet\nGamma second\nGamma third');
|
||||
await page.getByRole('checkbox', { name: 'Regex' }).check();
|
||||
await find.fill('[');
|
||||
assert.equal(await find.getAttribute('aria-invalid'), 'true');
|
||||
assert.equal(await page.getByRole('button', { name: 'Replace all', exact: true }).isDisabled(), true);
|
||||
await find.fill('(?<=G)(amma)');
|
||||
await page.getByRole('checkbox', { name: 'Whole word' }).uncheck();
|
||||
await replace.fill('$1!');
|
||||
await page.getByRole('button', { name: 'Replace all', exact: true }).click();
|
||||
assert.match(await page.evaluate(() => window.__MONACO__.getValue()), /^Gamma! alpha/);
|
||||
await page.getByRole('checkbox', { name: 'Regex' }).uncheck();
|
||||
await find.fill('Gamma');
|
||||
await page.getByRole('button', { name: 'Select all', exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.getSelections().length), 3);
|
||||
await page.screenshot({ path: `${output}/source-${theme}.png` });
|
||||
await find.focus(); await page.keyboard.press('Escape');
|
||||
assert.equal(await find.count(), 0);
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.hasTextFocus()), true);
|
||||
await page.keyboard.press('Control+h');
|
||||
assert.equal(await replace.evaluate(node => node === document.activeElement), true);
|
||||
await find.fill('Gamma');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.keyboard.press('F3');
|
||||
await page.screenshot({ path: `${output}/source-replace-${theme}.png` });
|
||||
await page.setViewportSize({ width: 800, height: 700 });
|
||||
await onePanel();
|
||||
assert.equal(await page.locator('.rs-find-bar').evaluate(node => node.scrollWidth <= node.clientWidth), true);
|
||||
await page.screenshot({ path: `${output}/source-narrow-${theme}.png` });
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await find.focus(); await page.keyboard.press('Escape');
|
||||
await page.evaluate(sample => window.__MONACO__.getModel().setValue(sample), sample);
|
||||
await mode('Document view', 'Read');
|
||||
await page.locator('.reading').focus();
|
||||
await page.keyboard.press('Control+f');
|
||||
await find.fill('Alpha'); await page.keyboard.press('Enter');
|
||||
await onePanel();
|
||||
assert.equal(await replace.count(), 0, 'Reading search does not offer replacement');
|
||||
assert.equal(await page.evaluate(() => window.getSelection().toString()), 'Alpha');
|
||||
const anchor = await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML);
|
||||
await page.keyboard.press('Enter');
|
||||
assert.notEqual(await page.evaluate(() => window.getSelection().anchorNode.parentElement.outerHTML), anchor);
|
||||
await page.screenshot({ path: `${output}/reading-${theme}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.locator('.reading').evaluate(node => node === document.activeElement), true);
|
||||
await mode('Document view', 'Edit');
|
||||
await mode('Editor layout', 'Writer');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: one full-width document Find in Writer, nested table focus, IDE/source, and Reading, with replacement, regex, CRLF, focus return, both themes, and narrow controls.');
|
||||
} catch (error) {
|
||||
console.error('Browser errors:', errors);
|
||||
await page.screenshot({ path: `${output}/failure.png` });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,176 @@
|
||||
// Run against the host development server with PLAYWRIGHT_MODULE set when needed.
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, readFile } 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(10000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
const output = '.audit/host-privacy-find';
|
||||
await mkdir(output, { recursive: true });
|
||||
const pm = {
|
||||
manifest: JSON.parse(await readFile(new URL('../../../../RuneStone_Project_Management/dist/plugin/plugin.json', import.meta.url), 'utf8')),
|
||||
code: await readFile(new URL('../../../../RuneStone_Project_Management/dist/plugin/main.js', import.meta.url), 'utf8'),
|
||||
};
|
||||
await page.addInitScript(({ pm }) => {
|
||||
window.isTauri = true;
|
||||
const files = new Map([['untitled.md', '# Existing note\n'], ['sample.finddoc', 'Alpha alpha alphabet']]);
|
||||
files.set('Board.md', '---\nrunestone_pm:\n schema: 1\n kind: board\n id: host-find-board\n lists:\n - {id: todo, name: To do, status: todo, collapsed: false}\n - {id: doing, name: In progress, status: doing, collapsed: false}\n - {id: done, name: Done, status: done, collapsed: false}\n defaults: {todo: todo, doing: doing, done: done}\n---\n');
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
let sequence = 0;
|
||||
const manifest = { schemaVersion: 1, id: 'test.find', name: 'Find test', author: 'Test', description: 'Search checks', version: '1.0.0', apiVersion: 1, entry: 'main.js', access: 'full-app' };
|
||||
const code = `export function activate(api) {
|
||||
api.registerDocumentType({ id: 'document', title: 'Test document', extensions: ['finddoc'], identify: path => ({ id: path }), mount(root) {
|
||||
root.innerHTML = '<section><h2>Test document</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
|
||||
}});
|
||||
for (const name of ['Board', 'Changes']) api.registerView({ id: name.toLowerCase(), title: name, placement: 'editor', navigation: true, icon: 'list', mount(root) {
|
||||
root.innerHTML = '<section><h2>' + name + '</h2><p>Alpha alpha alphabet</p><button>Alpha card</button><p hidden>Hidden Alpha</p><button class="focus-return">Details</button></section>';
|
||||
}});
|
||||
api.registerView({ id: 'native', title: 'Custom find', placement: 'editor', navigation: true, find() { window.customFindCalls = (window.customFindCalls || 0) + 1; }, mount(root) { root.innerHTML = '<p>Native content</p>'; } });
|
||||
}`;
|
||||
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 = {}) => {
|
||||
if (command === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'workspace_last_path') return 'C:/find-test';
|
||||
if (command === 'workspace_open') return { root: 'C:/find-test', name: 'find-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_list') return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: 'file' }));
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel) && args.missingOk) return null; if (!files.has(args.rel)) throw Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_list_markdown') return [...files.keys()].filter(path => !path.startsWith('.') && path.endsWith('.md'));
|
||||
if (command === 'workspace_read_many') return args.paths.map(path => ({ path, source: files.get(path) }));
|
||||
if (command === 'workspace_create') { if (files.has(args.rel)) throw Error('File exists'); files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_write') { files.set(args.rel, args.contents); return; }
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: [manifest, pm.manifest].map(item => ({ manifest: item, hash: item.id, enabled: true, path: 'C:/test/plugins/' + item.id, error: null, removal: false })) };
|
||||
if (command === 'plugins_load') return args.id === pm.manifest.id ? pm.code : code;
|
||||
if (command === 'plugins_data') return 'null';
|
||||
if (command === 'browser_connect') return 'test';
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
|
||||
window.__FILES__ = files;
|
||||
}, { pm });
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.locator('.ws').getByText('find-test', { exact: true }).waitFor();
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).waitFor();
|
||||
const note = page.locator('.tree-tools').getByRole('button', { name: 'New note', exact: true });
|
||||
assert.equal(await page.locator('.tree-tools').getByRole('button', { name: 'New file', exact: true }).count(), 0);
|
||||
await note.click();
|
||||
await page.waitForFunction(() => window.__FILES__.has('untitled 2.md'));
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click();
|
||||
await page.keyboard.press('Control+f');
|
||||
for (const label of ['Find in document', 'Replace with']) {
|
||||
assert.equal(await page.getByRole('textbox', { name: label, exact: true }).getAttribute('autocomplete'), 'off');
|
||||
}
|
||||
await page.keyboard.press('Escape');
|
||||
await page.screenshot({ path: `${output}/new-note-dark.png` });
|
||||
assert.equal(await page.getByRole('dialog').count(), 0, 'The note opens without a filename dialog');
|
||||
await note.click();
|
||||
await page.waitForFunction(() => window.__FILES__.has('untitled 3.md'));
|
||||
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 page.getByRole('tab', { name: 'untitled 3.md', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).click();
|
||||
await page.keyboard.press('Control+f');
|
||||
const writerFind = page.getByRole('textbox', { name: 'Find in document', exact: true });
|
||||
await writerFind.fill('fift');
|
||||
assert.equal(await writerFind.getAttribute('autocomplete'), 'off');
|
||||
assert.equal(await page.getByRole('textbox', { name: 'Replace with', exact: true }).getAttribute('autocomplete'), 'off');
|
||||
await page.screenshot({ path: `${output}/find-privacy-${theme}.png` });
|
||||
await page.setViewportSize({ width: 650, height: 800 });
|
||||
await page.screenshot({ path: `${output}/find-privacy-${theme}-narrow.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.mouse.move(900, 400);
|
||||
await note.hover();
|
||||
await page.getByRole('tooltip').filter({ hasText: /^New note$/ }).waitFor();
|
||||
await page.screenshot({ path: `${output}/new-note-tooltip-${theme}.png` });
|
||||
for (const name of ['Board', 'Changes']) {
|
||||
await page.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name, exact: true }).click();
|
||||
const pane = page.getByRole('tabpanel', { name, exact: true });
|
||||
await pane.getByRole('button', { name: 'Details', exact: true }).focus();
|
||||
await page.keyboard.press('Control+f');
|
||||
assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Non-document plugin views do not show document Find');
|
||||
await page.screenshot({ path: `${output}/${name}-${theme}.png` });
|
||||
await page.setViewportSize({ width: 650, height: 800 });
|
||||
await page.keyboard.press('Control+f');
|
||||
assert.equal(await pane.locator('.rs-find-bar').count(), 0);
|
||||
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
}
|
||||
for (const surface of ['all-tasks', 'board-document']) {
|
||||
if (surface === 'all-tasks') {
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: /^Project Management/ }).click();
|
||||
} else await page.getByRole('tree', { name: 'Workspace files' }).getByText('Board', { exact: true }).dblclick();
|
||||
const pane = page.locator('.plugin-editor-pane:visible');
|
||||
await pane.locator('.pm-board').waitFor();
|
||||
await pane.focus();
|
||||
await page.keyboard.press('Control+f');
|
||||
assert.equal(await pane.locator('.rs-find-bar').count(), 0, 'Actual PM views do not show host Find');
|
||||
await page.screenshot({ path: `${output}/pm-${surface}-${theme}.png` });
|
||||
await page.setViewportSize({ width: 650, height: 800 });
|
||||
await page.keyboard.press('Control+f');
|
||||
assert.equal(await pane.locator('.rs-find-bar').count(), 0);
|
||||
await page.screenshot({ path: `${output}/pm-${surface}-${theme}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
}
|
||||
await page.getByRole('tree', { name: 'Workspace files' }).getByText('sample', { exact: true }).dblclick();
|
||||
for (const name of ['sample']) {
|
||||
const pane = page.getByRole('tabpanel', { name, exact: true });
|
||||
const returnButton = pane.getByRole('button', { name: 'Details', exact: true });
|
||||
await returnButton.focus();
|
||||
await page.keyboard.press('Control+f');
|
||||
const find = pane.getByRole('textbox', { name: 'Find in document', exact: true });
|
||||
assert.equal(await find.getAttribute('autocomplete'), 'off');
|
||||
await find.fill('Alpha');
|
||||
assert.equal(await page.locator('.rs-find-bar:visible').count(), 1);
|
||||
assert.equal(await pane.getByRole('textbox', { name: 'Replace with' }).count(), 0);
|
||||
await page.keyboard.press('Enter');
|
||||
assert.equal(await page.evaluate(() => getSelection().toString()), 'Alpha');
|
||||
await page.keyboard.press('F3');
|
||||
assert.equal(await page.evaluate(() => getSelection().toString()), 'alpha');
|
||||
await pane.getByText('Whole word', { exact: true }).click();
|
||||
await find.focus();
|
||||
const matches = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
await page.keyboard.press('Enter');
|
||||
matches.push(await page.evaluate(() => ({ text: getSelection().toString(), button: !!getSelection().anchorNode?.parentElement?.closest('button') })));
|
||||
}
|
||||
assert.equal(matches.filter(match => match.button).length, 1, 'Rendered card buttons participate in search');
|
||||
assert.ok(matches.every(match => /^alpha$/i.test(match.text)));
|
||||
await page.screenshot({ path: `${output}/${name}-${theme}.png` });
|
||||
await page.setViewportSize({ width: 650, height: 800 });
|
||||
await page.screenshot({ path: `${output}/${name}-${theme}-narrow.png` });
|
||||
const bar = await pane.locator('.rs-find-bar').boundingBox(), bounds = await pane.boundingBox();
|
||||
assert.ok(bar.x >= bounds.x && bar.x + bar.width <= bounds.x + bounds.width + 1);
|
||||
await page.getByRole('button', { name: 'Files', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Hide outline', exact: true }).click();
|
||||
await page.screenshot({ path: `${output}/${name}-${theme}-narrow-focused.png` });
|
||||
await find.focus();
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await returnButton.evaluate(node => node === 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('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'Custom find', exact: true }).click();
|
||||
await page.getByRole('tabpanel', { name: 'Custom find' }).focus();
|
||||
await page.keyboard.press('Control+f');
|
||||
assert.equal(await page.evaluate(() => window.customFindCalls), 1, 'Plugin find handlers retain ownership');
|
||||
assert.equal(await page.locator('.rs-find-bar:visible').count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: Find privacy attributes, actual PM All Tasks and board scope, plugin document Find, custom handlers, focus, both themes, and narrow layouts');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: `${output}/failure.png` });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,167 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
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();
|
||||
const editor = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
await editor.waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: "# Alpha\n\nalpha Alpha alphabet\n\n## Beta\n\nBeta text\n" }, selection: { anchor: 0 } });
|
||||
window.__CM__.focus();
|
||||
});
|
||||
await page.keyboard.press("Control+f");
|
||||
const find = page.getByRole("textbox", { name: "Find in document", exact: true });
|
||||
await find.waitFor();
|
||||
assert.equal(await find.evaluate(el => document.activeElement === el), true);
|
||||
assert.equal(await page.locator(".cm-panels-top .rs-writer-search").count(), 1);
|
||||
const panelBounds = await page.locator(".rs-writer-search").boundingBox();
|
||||
const scrollBounds = await page.locator(".cm-scroller").boundingBox();
|
||||
assert.ok(panelBounds.y + panelBounds.height <= scrollBounds.y + 1);
|
||||
await find.fill("Alpha");
|
||||
await page.keyboard.press("Enter");
|
||||
const first = await page.evaluate(() => window.__CM__.state.selection.main.from);
|
||||
await page.keyboard.press("Enter");
|
||||
const second = await page.evaluate(() => window.__CM__.state.selection.main.from);
|
||||
assert.notEqual(first, second);
|
||||
await page.keyboard.press("Shift+Enter");
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.selection.main.from), first);
|
||||
await page.getByRole("checkbox", { name: "Match case" }).check();
|
||||
await page.getByRole("checkbox", { name: "Whole word" }).check();
|
||||
await page.getByRole("textbox", { name: "Replace with" }).fill("Gamma");
|
||||
await page.getByRole("button", { name: "Replace all", exact: true }).click();
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /# Gamma\n\nalpha Gamma alphabet/);
|
||||
await page.getByRole("checkbox", { name: "Regex" }).check();
|
||||
await find.fill("[");
|
||||
assert.equal(await find.getAttribute("aria-invalid"), "true");
|
||||
assert.equal(await page.getByRole("button", { name: "Replace all", exact: true }).isDisabled(), true);
|
||||
await page.getByText("Invalid expression", { exact: true }).waitFor();
|
||||
await find.fill("Gamma");
|
||||
await page.getByRole("checkbox", { name: "Regex" }).uncheck();
|
||||
await page.evaluate(async () => {
|
||||
const moduleUrl = performance.getEntriesByType("resource").find(entry => entry.name.includes("/@codemirror_search.js"))?.name;
|
||||
if (!moduleUrl) throw new Error("Search module was not loaded");
|
||||
const { SearchQuery, setSearchQuery } = await import(moduleUrl);
|
||||
window.__CM__.dispatch({ effects: setSearchQuery.of(new SearchQuery({ search: "Beta" })) });
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector('input[name="search"]').value === "Beta");
|
||||
await find.focus();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await find.count(), 0);
|
||||
assert.equal(await editor.evaluate(el => document.activeElement === el), true);
|
||||
await page.keyboard.press("Control+f");
|
||||
await find.waitFor();
|
||||
await page.getByRole("button", { name: "Next match (Enter)" }).focus();
|
||||
await page.getByRole("tooltip", { name: "Next match (Enter)" }).waitFor({ state: "visible" });
|
||||
await find.focus();
|
||||
|
||||
const outline = page.getByRole("region", { name: "Outline", exact: true });
|
||||
if (!await outline.count()) await page.getByRole("button", { name: "Outline", exact: true }).click();
|
||||
await outline.focus();
|
||||
await page.keyboard.press("Control+f");
|
||||
const outlineFind = page.getByRole("textbox", { name: "Find in outline", exact: true });
|
||||
await outlineFind.fill("beta");
|
||||
assert.equal(await outline.locator("li").count(), 1);
|
||||
assert.equal(await outline.locator("li button").textContent(), "Beta");
|
||||
await outlineFind.fill("missing");
|
||||
await outline.getByText("No matching headings or symbols.").waitFor();
|
||||
await outlineFind.fill("Gamma");
|
||||
await page.screenshot({ path: ".audit/find-bars.png" });
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await outlineFind.count(), 0);
|
||||
assert.equal(await outline.locator("li").count(), 2);
|
||||
assert.equal(await outline.evaluate(el => document.activeElement === el), true);
|
||||
await page.keyboard.press("Control+f");
|
||||
await outlineFind.fill("Beta");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(() => window.__CM__.state.doc.lineAt(window.__CM__.state.selection.main.head).text === "## Beta");
|
||||
assert.equal(await editor.evaluate(el => document.activeElement === el), true);
|
||||
|
||||
await page.setViewportSize({ width: 880, height: 760 });
|
||||
await find.focus();
|
||||
await page.screenshot({ path: ".audit/find-bars-narrow.png" });
|
||||
for (const selector of [".rs-writer-search", ".outline-search"]) {
|
||||
assert.equal(await page.locator(selector).evaluate(el => el.scrollWidth <= el.clientWidth), true, selector);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: Top search panel, shortcuts, replacement, query sync, invalid regex, focus tooltip, outline filtering, focus return and narrow layout.");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
await page.screenshot({ path: ".audit/find-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,95 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
|
||||
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 context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => 1, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugins_snapshot") return { root: "D:\\LayoutTest\\plugins", plugins: [] };
|
||||
if (command === "workspace_last_path") return "D:\\LayoutTest";
|
||||
if (command === "workspace_open") return { root: "D:\\LayoutTest", name: "LayoutTest", watch_mode: "native" };
|
||||
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.md", rel_path: "note.md", kind: "file" }];
|
||||
if (command === "workspace_read") {
|
||||
if (args.rel === "note.md") return "# Layout test\n\nA note.\n";
|
||||
throw new Error("Missing file");
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const errors = [];
|
||||
context.on("page", page => page.on("pageerror", error => errors.push(error.message)));
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
let page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
async function ready() { await page.getByRole("button", { name: /^(Hide|Show) outline$/ }).waitFor(); }
|
||||
async function reopen() {
|
||||
await page.close();
|
||||
page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
await page.goto(url);
|
||||
await ready();
|
||||
}
|
||||
async function resize(index, x) {
|
||||
const box = await page.locator(".gutter-v").nth(index).boundingBox();
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + 60);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(x, box.y + 60);
|
||||
await page.mouse.up();
|
||||
}
|
||||
async function widths() {
|
||||
return page.locator(".shell").evaluate(element => [element.style.getPropertyValue("--left"), element.style.getPropertyValue("--right")]);
|
||||
}
|
||||
try {
|
||||
await page.goto(url);
|
||||
await ready();
|
||||
await page.getByText("LayoutTest", { exact: true }).waitFor();
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("note.md");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.md" }).click();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
|
||||
await page.keyboard.press("Control+e");
|
||||
await page.locator(".monaco-editor").waitFor();
|
||||
assert.equal(await page.locator(".right").count(), 0);
|
||||
await page.keyboard.press("Control+e");
|
||||
await page.locator(".cm-content").waitFor();
|
||||
assert.equal(await page.locator(".right").count(), 0);
|
||||
console.log("PASS: hidden outline stays hidden across Writer and IDE changes");
|
||||
await page.reload();
|
||||
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
|
||||
assert.equal(await page.locator(".right").count(), 0);
|
||||
await reopen();
|
||||
await page.getByRole("button", { name: "Show outline", exact: true }).waitFor();
|
||||
console.log("PASS: hidden outline survives reload and window reopen");
|
||||
|
||||
await page.getByRole("button", { name: "Show outline", exact: true }).click();
|
||||
await resize(0, 330);
|
||||
await resize(1, 970);
|
||||
const resized = await widths();
|
||||
assert.deepEqual(resized, ["330px", "310px"]);
|
||||
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
|
||||
await reopen();
|
||||
assert.deepEqual(await widths(), resized);
|
||||
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
|
||||
await page.getByRole("button", { name: "Hide outline", exact: true }).waitFor();
|
||||
console.log("PASS: resized sidebars and chosen navigation view survive reopen");
|
||||
|
||||
await page.getByRole("button", { name: "Bookmarks", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Hide outline", exact: true }).click();
|
||||
await reopen();
|
||||
assert.equal(await page.locator(".left, .right").count(), 0);
|
||||
await page.keyboard.press("Control+b");
|
||||
assert.equal(await page.getByRole("button", { name: "Bookmarks", exact: true }).getAttribute("aria-pressed"), "true");
|
||||
await page.getByRole("button", { name: "Show outline", exact: true }).click();
|
||||
assert.deepEqual(await widths(), resized);
|
||||
console.log("PASS: collapsed sidebars retain their sizes and navigation view");
|
||||
assert.deepEqual(errors, []);
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,160 @@
|
||||
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));
|
||||
page.on("console", message => { if (message.text().includes("binding_property_non_reactive")) errors.push(message.text()); });
|
||||
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");
|
||||
files.set("a.md", "# Alpha\n\nOrigin paragraph.\n\n[[notes/b.md|Right note]]\n");
|
||||
files.set("notes/b.md", "# Bravo\n\nSecond paragraph.\n\n[Relative](c.md)\n\n[[/a.md|Original note]]\n");
|
||||
files.set("notes/c.md", "# Charlie\n\nThird paragraph.\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.tabMenuTest.change = (path, text) => { files.set(path, text); callbacks.get(listeners.get("workspace-event"))?.({ event: "workspace-event", id: 1, payload: { root, kind: "modify", paths: [path] } }); };
|
||||
window.tabMenuTest.writes = [];
|
||||
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") { if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("conflict"); files.set(args.rel, args.contents); window.tabMenuTest.writes.push(args.rel); 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 output = '.audit/document-splits';
|
||||
await mkdir(output, {recursive:true});
|
||||
const pane = path => page.locator(`[data-document-path="${path}"]`);
|
||||
const item = name => page.getByRole('menuitem',{name,exact:true});
|
||||
async function openRight(path,label) {
|
||||
const current = pane(path);
|
||||
await current.locator('.cm-content').getByText(path === 'a.md' ? 'Origin paragraph.' : 'Second paragraph.',{exact:true}).click();
|
||||
await current.locator('.cm-content').getByText(label,{exact:true}).click({button:'right'});
|
||||
await item('Open to the right').click();
|
||||
}
|
||||
async function append(path, text) {
|
||||
const target=pane(path).locator('.cm-content');
|
||||
await target.click(); await page.keyboard.press('Control+End'); await page.keyboard.type(text);
|
||||
}
|
||||
async function text(path) { return pane(path).locator('.cm-content').evaluate(async node=> { const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); return EditorView.findFromDOM(node).state.doc.toString(); }); }
|
||||
async function focus(path) { await pane(path).locator('.cm-content').click(); }
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.locator('[data-tree-rel="a.md"]').click(); await pane('a.md').locator('.cm-content').waitFor();
|
||||
await append('a.md','\nLeft unsaved.');
|
||||
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
|
||||
assert.equal(await page.locator('.document-pane').count(),2);
|
||||
assert.match(await text('a.md'),/Left unsaved/);
|
||||
await append('notes/b.md','\nRight saved.'); await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(()=>window.tabMenuTest.writes.includes('notes/b.md'));
|
||||
assert.equal(await page.evaluate(()=>window.tabMenuTest.writes.includes('a.md')),false,'Save uses the focused right pane');
|
||||
await focus('a.md'); await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.tabMenuTest.writes.includes('a.md'));
|
||||
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
|
||||
await pane('notes/b.md').getByRole('button',{name:'IDE',exact:true}).click(); await pane('notes/b.md').locator('.monaco-editor').waitFor();
|
||||
assert.equal(await pane('a.md').locator('.cm-content').count(),1,'Changing the right mode keeps the left editor');
|
||||
await openRight('a.md','Right note');
|
||||
assert.equal(await page.locator('.document-pane').count(),2);
|
||||
await page.waitForFunction(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getEditors().some(editor=>editor.getModel()?.uri.path.endsWith('/b.md') && editor.hasTextFocus());}); await page.keyboard.press('Control+End'); await page.keyboard.type('\nIDE edit.'); await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('IDE edit.'));
|
||||
await pane('notes/b.md').getByRole('group',{name:'Editor layout',exact:true}).hover();
|
||||
await pane('notes/b.md').getByRole('button',{name:'Writer',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
|
||||
assert.match(await text('notes/b.md'),/IDE edit/);
|
||||
await pane('notes/b.md').getByRole('group',{name:'Document view',exact:true}).hover();
|
||||
await pane('notes/b.md').getByRole('button',{name:'Read',exact:true}).click(); await pane('notes/b.md').locator('.reading').waitFor();
|
||||
assert.equal(await pane('a.md').locator('.reading').count(),0,'Reading mode belongs to its pane');
|
||||
await focus('a.md'); assert.equal(await pane('notes/b.md').locator('.reading').count(),1);
|
||||
await pane('notes/b.md').getByRole('group',{name:'Document view',exact:true}).hover();
|
||||
await pane('notes/b.md').getByRole('button',{name:'Edit',exact:true}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
|
||||
for(const path of ['a.md','notes/b.md']) await pane(path).locator('.cm-content').evaluate(async node=> {
|
||||
const {EditorView}=await import('/node_modules/@codemirror/view/dist/index.js'); const v=EditorView.findFromDOM(node); const source=v.state.doc.toString(); const from=source.indexOf(source.includes('Alpha') ? 'Origin' : 'Second'); v.dispatch({selection:{anchor:from,head:from+6}});
|
||||
});
|
||||
const selections=await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); const resource=performance.getEntriesByType('resource').find(entry=>new URL(entry.name).pathname==='/src/lib/editor/selection.ts'); const {selectedEditorText}=await import(resource.name); return monaco.editor.getModels().map(model=>selectedEditorText(model.uri.path.split('/')[1])).filter(Boolean).sort(); });
|
||||
assert.deepEqual(selections,['Origin','Second'],'Each pane retains its own selection');
|
||||
await openRight('a.md','Right note'); assert.equal(await page.locator('.document-pane').count(),2);
|
||||
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='notes/b.md');
|
||||
await openRight('notes/b.md','Original note'); assert.equal(await page.locator('.document-pane').count(),2);
|
||||
await page.waitForFunction(()=>document.activeElement?.closest('[data-document-path]')?.dataset.documentPath==='a.md');
|
||||
await append('notes/b.md','\nRight still unsaved.');
|
||||
for(const theme of ['light','dark']) {
|
||||
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
|
||||
await page.screenshot({path:`${output}/two-editors-${theme}.png`});
|
||||
}
|
||||
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
|
||||
assert.equal(await page.locator('.document-pane').count(),1); assert.equal(await pane('a.md').count(),1);
|
||||
assert.match(await text('a.md'),/Left unsaved/);
|
||||
assert.equal(await page.evaluate(async()=> { const {monaco}=await import('/src/lib/editor/monacoEnv.ts'); return monaco.editor.getModels().length; }),2,'Closing a split preserves both tab models');
|
||||
await page.getByRole('tab',{name:/b.md/}).click(); await pane('notes/b.md').locator('.cm-content').waitFor();
|
||||
assert.match(await text('notes/b.md'),/Right still unsaved/,'The closed split retains its unsaved buffer');
|
||||
await page.getByRole('tab',{name:/a.md/}).click(); await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
|
||||
await openRight('notes/b.md','Relative'); await pane('notes/c.md').locator('.cm-content').waitFor();
|
||||
assert.equal(await page.locator('.document-pane').count(),3);
|
||||
assert.match(await text('notes/c.md'),/Charlie/,'Relative links use the pane document folder');
|
||||
await pane('notes/c.md').getByRole('button',{name:'Close split',exact:true}).click();
|
||||
assert.equal(await page.locator('.document-pane').count(),2);
|
||||
await page.evaluate(()=>window.tabMenuTest.change('notes/b.md','# Bravo disk\n\nExternal update.\n'));
|
||||
await pane('notes/b.md').getByRole('alert').waitFor();
|
||||
assert.equal(await pane('a.md').getByRole('alert').count(),0);
|
||||
assert.match(await text('notes/b.md'),/Right still unsaved/,'A disk conflict preserves the right pane edits');
|
||||
await focus('a.md');
|
||||
await pane('notes/b.md').getByRole('button',{name:'Use disk version',exact:true}).click();
|
||||
await page.waitForFunction(()=>document.querySelector('[data-document-path="notes/b.md"] .cm-content')?.textContent.includes('External update.'));
|
||||
assert.match(await text('a.md'),/Left unsaved/,'Resolving the other pane cannot replace the primary buffer');
|
||||
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:740});
|
||||
for(const theme of ['light','dark']) {
|
||||
await page.evaluate(async mode=> { const {saveAppearance}=await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); },theme);
|
||||
const first=await pane('a.md').boundingBox(), second=await pane('notes/b.md').boundingBox();
|
||||
assert.ok(first.width>500 && second.width>500 && second.y>=first.y+first.height-1,'Narrow panes stack with readable widths');
|
||||
await page.screenshot({path:`${output}/stacked-${theme}.png`});
|
||||
}
|
||||
await append('notes/b.md','\nNarrow edit.'); await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Narrow edit.'));
|
||||
await pane('notes/b.md').getByRole('button',{name:'Close split',exact:true}).click();
|
||||
await append('a.md','\nAfter closing split.'); await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('After closing split.'));
|
||||
await page.setViewportSize({width:1440,height:1000});
|
||||
await openRight('a.md','Right note'); await pane('notes/b.md').locator('.cm-content').waitFor();
|
||||
await append('notes/b.md','\nClose guard.');
|
||||
await page.keyboard.press('Control+w');
|
||||
await page.waitForFunction(()=>window.tabMenuTest.prompts.length>0);
|
||||
assert.equal(await pane('notes/b.md').count(),1,'Cancel keeps the dirty split open');
|
||||
await page.keyboard.press('Control+s'); await page.waitForFunction(()=>window.tabMenuTest.files.get('notes/b.md').includes('Close guard.'));
|
||||
await page.keyboard.press('Control+w'); await pane('notes/b.md').waitFor({state:'detached'});
|
||||
await focus('a.md'); await append('a.md','\nOther tab closed.'); await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(()=>window.tabMenuTest.files.get('a.md').includes('Other tab closed.'));
|
||||
assert.equal(await page.evaluate(async()=>{const {monaco}=await import('/src/lib/editor/monacoEnv.ts');return monaco.editor.getModels().some(model=>model.uri.path.endsWith('/b.md'));}),false,'Closing the tab releases only its model');
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log(JSON.stringify({passed:['independent Writer/IDE/Reading modes','dirty close cancellation and model release','independent edits and saves','per-pane selections','focus existing duplicate target','closing split retains unsaved tabs and models','nested relative link origin','per-pane conflict resolution','narrow layout and save','light/dark screenshots'],nativeDesktop:'not tested'},null,2));
|
||||
} catch(error) { await page.screenshot({path:`${output}/failure.png`}); console.log(await page.locator('.status,.rs-menu').allTextContents()); throw error; } finally { await browser.close(); }
|
||||
@@ -0,0 +1,84 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } 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: 1400, height: 900 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
let sequence = 0;
|
||||
const state = { maximized: false, confirm: "Cancel", 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 = {}) => {
|
||||
state.calls.push(command);
|
||||
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 null;
|
||||
if (command === "plugin:window|is_maximized") return state.maximized;
|
||||
if (command === "plugin:window|toggle_maximize") { state.maximized = !state.maximized; emit("tauri://resize", { width: 1400, height: 900 }); return; }
|
||||
if (command === "plugin:window|minimize" || command === "plugin:window|destroy") return;
|
||||
if (command === "plugin:window|close") { emit("tauri://close-requested"); return; }
|
||||
if (command === "plugin:dialog|message") return state.confirm;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { state, emit };
|
||||
});
|
||||
try {
|
||||
const config = JSON.parse(await readFile(new URL("../../../src-tauri/tauri.conf.json", import.meta.url), "utf8"));
|
||||
assert.equal(config.app.windows[0].decorations, false);
|
||||
const capability = JSON.parse(await readFile(new URL("../../../src-tauri/capabilities/default.json", import.meta.url), "utf8"));
|
||||
for (const permission of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
|
||||
assert.ok(capability.permissions.includes(`core:window:allow-${permission}`));
|
||||
}
|
||||
await page.goto(process.env.SMOKE_URL || "http://localhost:1420");
|
||||
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
|
||||
// Native maximize/restore (e.g. double-clicking the drag region) updates the button too.
|
||||
await page.evaluate(() => { window.__TEST__.state.maximized = true; window.__TEST__.emit("tauri://resize", { width: 1920, height: 1080 }); });
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
|
||||
assert.ok(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|minimize")));
|
||||
await page.getByRole("button", { name: "Close window", exact: true }).focus();
|
||||
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
|
||||
// Opening the terminal engages the existing close guard; cancellation must not destroy the window.
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Close window", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:dialog|message"));
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.state.calls.includes("plugin:window|destroy")), false);
|
||||
await page.evaluate(() => window.__TEST__.state.confirm = "Ok");
|
||||
await page.getByRole("button", { name: "Close window", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.state.calls.includes("plugin:window|destroy"));
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
for (const width of [1400, 880]) {
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
const layout = await page.evaluate(() => {
|
||||
const header = document.querySelector(".header").getBoundingClientRect();
|
||||
const controls = [...document.querySelectorAll(".header button")].map(el => el.getBoundingClientRect());
|
||||
return { height: header.height, top: header.top, fits: controls.every(rect => rect.x >= 0 && rect.right <= innerWidth && rect.y >= header.y && rect.bottom <= header.bottom), drag: document.querySelector(".window-drag-space").getBoundingClientRect().width };
|
||||
});
|
||||
assert.equal(layout.height, 36);
|
||||
assert.equal(layout.top, 0);
|
||||
assert.ok(layout.fits);
|
||||
assert.ok(layout.drag >= 40);
|
||||
await page.screenshot({ path: `.audit/window-controls-${width}.png` });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Window controls smoke passed: actions, restore state, close guard, keyboard tooltip, and 1400/880px layouts.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,801 @@
|
||||
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } 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(10000);
|
||||
const errors = [];
|
||||
const showcase = await readFile(new URL("../../../fixtures/reader-showcase.md", import.meta.url), "utf8");
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
await mockFeaturePlugins(page);
|
||||
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
if (await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).count()) {
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
}
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
async function contents() {
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
|
||||
});
|
||||
}
|
||||
async function waitForText(text) {
|
||||
await page.evaluate(async () => { window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco; });
|
||||
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() === expected), text);
|
||||
}
|
||||
async function focusEditor() {
|
||||
await page.locator(".monaco-host .view-lines").click({position:{x:120,y:12}});
|
||||
}
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await quickOpen("welcome.md");
|
||||
const original = await contents();
|
||||
assert.ok(original.startsWith("---\ntitle:"));
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Added in source.");
|
||||
await waitForText(original + "Added in source.");
|
||||
await quickOpen("hello.py");
|
||||
await page.getByRole("tab", { name: /welcome\.md/ }).click();
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.waitForFunction(expected => window.__MONACO__.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getValue() !== expected), original + "Added in source.");
|
||||
await page.keyboard.press("Control+y");
|
||||
await waitForText(original + "Added in source.");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(expected => window.__TEST__.files.get("notes/welcome.md") === expected, original + "Added in source.");
|
||||
|
||||
await page.getByRole("button", { name: "Split", exact: true }).click();
|
||||
await page.locator(".md-page h1").first().waitFor();
|
||||
assert.ok(await page.locator(".monaco-host").isVisible());
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("notes/welcome.md", "# Agent update\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
|
||||
});
|
||||
await waitForText("# Agent update\n");
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Local edit");
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("notes/welcome.md", "# Another agent edit\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/welcome.md"] });
|
||||
});
|
||||
await page.getByRole("button", { name: "Keep my edits" }).waitFor();
|
||||
assert.equal(await contents(), "# Agent update\nLocal edit");
|
||||
await page.getByRole("button", { name: "Keep my edits" }).click();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("notes/welcome.md") === "# Agent update\nLocal edit");
|
||||
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_open"));
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(c => c.command === "pty_write" && /\x1b\[\d+;\d+R/.test(c.args.data)));
|
||||
await page.screenshot({ path: ".audit/core-rebuild-terminal.png" });
|
||||
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length), 0);
|
||||
await page.getByRole("button", { name: "Terminal", exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length), 1);
|
||||
await page.getByRole("button", { name: "New terminal", exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_open").length === 2);
|
||||
await page.getByRole("button", { name: "Kill terminal", exact: true }).first().click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.filter(c => c.command === "pty_close").length === 1);
|
||||
await page.getByRole("button", { name: "Hide terminal (sessions keep running)" }).click();
|
||||
await page.keyboard.press("Control+n");
|
||||
await page.getByLabel("New file path relative to the workspace").fill("notes/new-note.md");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await page.getByRole("tab", { name: "new-note.md", exact: true }).waitFor();
|
||||
await page.screenshot({ path: ".audit/core-rebuild.png" });
|
||||
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set("reader-showcase.md", text);
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
|
||||
}, showcase);
|
||||
await quickOpen("reader-showcase.md");
|
||||
const read = page.getByRole("button", { name: "Read", exact: true });
|
||||
assert.equal(await read.innerText(), "");
|
||||
assert.equal(await read.locator("svg").count(), 1);
|
||||
await read.hover();
|
||||
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
|
||||
const tip = await page.getByRole("tooltip", { name: "Read", exact: true }).boundingBox();
|
||||
assert.ok(tip.x >= 0 && tip.x + tip.width <= 1440);
|
||||
await read.click();
|
||||
assert.equal(await read.getAttribute("aria-pressed"), "true");
|
||||
await page.locator(".reading h1:not(.document-title)").waitFor();
|
||||
assert.equal(await page.locator(".monaco-host").isVisible(), false);
|
||||
assert.equal(await page.locator(".reading h1:not(.document-title)").innerText(), "Project field notes");
|
||||
assert.equal(await page.locator(".reading ol > li").count(), 3);
|
||||
assert.equal(await page.locator(".reading ol ul > li").count(), 2);
|
||||
assert.equal(await page.locator(".reading input:checked").count(), 2);
|
||||
assert.equal(await page.locator(".md-properties").getAttribute("open"), null);
|
||||
assert.ok((await page.locator(".reading > p").first().innerText()).includes("implementation notes"));
|
||||
const surface = await page.locator(".reading").boundingBox();
|
||||
assert.ok(surface.width <= 741);
|
||||
await page.mouse.move(700, 980);
|
||||
await page.screenshot({ path: ".audit/reader-mode.png" });
|
||||
await page.locator(".md-table-scroll").scrollIntoViewIfNeeded();
|
||||
await page.getByRole("button", { name: "Copy code", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Copied", exact: true }).waitFor();
|
||||
await page.screenshot({ path: ".audit/reader-details.png" });
|
||||
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await page.locator(".md-page").evaluate(element => { element.scrollTop = 0; });
|
||||
await page.screenshot({ path: ".audit/reader-narrow.png" });
|
||||
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
|
||||
await page.getByRole("button", { name: "Split", exact: true }).click();
|
||||
await page.waitForFunction(() => {
|
||||
const host = document.querySelector(".monaco-host");
|
||||
const rendered = host?.querySelector(".monaco-editor");
|
||||
return rendered && Math.abs(host.clientWidth - rendered.clientWidth) < 2;
|
||||
});
|
||||
assert.equal(await page.locator(".body.split").evaluate(element => getComputedStyle(element).flexDirection), "column");
|
||||
await page.screenshot({ path: ".audit/reader-split.png" });
|
||||
assert.ok(await page.locator(".md-page").evaluate(element => element.scrollWidth <= element.clientWidth + 1));
|
||||
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector(".body.split")).flexDirection === "row");
|
||||
await page.screenshot({ path: ".audit/reader-split-wide.png" });
|
||||
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).click();
|
||||
assert.equal(await contents(), showcase);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get("reader-showcase.md")), showcase);
|
||||
await page.getByRole("button", { name: "Read", exact: true }).focus();
|
||||
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "visible" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("tooltip", { name: "Read", exact: true }).waitFor({ state: "hidden" });
|
||||
|
||||
// Continuous live Markdown: only active lines reveal source; checkboxes
|
||||
// remain inline and update the original file without HTML serialization.
|
||||
const writingSource = '---\ntitle: Preserved\n---\n\n# Writer preview\n\nA **formatted** paragraph.\n\n[Project link](https://example.com/old)\n\n- [ ] Ship draft\n- [x] Finished task\n\n```mermaid\nflowchart LR\n A[Draft] --> B[Publish]\n```\n\n```mermaid\nnot a valid diagram\n```\n\n- Parent\n - Child\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set("writing.md", text);
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["writing.md"] });
|
||||
}, writingSource);
|
||||
await quickOpen("writing.md");
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
await writer.waitFor();
|
||||
assert.equal(await page.locator('.live-writer [contenteditable="true"]').count(), 1);
|
||||
assert.equal(await page.getByRole("toolbar", { name: "Text formatting" }).count(), 0);
|
||||
await page.locator(".live-writer .md-diagram svg").waitFor({ timeout: 30000 });
|
||||
await page.getByRole("status").filter({ hasText: "Diagram could not render" }).waitFor();
|
||||
const paragraph = page.locator(".live-writer .cm-line").filter({ hasText: "A formatted paragraph." });
|
||||
await paragraph.click();
|
||||
await page.locator(".live-writer .cm-line").filter({ hasText: "A **formatted** paragraph." }).waitFor();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.type("New ");
|
||||
await page.keyboard.press("Control+s");
|
||||
const editedSource = writingSource.replace("A **formatted**", "New A **formatted**");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, writingSource);
|
||||
await page.keyboard.press("Control+y");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("writing.md") === text, editedSource);
|
||||
await page.getByRole("button", { name: "Switch to IDE layout (Ctrl E)", exact: true }).click();
|
||||
await waitForText(editedSource);
|
||||
await focusEditor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await waitForText(writingSource);
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
await writer.waitFor();
|
||||
await paragraph.click();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("First new paragraph.");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("**Second new paragraph.**");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Third new paragraph.");
|
||||
assert.equal(await page.locator(".live-writer .writer-strong").filter({ hasText: "Second new paragraph." }).count(), 1);
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Shift+ArrowUp");
|
||||
await page.keyboard.press("Shift+ArrowUp");
|
||||
assert.ok((await page.evaluate(() => window.getSelection().toString())).includes("Second new paragraph."));
|
||||
await page.keyboard.press("Backspace");
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes("First new paragraph.\n\n**Second new paragraph.**\n\nThird new paragraph."));
|
||||
assert.ok(await writer.evaluate(el => el.contains(document.activeElement)));
|
||||
|
||||
// Link syntax becomes editable on a normal click, without opening the link.
|
||||
await page.locator('.live-writer .writer-link').filter({ hasText: "Project link" }).click();
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: "[Project link](https://example.com/old)" }).waitFor();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Shift+End");
|
||||
await page.keyboard.type("[Project link](https://example.com/new)");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.locator('.live-writer [data-href="https://example.com/new"]').waitFor();
|
||||
const task = page.locator('.live-writer .cm-line').filter({ hasText: "Ship draft" });
|
||||
const checkbox = task.getByRole("checkbox");
|
||||
assert.ok(await task.evaluate(line => {
|
||||
const box = line.querySelector('input').getBoundingClientRect();
|
||||
const text = [...line.childNodes].find(node => node.nodeType === Node.TEXT_NODE && node.textContent.includes('Ship draft'));
|
||||
const range = document.createRange(); range.selectNode(text);
|
||||
const label = range.getBoundingClientRect();
|
||||
return Math.abs((box.top + box.bottom) / 2 - (label.top + label.bottom) / 2) < 8 && box.right <= label.left;
|
||||
}));
|
||||
await checkbox.click();
|
||||
await task.locator('.writer-completed').waitFor();
|
||||
assert.equal(await task.locator('.writer-completed').evaluate(el => getComputedStyle(el).textDecorationLine), 'line-through');
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [x] Ship draft'));
|
||||
await task.locator('.writer-completed').click();
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: '- [x] Ship draft' }).waitFor();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Shift+End");
|
||||
await page.keyboard.type('- [ ] Revised task');
|
||||
await page.keyboard.press("ArrowUp");
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: 'Revised task' }).getByRole('checkbox', { checked: false }).waitFor();
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("writing.md").includes('- [ ] Revised task'));
|
||||
await page.locator(".live-writer .md-diagram svg").waitFor();
|
||||
await page.screenshot({ path: ".audit/writing-continuous.png" });
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
assert.ok(await page.locator(".cm-scroller").evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("crlf.md", "# Windows note\r\n\r\nA paragraph.\r\n\r\nTail stays intact.\r\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["crlf.md"] });
|
||||
});
|
||||
await quickOpen("crlf.md");
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
await page.locator(".live-writer .cm-line").filter({ hasText: "A paragraph." }).click();
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.type("Changed ");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("crlf.md") === "# Windows note\r\n\r\nChanged A paragraph.\r\n\r\nTail stays intact.\r\n");
|
||||
await page.keyboard.press("Control+n");
|
||||
await page.getByLabel("New file path relative to the workspace").fill("blank.md");
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await writer.waitFor();
|
||||
await page.keyboard.type("One");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Two");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Three");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
|
||||
await page.getByRole("tab", { name: "crlf.md", exact: true }).click();
|
||||
await page.getByRole("tab", { name: "blank.md", exact: true }).click();
|
||||
await writer.waitFor();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") !== "One\nTwo\nThree");
|
||||
await page.keyboard.press("Control+y");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "One\nTwo\nThree");
|
||||
await page.keyboard.press("Control+f");
|
||||
await page.getByRole("textbox", { name: "Find", exact: true }).fill("Two");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Control+a");
|
||||
await page.keyboard.type("- [ ] First task");
|
||||
await page.keyboard.press("Enter");
|
||||
await page.keyboard.type("Second task");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(() => window.__TEST__.files.get("blank.md").replace(/\r\n/g, "\n") === "- [ ] First task\n- [ ] Second task");
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("blank.md", "Fresh disk version\r\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["blank.md"] });
|
||||
});
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: 'Fresh disk version' }).waitFor();
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.ok((await writer.innerText()).includes("Fresh disk version"));
|
||||
|
||||
const tableSource = '# Table layout\n\n| Ticker | Name | Exchange | Products/Service | Notes |\n| :--- | --- | --- | --- | --- |\n| IBKR.US | Interactive Brokers Group Inc | NASDAQ | Broker | Rebuild the trading interface.<br>Keep listings consistent.<br>Introduce automated investing.<br>Make the API usable and document common errors. |\n| CBOE.US | Cboe Global Markets Inc | BATS | Exchange | Operations;<br>- Trading |\n\nAfter the table.\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set("tables.md", text);
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["tables.md"] });
|
||||
}, tableSource);
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await quickOpen("tables.md");
|
||||
await page.getByRole("button", { name: "Switch to writing layout (Ctrl E)", exact: true }).click();
|
||||
const table = page.locator('.live-writer table');
|
||||
await table.waitFor();
|
||||
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'tables');
|
||||
const tableHeading = page.locator('.live-writer .writer-heading');
|
||||
await tableHeading.click();
|
||||
assert.equal(await tableHeading.innerText(), '# Table layout');
|
||||
await table.locator('tbody tr').first().locator('td').first().click();
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer .writer-heading')?.textContent === 'Table layout');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), tableSource);
|
||||
assert.equal(await table.locator('th').count(), 5);
|
||||
assert.equal(await table.locator('tbody tr').count(), 2);
|
||||
assert.equal(await table.locator('br').count(), 4);
|
||||
assert.ok(!(await table.innerText()).includes('<br>'));
|
||||
assert.ok(await table.locator('th').evaluateAll(cells => cells.every(cell => cell.getBoundingClientRect().width >= 100)));
|
||||
assert.ok(await table.locator('td').evaluateAll(cells => cells.every(cell => getComputedStyle(cell).verticalAlign === 'top')));
|
||||
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
const addColumn = page.getByRole('button', { name: 'Add column to the right', exact: true });
|
||||
const addRow = page.getByRole('button', { name: 'Add row below', exact: true });
|
||||
await addColumn.hover();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
|
||||
assert.equal(await addRow.evaluate(el => getComputedStyle(el).opacity), '0');
|
||||
await table.locator('td').first().hover();
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.table-add')].every(button => getComputedStyle(button).opacity === '0'));
|
||||
await addColumn.hover();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-column')).opacity === '1');
|
||||
await page.screenshot({ path: '.audit/writing-table-column.png' });
|
||||
await addColumn.click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer th').length === 6);
|
||||
await addRow.hover();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.table-add-row')).opacity === '1');
|
||||
await page.screenshot({ path: '.audit/writing-table-row.png' });
|
||||
await addRow.click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 3);
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('| | | | | | |'));
|
||||
assert.ok((await page.evaluate(() => window.__TEST__.files.get('tables.md'))).endsWith('\n\nAfter the table.\n'));
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 2);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(expected => window.__TEST__.files.get('tables.md') === expected, tableSource);
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.keyboard.press('Control+y');
|
||||
await table.locator('th').last().click();
|
||||
const cellEditor = page.locator('.writer-cell-editor');
|
||||
await cellEditor.waitFor();
|
||||
assert.equal(await table.locator('th').count(), 6);
|
||||
assert.equal(await page.locator('.live-writer .cm-line').filter({ hasText: '| Ticker |' }).count(), 0);
|
||||
await page.keyboard.type('New column');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('New column'));
|
||||
await page.keyboard.press('Tab');
|
||||
assert.ok(await table.locator('tbody tr').first().locator('td').first().locator('.writer-cell-editor').count());
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
assert.ok(await table.locator('th').last().locator('.writer-cell-editor').count());
|
||||
await table.locator('tbody tr').first().locator('td').nth(4).click();
|
||||
assert.equal(await cellEditor.locator('br:not(.ProseMirror-trailingBreak)').count(), 3);
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.keyboard.type('Plain | pipe and *stars*');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('<br>Plain \\| pipe and \\*stars\\*'));
|
||||
assert.equal(await table.locator('th').count(), 6);
|
||||
await page.screenshot({ path: '.audit/writing-table-cell-edit.png' });
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => !window.__TEST__.files.get('tables.md').includes('Plain'));
|
||||
await cellEditor.waitFor();
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('tables.md').includes('Plain'));
|
||||
await page.keyboard.press('Escape');
|
||||
await page.locator('.live-writer .cm-line').filter({ hasText: 'After the table.' }).click();
|
||||
const beforeVisit = await page.evaluate(() => window.__TEST__.files.get('tables.md'));
|
||||
await table.locator('tbody tr').first().locator('td').nth(4).click();
|
||||
await page.keyboard.press('Escape');
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('tables.md')), beforeVisit);
|
||||
await table.locator('tbody tr').last().locator('td').last().click();
|
||||
await page.keyboard.press('Tab');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer tbody tr').length === 4);
|
||||
await table.locator('tbody tr').last().locator('td').first().locator('.writer-cell-editor').waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
assert.ok(await page.locator('.cm-scroller').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
assert.equal(await page.locator('.md-page .document-title').innerText(), 'tables');
|
||||
assert.equal(await page.locator('.md-page table br').count(), 5);
|
||||
assert.ok(await page.locator('.md-page').evaluate(el => el.scrollWidth <= el.clientWidth + 1));
|
||||
|
||||
const selectionTable = '| A | B | C |\n| --- | --- | --- |\n| one | two | three |\n| four | five | six |\n\nAfter.\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('selection-table.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['selection-table.md'] });
|
||||
window.__TEST__.clipboard = '';
|
||||
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: {
|
||||
writeText: async text => { window.__TEST__.clipboard = text; },
|
||||
readText: async () => window.__TEST__.clipboard,
|
||||
} });
|
||||
}, selectionTable);
|
||||
await quickOpen('selection-table.md');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
const selectedTable = page.locator('.live-writer table');
|
||||
const selectedCell = (r, c) => selectedTable.locator('tr').nth(r).locator('th, td').nth(c);
|
||||
const fromCell = await selectedCell(1, 0).boundingBox(), toCell = await selectedCell(2, 1).boundingBox();
|
||||
await page.mouse.move(fromCell.x + 15, fromCell.y + 15);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(toCell.x + 15, toCell.y + 15, { steps: 12 });
|
||||
await page.mouse.up();
|
||||
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
|
||||
await selectedCell(1, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name: 'Bold', exact: true }).waitFor();
|
||||
await page.screenshot({ path: '.audit/table-cell-selection-menu.png' });
|
||||
await page.getByRole('menuitem', { name: 'Bold', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 4);
|
||||
await page.waitForFunction(() => document.querySelectorAll('.is-cell-selected').length === 4);
|
||||
await page.keyboard.press('Control+i');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 4);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table em').length === 0);
|
||||
assert.equal(await selectedTable.locator('strong').count(), 4);
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
|
||||
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 4);
|
||||
async function cellAction(name, formatted = false) {
|
||||
await selectedTable.locator('.is-cell-selected').first().click({ button: 'right' });
|
||||
if (formatted) await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name, exact: true }).click();
|
||||
}
|
||||
await cellAction('Clear formatting', true);
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table strong').length === 0);
|
||||
await cellAction('Copy');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'one\ttwo\nfour\tfive');
|
||||
await cellAction('Cut');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => !cell.textContent.trim()));
|
||||
await cellAction('Paste');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
|
||||
await cellAction('Align centre');
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.is-cell-selected')].every(cell => cell.style.textAlign === 'center'));
|
||||
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]'], ['Code', 'code'], ['Strikethrough', 's']]) {
|
||||
await cellAction(name, true);
|
||||
await page.waitForFunction(selector => document.querySelectorAll(`.live-writer table ${selector}`).length === 4, selector);
|
||||
await cellAction('Clear formatting', true);
|
||||
}
|
||||
// Native clipboard events must operate on the rectangle, including one-step undo.
|
||||
await page.locator('.writer-table').evaluate(el => {
|
||||
const data = new DataTransfer(); data.setData('text/plain', 'red\tblue\ngreen\tyellow');
|
||||
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'red');
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(2, 1).click({ modifiers: ['Shift'] });
|
||||
await cellAction('Delete cells');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'three');
|
||||
assert.equal(await selectedTable.locator('th').count(), 3);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer tbody td').textContent === 'one');
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
|
||||
await page.keyboard.press('Control+a');
|
||||
assert.equal(await selectedTable.locator('.is-cell-selected').count(), 9);
|
||||
await cellAction('Delete cells');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table').length === 0);
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectedTable.waitFor();
|
||||
for (const [name, selector] of [['Highlight', 'mark'], ['Math', '[data-cell-format="math"]'], ['Comment', '[data-cell-format="comment"]']]) {
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
|
||||
await selectedCell(1, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Format', exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name, exact: true }).click();
|
||||
await selectedCell(1, 0).click();
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.type(' edited');
|
||||
await page.keyboard.press('Escape');
|
||||
assert.ok(await selectedCell(1, 0).locator(selector).count(), `${name} survives cell editing`);
|
||||
await selectedCell(1, 0).click();
|
||||
await selectedCell(1, 0).click({ modifiers: ['Shift'] });
|
||||
await selectedCell(1, 0).click({ button: 'right' });
|
||||
await cellAction('Clear formatting', true);
|
||||
}
|
||||
|
||||
const actionsSource = '| Name | Value |\n| :--- | ---: |\n| Interactive Brokers Group | 20 |\n| Apple | 3 |\n| Pear | 10 |\n\nAfter.\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('table-actions.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-actions.md'] });
|
||||
}, actionsSource);
|
||||
await quickOpen('table-actions.md');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
const actionTable = page.locator('.live-writer table');
|
||||
const actionCell = (r, c) => actionTable.locator('tr').nth(r).locator('th, td').nth(c);
|
||||
async function actionItem(label, group, r = 1, c = 0) {
|
||||
await actionCell(r, c).click({ button: 'right' });
|
||||
if (group) await page.getByRole('menuitem', { name: group, exact: true }).hover();
|
||||
await page.getByRole('menuitem', { name: label, exact: true }).click();
|
||||
}
|
||||
async function saveActionSource() {
|
||||
await page.keyboard.press('Control+s');
|
||||
return page.evaluate(() => window.__TEST__.files.get('table-actions.md'));
|
||||
}
|
||||
async function undoAction() {
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(expected => window.__TEST__.files.get('table-actions.md') === expected, actionsSource);
|
||||
}
|
||||
for (const [label, group, r, c, rows, columns] of [
|
||||
['Add row above', 'Row', 1, 0, 5, 2], ['Add row below', 'Row', 2, 0, 5, 2], ['Duplicate row', 'Row', 1, 0, 5, 2], ['Delete row', 'Row', 1, 0, 3, 2],
|
||||
['Add column to the left', 'Column', 1, 0, 4, 3], ['Add column to the right', 'Column', 1, 1, 4, 3], ['Duplicate column', 'Column', 1, 1, 4, 3], ['Delete column', 'Column', 1, 1, 4, 1],
|
||||
]) {
|
||||
await actionItem(label, group, r, c);
|
||||
assert.equal(await actionTable.locator('tr').count(), rows, label);
|
||||
assert.equal(await actionTable.locator('th').count(), columns, label);
|
||||
await undoAction();
|
||||
}
|
||||
await actionItem('Move row down', 'Row');
|
||||
assert.equal(await actionCell(2, 0).innerText(), 'Interactive Brokers Group');
|
||||
await undoAction();
|
||||
await actionItem('Move row up', 'Row', 2);
|
||||
assert.equal(await actionCell(1, 0).innerText(), 'Apple');
|
||||
await undoAction();
|
||||
await actionItem('Move column right', 'Column');
|
||||
assert.equal(await actionCell(0, 0).innerText(), 'Value');
|
||||
assert.equal(await actionCell(1, 0).evaluate(el => el.style.textAlign), 'right');
|
||||
await undoAction();
|
||||
await actionItem('Move column left', 'Column', 1, 1);
|
||||
assert.equal(await actionCell(0, 0).innerText(), 'Value');
|
||||
await undoAction();
|
||||
await actionItem('Sort by column (A to Z)', undefined, 1, 1);
|
||||
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['3', '10', '20']);
|
||||
await undoAction();
|
||||
await actionItem('Sort by column (Z to A)', undefined, 1, 1);
|
||||
assert.deepEqual(await actionTable.locator('tbody tr td:last-child').allTextContents(), ['20', '10', '3']);
|
||||
await undoAction();
|
||||
await actionCell(0, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
|
||||
assert.ok(await page.getByRole('menuitem', { name: 'Add row above', exact: true }).isDisabled());
|
||||
assert.ok(await page.getByRole('menuitem', { name: 'Move row down', exact: true }).isDisabled());
|
||||
await page.keyboard.press('Escape');
|
||||
async function selectBrokers() {
|
||||
await actionCell(1, 0).click();
|
||||
await page.keyboard.press('Control+Home');
|
||||
for (let i = 0; i < 12; i++) await page.keyboard.press('ArrowRight');
|
||||
for (let i = 0; i < 7; i++) await page.keyboard.press('Shift+ArrowRight');
|
||||
assert.equal(await page.evaluate(() => getSelection().toString()), 'Brokers');
|
||||
}
|
||||
await selectBrokers();
|
||||
await actionCell(1, 0).click({ button: 'right' });
|
||||
assert.equal(await page.getByRole('menuitem', { name: 'Copy', exact: true }).isDisabled(), false);
|
||||
assert.ok(await page.locator('.table-cell-menu button').evaluateAll(buttons => buttons.every(button => button.querySelector('svg[aria-hidden="true"]'))));
|
||||
await page.getByRole('menuitem', { name: 'Row', exact: true }).hover();
|
||||
await page.screenshot({ path: '.audit/table-text-row-menu.png' });
|
||||
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
|
||||
await page.screenshot({ path: '.audit/table-text-column-menu.png' });
|
||||
await page.getByRole('menuitem', { name: 'Column', exact: true }).focus();
|
||||
await page.keyboard.press('ArrowRight');
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Add column to the left');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
assert.equal(await page.evaluate(() => document.activeElement.textContent), 'Column');
|
||||
await page.keyboard.press('Escape');
|
||||
await actionItem('Bold', 'Format');
|
||||
assert.equal(await actionCell(1, 0).locator('strong').innerText(), 'Brokers');
|
||||
assert.ok((await saveActionSource()).includes('Interactive **Brokers** Group'));
|
||||
await actionItem('Add external link');
|
||||
await page.getByRole('dialog').locator('input').fill('https://example.com/brokers?q=1');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === 'https://example.com/brokers?q=1');
|
||||
assert.equal(await actionCell(1, 0).locator('a').innerText(), 'Brokers');
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await actionItem('Add link');
|
||||
await page.getByRole('dialog').locator('input').fill('notes/second');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('data-kind') === 'wiki');
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await actionItem('Search for “Brokers”');
|
||||
await page.getByPlaceholder('Search files and notes').waitFor();
|
||||
assert.equal(await page.getByPlaceholder('Search files and notes').inputValue(), 'Brokers');
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'workspace_search' && call.args.query === 'Brokers'));
|
||||
await selectBrokers();
|
||||
await actionItem('Extract current selection…');
|
||||
await page.getByRole('dialog').locator('input').fill('extracted-brokers.md');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('extracted-brokers.md') === '**Brokers**\n');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td a')?.getAttribute('href') === '/extracted-brokers.md');
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await page.evaluate(() => { window.__TEST__.clipboard = '<b>literal</b>\nnext'; });
|
||||
await actionItem('Paste as plain text');
|
||||
assert.ok((await saveActionSource()).includes('Interactive <') || (await saveActionSource()).includes('Interactive \\<b\\>literal\\</b\\><br>next'));
|
||||
assert.equal(await actionCell(1, 0).locator('b').count(), 0);
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await page.evaluate(() => {
|
||||
navigator.clipboard.read = async () => [{ types: ['text/html', 'text/plain'], getType: async type => new Blob([type === 'text/html' ? '<em>Rich paste</em>' : 'Rich paste'], { type }) }];
|
||||
});
|
||||
await actionItem('Paste');
|
||||
await page.waitForFunction(() => document.querySelector('.live-writer td em')?.textContent === 'Rich paste');
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.evaluate(() => { delete navigator.clipboard.read; });
|
||||
await selectBrokers();
|
||||
await actionItem('Copy');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), 'Brokers');
|
||||
await actionItem('Cut');
|
||||
await page.waitForFunction(() => !document.querySelector('.live-writer td').textContent.includes('Brokers'));
|
||||
await page.keyboard.press('Control+z');
|
||||
await selectBrokers();
|
||||
await actionItem('Select all');
|
||||
assert.equal(await page.evaluate(() => getSelection().toString()), 'Interactive Brokers Group');
|
||||
await page.setViewportSize({ width: 800, height: 600 });
|
||||
await actionCell(1, 0).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Column', exact: true }).hover();
|
||||
assert.ok(await page.locator('.table-cell-menu, .table-cell-submenu:not([hidden])').evaluateAll(panels => panels.every(panel => {
|
||||
const rect = panel.getBoundingClientRect(); return rect.left >= 0 && rect.top >= 0 && rect.right <= innerWidth && rect.bottom <= innerHeight;
|
||||
})));
|
||||
await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
|
||||
const richTable = '| Name | Notes |\r\n| :--- | ---: |\r\n| Untouched | ~~Old~~ **bold** [link](https://example.com) <br />Next |\r\n| Short |\r\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('rich-table.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['rich-table.md'] });
|
||||
}, richTable);
|
||||
await quickOpen('rich-table.md');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
const richCell = page.locator('.live-writer tbody tr').first().locator('td').last();
|
||||
assert.equal(await page.locator('.live-writer .document-title').innerText(), 'rich-table');
|
||||
await richCell.click();
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('rich-table.md')), richTable);
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.type(' edited');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('edited'));
|
||||
const richSaved = await page.evaluate(() => window.__TEST__.files.get('rich-table.md'));
|
||||
assert.ok(richSaved.includes('| Untouched |'));
|
||||
assert.ok(richSaved.includes('~~Old~~'));
|
||||
assert.ok(richSaved.includes('**bold**'));
|
||||
assert.ok(richSaved.includes('https://example.com'));
|
||||
assert.ok(richSaved.includes(''));
|
||||
assert.ok(richSaved.includes('<br>Next edited'));
|
||||
assert.ok(!/(?<!\r)\n/.test(richSaved));
|
||||
await page.keyboard.press('Escape');
|
||||
await richCell.click();
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.type(' again');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Next edited again'));
|
||||
const shortCell = page.locator('.live-writer tbody tr').last().locator('td').last();
|
||||
await shortCell.click();
|
||||
await cellEditor.evaluate(el => {
|
||||
const data = new DataTransfer(); data.setData('text/plain', 'Pasted | text\nSecond line');
|
||||
el.dispatchEvent(new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }));
|
||||
});
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('Pasted \\| text<br>Second line'));
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.press('Control+b');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('rich-table.md').includes('**Pasted \\| text**'));
|
||||
assert.equal(await page.locator('.live-writer th').count(), 2);
|
||||
|
||||
// Physical mouse coordinates below tall block widgets must resolve to the
|
||||
// visible line, including immediately adjacent heading/body lines.
|
||||
const longTable = '| Ticker | Name | Notes |\n| --- | --- | --- |\n' +
|
||||
Array.from({ length: 14 }, (_, index) => `| STOCK${index} | Company ${index} | First note<br>Second note<br>Third note |`).join('\n');
|
||||
const hitTestSource = `# Listed\n\n${longTable}\n\n# Tier 1\nTier one body directly below heading.\n\n${longTable}\n\n## Tier 2\nTier two body directly below heading.\n`;
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('table-hit-testing.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['table-hit-testing.md'] });
|
||||
}, hitTestSource);
|
||||
await quickOpen('table-hit-testing.md');
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
async function clickRenderedLine(locator, expected) {
|
||||
await locator.scrollIntoViewIfNeeded();
|
||||
const rect = await locator.boundingBox();
|
||||
assert.ok(rect);
|
||||
await page.mouse.click(rect.x + 45, rect.y + rect.height * .7);
|
||||
const actual = await page.evaluate(() => window.getSelection()?.anchorNode?.parentElement?.closest('.cm-line')?.textContent);
|
||||
assert.equal(actual, expected, `Mouse click on ${expected} landed on ${actual}`);
|
||||
}
|
||||
async function checkLinesAfterTables() {
|
||||
await page.locator('.cm-scroller').evaluate(async el => {
|
||||
el.scrollTop = 0;
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
});
|
||||
for (const [heading, body] of [
|
||||
['# Tier 1', 'Tier one body directly below heading.'],
|
||||
['## Tier 2', 'Tier two body directly below heading.'],
|
||||
]) {
|
||||
const tables = page.locator('.live-writer .writer-table');
|
||||
await (heading === '# Tier 1' ? tables.first() : tables.last()).locator('.table-add-row').scrollIntoViewIfNeeded();
|
||||
await clickRenderedLine(page.locator('.live-writer .writer-heading').filter({ hasText: heading.replace(/^#+ /, '') }), heading);
|
||||
await page.keyboard.press('End');
|
||||
await page.keyboard.type(' edited');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(text => window.__TEST__.files.get('table-hit-testing.md').includes(text + ' edited\n'), heading);
|
||||
await page.keyboard.press('Control+z');
|
||||
await clickRenderedLine(page.locator('.live-writer .cm-line').filter({ hasText: body }), body);
|
||||
}
|
||||
}
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
await checkLinesAfterTables();
|
||||
await page.locator('.cm-scroller').evaluate(async el => {
|
||||
el.scrollTop = 0;
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
});
|
||||
await page.locator('.live-writer table').first().locator('tbody tr').last().locator('td').last().click();
|
||||
await page.keyboard.press('Control+End');
|
||||
for (let line = 0; line < 4; line++) {
|
||||
await page.keyboard.press('Enter');
|
||||
await page.keyboard.type('A newly added line changes the table height.');
|
||||
}
|
||||
await checkLinesAfterTables();
|
||||
await page.setViewportSize({ width: 1000, height: 900 });
|
||||
await checkLinesAfterTables();
|
||||
await page.screenshot({ path: '.audit/table-cursor-position.png' });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: continuous live Markdown, raw active lines, editable links and checklists, completed-task strikethrough, cross-line selection, preservation and history, search, table layout/line breaks/edge insertion/cell editing/undo, save, agent refresh, conflicts, persistent terminals, reader and Mermaid previews, narrow layouts (mocked desktop IPC).");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
console.error("Writing source:", await page.evaluate(() => window.__TEST__?.files.get("writing.md")));
|
||||
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 5000));
|
||||
await page.screenshot({ path: ".audit/core-rebuild-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -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(); }
|
||||
@@ -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(); }
|
||||
@@ -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(); }
|
||||
@@ -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(); }
|
||||
@@ -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(); }
|
||||
|
||||
@@ -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();}
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
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| Name | Value |\n| --- | --- |\n| Alpha | One |\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") {
|
||||
if (window.spellingTest.delay) return new Promise(resolve => window.spellingTest.resolve = resolve);
|
||||
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") throw new Error("Keep unsaved edits for the close test");
|
||||
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 });
|
||||
async function metrics(panel) {
|
||||
return panel.evaluate(node => {
|
||||
const row = node.querySelector(":scope > button");
|
||||
const icon = row.querySelector(".action-icon");
|
||||
const label = row.querySelector(".action-label");
|
||||
const css = getComputedStyle(node), button = getComputedStyle(row);
|
||||
return {
|
||||
panel: [css.padding, css.borderRadius, css.backgroundColor, css.color, css.boxShadow, css.font],
|
||||
row: [button.padding, button.minHeight, button.borderRadius, button.gap, button.font],
|
||||
iconWidth: icon.getBoundingClientRect().width,
|
||||
inset: Math.round(row.getBoundingClientRect().left - node.getBoundingClientRect().left),
|
||||
labelOffset: Math.round(label.getBoundingClientRect().left - row.getBoundingClientRect().left),
|
||||
};
|
||||
});
|
||||
}
|
||||
async function dismiss() { await page.keyboard.press("Escape"); await page.locator(".rs-menu").waitFor({ state: "detached" }); }
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
const row = page.locator('[data-tree-rel="a.md"]');
|
||||
await row.waitFor();
|
||||
await row.click();
|
||||
const tab = page.getByRole("tab", { name: "a.md", exact: true });
|
||||
await tab.waitFor();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 800; canvas.height = 600;
|
||||
const context = canvas.getContext('2d');
|
||||
const gradient = context.createLinearGradient(0, 0, 800, 600);
|
||||
gradient.addColorStop(0, '#628ba8'); gradient.addColorStop(1, '#b47796');
|
||||
context.fillStyle = gradient; context.fillRect(0, 0, 800, 600);
|
||||
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: 0.15, position: 'center', size: 'cover' } });
|
||||
}, theme);
|
||||
await row.focus();
|
||||
await row.click({ button: "right" });
|
||||
const file = menu("File actions");
|
||||
await file.waitFor();
|
||||
const reference = await metrics(file);
|
||||
assert.equal(reference.row[1], "24px", "Menus use compact shared rows");
|
||||
assert.equal(reference.row[0], "2px 10px");
|
||||
const compactHeight = await file.evaluate(node => node.getBoundingClientRect().height);
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.style.setProperty('--rs-menu-row-height', '30px');
|
||||
document.documentElement.style.setProperty('--rs-menu-row-padding', '4px 10px');
|
||||
});
|
||||
const previousHeight = await file.evaluate(node => node.getBoundingClientRect().height);
|
||||
await page.screenshot({ path: '.audit/todo-2026-10-14/menu-spacing-before-' + theme + '.png' });
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.style.removeProperty('--rs-menu-row-height');
|
||||
document.documentElement.style.removeProperty('--rs-menu-row-padding');
|
||||
});
|
||||
assert.ok(compactHeight < previousHeight * .85, 'The same actions use at least 15% less vertical space');
|
||||
console.log(JSON.stringify({ theme, compactHeight, previousHeight }));
|
||||
await page.screenshot({ path: '.audit/todo-2026-10-14/menu-spacing-after-' + theme + '.png' });
|
||||
assert.ok(reference.panel[2].includes('/ 0.82') || /rgba\(.+, 0\.82\)/.test(reference.panel[2]), "Shared menus retain an 82% surface tint");
|
||||
assert.ok(reference.inset >= 5, "Rows need an inset from the panel border");
|
||||
assert.equal(await item("Pin").locator("svg.action-icon").count(), 1);
|
||||
const offsets = await file.locator(":scope > button").evaluateAll(nodes => nodes.map(node => Math.round(node.querySelector(".action-label").getBoundingClientRect().left - node.getBoundingClientRect().left)));
|
||||
assert.equal(new Set(offsets).size, 1, "All file labels align");
|
||||
await page.screenshot({ path: ".audit/menu-file-" + theme + ".png" });
|
||||
await dismiss();
|
||||
assert.equal(await row.evaluate(node => node === document.activeElement), true);
|
||||
await page.getByRole("navigation", { name: "Workspace files" }).click({ button: "right", position: { x: 100, y: 350 } });
|
||||
await file.waitFor();
|
||||
assert.deepEqual(await metrics(file), reference, "Pane and file menus share styles");
|
||||
assert.equal(await item("Show in Explorer").locator("svg.action-icon").count(), 1);
|
||||
await page.keyboard.press("End");
|
||||
assert.equal(await item("Show in Explorer").evaluate(node => node === document.activeElement), true);
|
||||
await page.keyboard.press("Enter");
|
||||
await file.waitFor({ state: "detached" });
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "", "Pane action opens the workspace root");
|
||||
await row.click({ button: "right" });
|
||||
await item("Show in Explorer").click();
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "a.md", "File action reveals the selected file");
|
||||
await page.locator('[data-tree-rel="notes"]').click({ button: "right" });
|
||||
assert.deepEqual(await metrics(file), reference, "Folder and file menus share styles");
|
||||
await dismiss();
|
||||
await tab.click({ button: "right" });
|
||||
const tabs = menu("Tab actions");
|
||||
assert.deepEqual(await metrics(tabs), reference, "Tab and file menus share styles");
|
||||
await item("Close tabs after").hover();
|
||||
assert.equal(await item("Close tabs after").evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)");
|
||||
await item("Move tab").focus();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.deepEqual(await metrics(menu("Move tab")), reference, "Submenus share styles");
|
||||
await page.screenshot({ path: ".audit/menu-tab-" + theme + ".png" });
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
assert.equal(await item("Move tab").evaluate(node => node === document.activeElement), true);
|
||||
await dismiss();
|
||||
await page.getByText("Original text.", { exact: true }).click();
|
||||
await page.keyboard.press("Shift+F10");
|
||||
const editor = menu("Markdown text actions");
|
||||
assert.deepEqual(await metrics(editor), reference, "Editor and file menus share styles");
|
||||
await item("Paragraph").focus();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.deepEqual(await metrics(menu("Paragraph")), reference);
|
||||
await page.screenshot({ path: ".audit/menu-editor-" + theme + ".png" });
|
||||
await dismiss();
|
||||
await page.locator(".live-writer td").first().click({ button: "right" });
|
||||
assert.deepEqual(await metrics(menu("Table actions")), reference, "Table and file menus share styles");
|
||||
await dismiss();
|
||||
const wordPoint = await page.getByText("Original text.", { exact: true }).evaluate(element => {
|
||||
const node = element.firstChild;
|
||||
const range = document.createRange();
|
||||
range.setStart(node, 0); range.setEnd(node, "Original".length);
|
||||
const bounds = range.getBoundingClientRect();
|
||||
return { x: bounds.left + bounds.width / 2, y: bounds.top + bounds.height / 2 };
|
||||
});
|
||||
await page.mouse.click(wordPoint.x, wordPoint.y, { button: "right" });
|
||||
await editor.waitFor();
|
||||
assert.deepEqual(await metrics(editor), reference, "Word and blank-space menus share styles");
|
||||
assert.equal(await item("Format").count(), 1, "Words retain the Markdown actions");
|
||||
await dismiss();
|
||||
await page.evaluate(() => {
|
||||
const input = document.createElement("input");
|
||||
input.id = "native-spelling-test";
|
||||
input.spellcheck = true;
|
||||
input.value = "Original";
|
||||
Object.assign(input.style, { position: "fixed", left: "500px", top: "100px" });
|
||||
document.body.append(input);
|
||||
input.focus();
|
||||
input.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
|
||||
});
|
||||
await page.evaluate(() => window.spellingTest.emit({ request: "spelling-1", items: [
|
||||
{ id: 71, name: "suggestion", label: "Original", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
|
||||
{ id: 72, name: "addToDictionary", label: "Add to dictionary", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
|
||||
{ id: 0, name: "", label: "", shortcut: "", kind: 3, enabled: false, checked: false, children: [] },
|
||||
{ id: 73, name: "cut", label: "Cu&t", shortcut: "Ctrl+X", kind: 0, enabled: false, checked: false, children: [] },
|
||||
{ id: 74, name: "copy", label: "&Copy", shortcut: "Ctrl+C", kind: 0, enabled: true, checked: false, children: [] },
|
||||
{ id: 75, name: "spellCheck", label: "Spell check", shortcut: "", kind: 1, enabled: true, checked: true, children: [] },
|
||||
] }));
|
||||
const spelling = menu("Spelling actions");
|
||||
await spelling.waitFor();
|
||||
assert.deepEqual(await metrics(spelling), reference, "Spelling and file menus share styles");
|
||||
assert.equal(await item("Add to dictionary").locator("svg.action-icon").count(), 1);
|
||||
assert.equal(await page.getByRole("menuitemcheckbox", { name: "Spell check" }).getAttribute("aria-checked"), "true");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
assert.equal(await item("Copy Ctrl+C").evaluate(node => node === document.activeElement), true, "Spelling keyboard navigation skips disabled commands");
|
||||
await page.screenshot({ path: ".audit/menu-spelling-" + theme + ".png" });
|
||||
await page.keyboard.press("Home");
|
||||
await page.keyboard.press("Enter");
|
||||
await spelling.waitFor({ state: "detached" });
|
||||
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "spelling-1", command: 71 });
|
||||
assert.equal(await page.locator("#native-spelling-test").evaluate(node => node === document.activeElement), true);
|
||||
async function emitSpelling(request) {
|
||||
await page.evaluate(request => window.spellingTest.emit({ request, items: [
|
||||
{ id: 81, name: "suggestion", label: "Replacement", shortcut: "", kind: 0, enabled: true, checked: false, children: [] },
|
||||
] }), request);
|
||||
await spelling.waitFor();
|
||||
}
|
||||
await emitSpelling("cancel");
|
||||
await dismiss();
|
||||
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "cancel", command: null });
|
||||
await emitSpelling("outside");
|
||||
await row.click();
|
||||
await spelling.waitFor({ state: "detached" });
|
||||
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "outside", command: null });
|
||||
await emitSpelling("old");
|
||||
await emitSpelling("new");
|
||||
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null });
|
||||
await dismiss();
|
||||
await page.evaluate(() => {
|
||||
window.spellingTest.delay = true;
|
||||
const input = document.querySelector('#native-spelling-test');
|
||||
input.value = 'recieved'; input.focus(); input.setSelectionRange(3, 3);
|
||||
input.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }));
|
||||
window.spellingTest.emit({ request: 'delayed-spelling', fallback_spelling: true, items: [
|
||||
{ id: 90, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] },
|
||||
] });
|
||||
});
|
||||
await spelling.waitFor();
|
||||
assert.equal(await item('Copy').count(), 1, 'Editing actions appear before the spelling service resolves');
|
||||
await page.evaluate(() => { window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true }); window.spellingTest.delay = false; });
|
||||
await item('received').waitFor();
|
||||
await page.screenshot({ path: `.audit/menu-spelling-async-${theme}.png` });
|
||||
await dismiss();
|
||||
await page.evaluate(() => {
|
||||
window.spellingTest.delay = true;
|
||||
document.querySelector('#native-spelling-test').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }));
|
||||
window.spellingTest.emit({ request: 'dismissed-spelling', fallback_spelling: true, items: [
|
||||
{ id: 91, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] },
|
||||
] });
|
||||
});
|
||||
await spelling.waitFor();
|
||||
await dismiss();
|
||||
await page.evaluate(async () => {
|
||||
window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true });
|
||||
window.spellingTest.delay = false;
|
||||
await new Promise(resolve => requestAnimationFrame(resolve));
|
||||
});
|
||||
assert.equal(await spelling.count(), 0, 'Late spelling results cannot reopen a dismissed menu');
|
||||
await page.evaluate(() => { document.querySelector('#native-spelling-test').value = 'Original'; });
|
||||
await page.locator("#native-spelling-test").evaluate(node => node.remove());
|
||||
await page.evaluate(() => {
|
||||
const input = document.createElement("input");
|
||||
input.spellcheck = false;
|
||||
document.body.append(input);
|
||||
input.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
|
||||
window.spellingTest.emit({ request: "ordinary-input", items: [] });
|
||||
input.remove();
|
||||
});
|
||||
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "ordinary-input", command: null, fallback: true });
|
||||
}
|
||||
await page.setViewportSize({ width: 420, height: 320 });
|
||||
await page.evaluate(async () => {
|
||||
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
|
||||
const root = actionMenu(418, 318, [{ label: "Modifier toutes les occurrences dans le document", icon: "select", shortcut: "Ctrl+F2" }], () => root.remove(), "Long translated label");
|
||||
});
|
||||
const translated = menu("Long translated label");
|
||||
assert(await translated.locator('.action-label').evaluate(node => {
|
||||
const css = getComputedStyle(node);
|
||||
return css.whiteSpace === 'normal' && css.textOverflow !== 'ellipsis' && node.scrollWidth <= node.clientWidth;
|
||||
}), 'Long translated actions wrap without truncation');
|
||||
await page.screenshot({ path: '.audit/menu-translated-long-label.png' });
|
||||
await dismiss();
|
||||
await page.evaluate(async () => {
|
||||
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
|
||||
const root = actionMenu(418, 318, [
|
||||
{ label: "Without icon", run: () => {} },
|
||||
{ label: "With icon", icon: "copy", run: () => {} },
|
||||
{ label: "Unavailable", icon: "trash", disabled: true },
|
||||
{ label: "More", icon: "plus", children: [
|
||||
{ label: "Languages", children: [{ label: "English", checked: true, run: () => {} }] },
|
||||
...Array.from({ length: 30 }, (_, i) => ({ label: "Action " + i, icon: "copy" })),
|
||||
] },
|
||||
], () => root.remove(), "Edge test");
|
||||
});
|
||||
const edge = menu("Edge test");
|
||||
const offsets = await edge.locator(":scope > button").evaluateAll(nodes => nodes.map(node => node.querySelector(".action-label").getBoundingClientRect().left));
|
||||
assert.equal(new Set(offsets).size, 1, "Iconless labels keep the icon column");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("ArrowDown");
|
||||
assert.equal(await item("More").evaluate(node => node === document.activeElement), true, "Keyboard skips disabled rows");
|
||||
await page.keyboard.press("ArrowRight");
|
||||
const sub = menu("More");
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await sub.isVisible(), true, "Nested submenus keep the parent visible");
|
||||
assert.equal(await menu("Languages").isVisible(), true);
|
||||
assert.equal(await page.getByRole("menuitemcheckbox", { name: "English" }).evaluate(node => node === document.activeElement), true);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
assert.equal(await menu("Languages").isVisible(), false);
|
||||
assert.equal(await item("Languages").evaluate(node => node === document.activeElement), true);
|
||||
for (const panel of [edge, sub]) {
|
||||
const bounds = await panel.boundingBox();
|
||||
assert.ok(bounds.x >= 8 && bounds.y >= 8 && bounds.x + bounds.width <= 412 && bounds.y + bounds.height <= 312);
|
||||
}
|
||||
await page.keyboard.press("End");
|
||||
assert.equal(await item("Action 29").evaluate(node => node === document.activeElement), true);
|
||||
await page.screenshot({ path: ".audit/menu-edge.png" });
|
||||
await dismiss();
|
||||
await page.evaluate(async () => {
|
||||
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
|
||||
const dialog = document.createElement("dialog");
|
||||
dialog.id = "menu-modal-test";
|
||||
dialog.style.cssText = "height:220px;width:320px;overflow:auto";
|
||||
const content = document.createElement("div");
|
||||
content.style.height = "600px";
|
||||
dialog.append(content);
|
||||
document.body.append(dialog);
|
||||
dialog.showModal();
|
||||
dialog.scrollTop = 160;
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
window.menuModalScroll = dialog.scrollTop;
|
||||
const root = actionMenu(180, 280, Array.from({ length: 30 }, (_, index) => ({ label: `Modal action ${index}`, icon: "copy" })), () => root.remove(), "Modal scrolling test", dialog);
|
||||
const dismissOnAncestorScroll = event => { if (!root.contains(event.target)) root.remove(); };
|
||||
dialog.addEventListener("scroll", dismissOnAncestorScroll, true);
|
||||
});
|
||||
await page.keyboard.press("End");
|
||||
const modalMenu = menu("Modal scrolling test");
|
||||
await modalMenu.waitFor();
|
||||
assert.equal(await item("Modal action 29").evaluate(node => node === document.activeElement), true);
|
||||
assert.equal(await page.locator("#menu-modal-test").evaluate(dialog => dialog.scrollTop), await page.evaluate(() => window.menuModalScroll), "Keyboard traversal scrolls only the menu panel");
|
||||
const modalBounds = await modalMenu.boundingBox(), lastBounds = await item("Modal action 29").boundingBox();
|
||||
assert.ok(lastBounds.y >= modalBounds.y && lastBounds.y + lastBounds.height <= modalBounds.y + modalBounds.height + 1, "End keeps the last row visible inside a short modal");
|
||||
await page.screenshot({ path: ".audit/menu-modal-end.png" });
|
||||
await page.keyboard.press("Home");
|
||||
assert.equal(await item("Modal action 0").evaluate(node => node === document.activeElement), true);
|
||||
await dismiss();
|
||||
await page.locator("#menu-modal-test").evaluate(dialog => { dialog.close(); dialog.remove(); });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: menu styles, dark/light themes, icons, disabled rows, focus return, submenus, scrolling, and viewport edges");
|
||||
} finally { await browser.close(); }
|
||||
@@ -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 origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
let sequence = 0;
|
||||
const emit = (event, payload) => { for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload }); };
|
||||
const manifest = (id, name) => ({ schemaVersion: 1, id, name, author: "Test", description: "Access test", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" });
|
||||
const plugins = [manifest("runestone.local-autocomplete", "Local Autocomplete"), manifest("org.example.browser", "Browser"), manifest("org.example.tasks", "Tasks")];
|
||||
const modules = {
|
||||
"runestone.local-autocomplete": `export function activate(api) {
|
||||
window.accessTest = { mounts: 0, disposed: 0, settings: 0 };
|
||||
api.settings.subscribe?.(() => { window.accessTest.settings++; });
|
||||
api.registerView({ id: 'settings', title: 'Local Autocomplete', placement: 'editor', mount(container, context) {
|
||||
window.accessTest.mounts++;
|
||||
container.innerHTML = '<h2>Local Autocomplete</h2><label>Model<input aria-label="Model"></label><button>Save model</button><p class="mount-context"></p>';
|
||||
container.querySelector('p').textContent = context?.surface;
|
||||
container.querySelector('button').onclick = () => api.settings.write({ model: container.querySelector('input').value });
|
||||
return () => { window.accessTest.disposed++; };
|
||||
}});
|
||||
api.registerCommand({ id: 'configure', title: 'Configure Local Autocomplete', run: () => api.openView('settings') });
|
||||
api.registerCommand({ id: 'fail', title: 'Failed command', run: () => { throw Error('Command failed for test'); } });
|
||||
}`,
|
||||
"org.example.browser": `export function activate(api) {
|
||||
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run() {
|
||||
const id = 'tab-' + Date.now(); api.registerView({ id, title: 'Browser instance', placement: 'editor', mount(container) { container.textContent = 'Browser content'; } }); api.openView(id);
|
||||
}});
|
||||
}`,
|
||||
"org.example.tasks": `export function activate(api) {
|
||||
api.registerView({ id: 'tasks', title: 'All tasks', icon: 'list', navigation: true, placement: 'editor', launch() { api.openView('default-board'); }, mount(container) { container.textContent = 'Task content'; } });
|
||||
api.registerView({ id: 'default-board', title: 'Default board', launcher: false, placement: 'editor', mount(container) { container.textContent = 'Default board content'; } });
|
||||
window.taskTestApi = api;
|
||||
api.registerView({ id: 'dialog', title: 'Task summary', mount(container) { container.textContent = 'Task summary content'; } });
|
||||
}`,
|
||||
};
|
||||
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 = {}) => {
|
||||
if (command === 'plugin:event|listen') { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
|
||||
if (command === 'plugin:event|unlisten') { callbacks.delete(args.eventId); return; }
|
||||
if (command === 'browser_connect') return 'test-session';
|
||||
if (command === 'browser_stop') return;
|
||||
if (command === 'workspace_last_path') return null;
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/test/plugins', plugins: plugins.map(manifest => ({ manifest, hash: 'test', enabled: !(manifest.id === 'runestone.local-autocomplete' && localStorage.getItem('disabled')), installedAt: 1, path: 'C:/test/plugins/' + manifest.id, error: null, removal: false })) };
|
||||
if (command === 'plugins_load') return modules[args.id];
|
||||
if (command === 'plugins_data') {
|
||||
if (args.value !== null) { localStorage.setItem('settings:' + args.id, args.value); emit('plugin-settings-changed', args.id); }
|
||||
return localStorage.getItem('settings:' + args.id) || 'null';
|
||||
}
|
||||
if (command === 'plugins_set_enabled') { if (!args.enabled) localStorage.setItem('disabled', 'true'); emit('plugins-changed', {}); return; }
|
||||
if (command === 'plugins_release' || command === 'settings_open_window') return;
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
throw new Error('Unhandled IPC: ' + command);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.addEventListener('storage', event => { if (event.key?.startsWith('settings:')) emit('plugin-settings-changed', event.key.slice(9)); if (event.key === 'disabled') emit('plugins-changed', {}); });
|
||||
});
|
||||
const main = await context.newPage(), settings = await context.newPage();
|
||||
for (const page of [main, settings]) { page.setDefaultTimeout(10000); page.on('pageerror', error => errors.push(error.message)); }
|
||||
try {
|
||||
await main.goto(origin);
|
||||
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).waitFor();
|
||||
assert.equal(await main.getByRole('button', { name: 'Open tab or view', exact: true }).count(), 0);
|
||||
assert.equal(await main.getByRole('button', { name: 'Commands', exact: true }).count(), 1);
|
||||
await main.getByRole('navigation', { name: 'Plugin shortcuts' }).getByRole('button', { name: 'All tasks', exact: true }).click();
|
||||
await main.getByText('Default board content', { exact: true }).waitFor();
|
||||
await main.evaluate(() => window.taskTestApi.openView('tasks'));
|
||||
await main.getByText('Task content', { exact: true }).waitFor();
|
||||
await main.evaluate(async () => {
|
||||
const { closePluginEditor, pluginTabState, pluginView, restorePluginTab } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
let view;
|
||||
const off = pluginView.subscribe(value => { view = value; }); off();
|
||||
const transfer = pluginTabState(view);
|
||||
closePluginEditor(view.key);
|
||||
if (!await restorePluginTab(transfer)) throw Error('Tab restore failed');
|
||||
});
|
||||
await main.getByText('Task content', { exact: true }).waitFor();
|
||||
await main.evaluate(async () => {
|
||||
const { runPluginCommand } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
await runPluginCommand('org.example.browser', 'new-tab');
|
||||
});
|
||||
await main.getByText('Browser content', { exact: true }).waitFor();
|
||||
await main.evaluate(async () => {
|
||||
const { openPluginView } = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
openPluginView('org.example.tasks', 'dialog');
|
||||
});
|
||||
await main.getByRole('dialog', { name: 'Task summary' }).waitFor();
|
||||
await main.keyboard.press('Escape');
|
||||
for (const theme of ['dark', 'light']) {
|
||||
await main.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
await main.screenshot({ path: `.audit/plugin-access-${theme}.png` });
|
||||
}
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).click();
|
||||
await settings.getByRole('textbox', { name: 'Model', exact: true }).fill('unsaved-model');
|
||||
assert.equal(await settings.locator('.mount-context').innerText(), 'settings');
|
||||
await settings.waitForTimeout(5500);
|
||||
assert.equal(await settings.getByRole('textbox', { name: 'Model', exact: true }).inputValue(), 'unsaved-model');
|
||||
assert.equal(await settings.evaluate(() => window.accessTest.mounts), 1);
|
||||
await settings.getByRole('button', { name: 'Save model', exact: true }).click();
|
||||
await main.waitForFunction(() => window.accessTest.settings === 1);
|
||||
await settings.screenshot({ path: '.audit/plugin-access-settings.png' });
|
||||
await settings.getByRole('button', { name: 'General', exact: true }).click();
|
||||
await settings.waitForFunction(() => window.accessTest.disposed === 1);
|
||||
await settings.getByRole('textbox', { name: 'Search settings' }).fill('Local');
|
||||
await settings.getByRole('textbox', { name: 'Model', exact: true }).waitFor();
|
||||
await settings.getByRole('textbox', { name: 'Search settings' }).fill('');
|
||||
await settings.getByRole('button', { name: 'Plug-ins', exact: true }).click();
|
||||
await settings.getByRole('switch', { name: 'Local Autocomplete', exact: true }).uncheck();
|
||||
await settings.getByRole('button', { name: 'Local Autocomplete', exact: true }).waitFor({ state: 'detached' });
|
||||
await main.getByRole('button', { name: 'Commands', exact: true }).waitFor({ state: 'detached' });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Plugin access smoke passed: compact header, navigation, dynamic tabs, dialog, settings search, stable forms, cross-window settings, disable cleanup.');
|
||||
} catch (error) {
|
||||
await settings.screenshot({ path: '.audit/plugin-access-failure.png' });
|
||||
console.log(await settings.locator('body').innerText(), await settings.evaluate(() => window.accessTest), errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,52 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFile, mkdir } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
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();
|
||||
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await mkdir('.audit/menu-audit', { recursive: true });
|
||||
await page.route('**/__choice-audit__', route => route.fulfill({ contentType: 'text/html', body: '<link rel="stylesheet" href="/src/lib/theme/tokens.css"><link rel="stylesheet" href="/src/lib/ui/menu.css"><style>dialog{inset:0;margin:0;max-width:none;max-height:none;width:100%;height:100%;box-sizing:border-box;background:var(--rs-bg);color:var(--rs-text);padding:0;border:0}</style><dialog><main></main></dialog>' }));
|
||||
await page.route('**/__autocomplete__/*.mjs', async route => {
|
||||
const name = new URL(route.request().url()).pathname.split('/').pop();
|
||||
assert.ok(['main.mjs', 'engine.mjs'].includes(name));
|
||||
await route.fulfill({ contentType: 'application/javascript', body: await readFile(new URL(`../../../../RuneStone_LocalAutocomplete/src/${name}`, import.meta.url), 'utf8') });
|
||||
});
|
||||
try {
|
||||
for (const theme of ['light', 'dark']) for (const width of [1100, 390]) {
|
||||
await page.setViewportSize({ width, height: 850 });
|
||||
await page.goto(url + '/__choice-audit__');
|
||||
await page.evaluate(async theme => {
|
||||
document.documentElement.dataset.theme = theme;
|
||||
const { showActionMenu } = await import('/src/lib/ui/managedActionMenu.ts');
|
||||
const { activate } = await import('/__autocomplete__/main.mjs');
|
||||
let view;
|
||||
window.choiceAudit = { saved: null };
|
||||
await activate({ ui: { showActionMenu }, completion: { version: 1, transport() {}, invalidate() {}, registerProvider() { return () => {}; }, registerInput() { return { dispose() {}, request() {} }; } },
|
||||
settings: { read: async () => ({}), write: async value => { window.choiceAudit.saved = value; } },
|
||||
onDispose() {}, registerCommand() {}, registerView(value) { view = value; } });
|
||||
document.querySelector('dialog').showModal();
|
||||
window.choiceAudit.dispose = view.mount(document.querySelector('main'), { surface: 'settings' });
|
||||
}, theme);
|
||||
const trigger = page.getByRole('button', { name: 'Server type', exact: true });
|
||||
await trigger.click();
|
||||
const menu = page.getByRole('menu', { name: 'Server type', exact: true });
|
||||
assert.equal(await menu.evaluate(node => !!node.closest('dialog[open]')), true);
|
||||
await page.keyboard.press('End');
|
||||
assert.equal(await page.getByRole('menuitemradio', { name: 'Ollama', exact: true }).evaluate(node => node === document.activeElement), true);
|
||||
await page.screenshot({ path: `.audit/menu-audit/autocomplete-${theme}-${width}.png` });
|
||||
await page.keyboard.press('Enter');
|
||||
assert.match(await trigger.innerText(), /Ollama/);
|
||||
await page.getByRole('button', { name: 'Save settings', exact: true }).click();
|
||||
await page.waitForFunction(() => window.choiceAudit.saved?.adapter === 'ollama');
|
||||
await trigger.click(); await page.keyboard.press('Escape');
|
||||
assert.equal(await trigger.evaluate(node => node === document.activeElement), true);
|
||||
await trigger.click(); await page.evaluate(() => window.choiceAudit.dispose());
|
||||
assert.equal(await page.locator('.rs-menu').count(), 0);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: Local Autocomplete shared choices, modal input, saved adapter, focus return, and cleanup in both themes at 1100/390px.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,238 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
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 context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US', timezoneId: 'America/Vancouver' });
|
||||
const page = await context.newPage();
|
||||
const settingsPage = await context.newPage();
|
||||
settingsPage.setDefaultTimeout(10000);
|
||||
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
|
||||
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
|
||||
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));
|
||||
settingsPage.on("pageerror", error => errors.push(error.message));
|
||||
const manifest = JSON.parse(readFileSync('fixtures/plugins/workspace-overview/plugin.json', 'utf8'));
|
||||
const pluginCode = readFileSync('fixtures/plugins/workspace-overview/main.js', 'utf8') + '\n// Browser cleanup probe\n';
|
||||
await page.context().addInitScript(({ manifest, pluginCode }) => {
|
||||
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 = [];
|
||||
let installed = [];
|
||||
let removalPrepared = false;
|
||||
const data = { preserved: true };
|
||||
const path = "C:\\AppData\\RuneStone\\plugins\\" + manifest.id;
|
||||
const snapshot = () => ({ root: "C:\\AppData\\RuneStone\\plugins", plugins: installed });
|
||||
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 = {}) => {
|
||||
if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|"))
|
||||
return window.settingsHostInvoke(command, args);
|
||||
calls.push({ command, args });
|
||||
if (command === "settings_open_window") return;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
if (command.startsWith("plugin:window|")) return null;
|
||||
if (command === "plugins_snapshot") return snapshot();
|
||||
if (command === "plugins_choose") return [{ token: 'candidate', source: 'C:/Downloads/overview.zip', manifest, error: null }];
|
||||
if (command === "plugins_from_git") {
|
||||
if (args.tag === 'missing') throw new Error('Release not found. Publish a release with one plugin ZIP.');
|
||||
return [{ token: 'git-candidate', source: args.url + ' @ ' + (args.tag || 'v1.0.0'), manifest, error: null }];
|
||||
}
|
||||
if (command === "plugins_cancel") { removalPrepared = false; return; }
|
||||
if (command === "plugins_install") {
|
||||
const previous = installed[0];
|
||||
installed = [{ manifest, hash: 'reviewed-hash', enabled: previous ? previous.enabled : args.enabled, installedAt: Date.parse('2026-10-05T18:24:36Z'), path, error: null, removal: false }];
|
||||
emit('plugins-changed', null); return [{ name: manifest.name, error: null }];
|
||||
}
|
||||
if (command === "plugins_set_enabled") {
|
||||
installed[0].enabled = args.enabled;
|
||||
emit('plugins-changed', null); return;
|
||||
}
|
||||
if (command === "plugins_load") { window.__TEST__.cleaned = false; window.__TEST__.released = false; return pluginCode.replace('export function activate(api) {', 'export function activate(api) { api.onDispose(() => { window.__TEST__.cleaned = true; });'); }
|
||||
if (command === "plugins_release") { window.__TEST__.released = true; return; }
|
||||
if (command === "plugins_data") return JSON.stringify(data);
|
||||
if (command === "plugins_reveal") return;
|
||||
if (command === "plugins_prepare_remove") { removalPrepared = true; return { token: 'remove-plan', plugin: installed[0] }; }
|
||||
if (command === "plugins_remove") {
|
||||
if (!removalPrepared) throw Error('Missing removal plan');
|
||||
removalPrepared = false;
|
||||
installed[0].enabled = false; emit('plugins-changed', null);
|
||||
for (let i=0; i<100 && !window.__TEST__.released; i++) await new Promise(resolve => setTimeout(resolve, 50));
|
||||
if (!window.__TEST__.cleaned || !window.__TEST__.released) throw Error('Cleanup was not acknowledged');
|
||||
installed = []; emit('plugins-changed', null); return;
|
||||
}
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root, data };
|
||||
}, { manifest, pluginCode });
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
|
||||
const settingsDialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
|
||||
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
|
||||
async function settings() {
|
||||
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
|
||||
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
await settingsDialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
|
||||
}
|
||||
async function uninstall() { await settingsDialog.locator('.card').filter({ hasText: 'Workspace overview' }).getByRole('button', { name: 'Uninstall', exact: true }).click(); }
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await settings();
|
||||
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from folder', exact: true }).count(), 0);
|
||||
assert.equal(await settingsDialog.getByRole('button', { name: 'Install from file', exact: true }).count(), 0);
|
||||
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
|
||||
let review = settingsPage.getByRole('dialog', { name: 'Review plugin installation', exact: true });
|
||||
await review.getByText('Source: C:/Downloads/overview.zip', { exact: true }).waitFor();
|
||||
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
assert.equal(await count('plugins_install'), 0);
|
||||
const gitButton = settingsDialog.getByRole('button', { name: 'Install from Git link', exact: true });
|
||||
await gitButton.click();
|
||||
const gitDialog = settingsPage.getByRole('dialog', { name: 'Install from Git link', exact: true });
|
||||
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
|
||||
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('missing');
|
||||
await gitDialog.getByLabel('Access token (optional)', { exact: true }).fill('test-token');
|
||||
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
|
||||
await gitDialog.getByRole('alert').getByText(/Release not found/).waitFor();
|
||||
assert.equal(await gitDialog.getByLabel('Access token (optional)', { exact: true }).inputValue(), '');
|
||||
await gitDialog.getByLabel('Release tag (optional)', { exact: true }).fill('v1.0.0');
|
||||
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
|
||||
await review.getByText('Source: https://git.example/owner/plugin.git @ v1.0.0', { exact: true }).waitFor();
|
||||
await review.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
assert.equal(await count('plugins_install'), 0);
|
||||
assert(await gitButton.evaluate(element => element === document.activeElement));
|
||||
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
|
||||
await review.getByRole('button', { name: 'Install and enable', exact: true }).click();
|
||||
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
|
||||
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||
assert.equal(await settingsDialog.locator('time').getAttribute('datetime'), '2026-10-05T18:24:36.000Z');
|
||||
assert.match(await settingsDialog.locator('time').innerText(), /Oct 5, 2026.*11:24:36 AM PDT/);
|
||||
await settingsPage.screenshot({ path: '.audit/plugin-manager-installed.png' });
|
||||
await settingsPage.keyboard.press('Escape');
|
||||
await page.getByRole('button', { name: 'Commands', exact: true }).click();
|
||||
await page.getByRole('menuitem', { name: /Show workspace overview/ }).click();
|
||||
const view = page.getByRole('dialog', { name: 'Workspace overview', exact: true });
|
||||
await view.getByText(/files and folders in this workspace/).waitFor();
|
||||
await view.getByRole('button', { name: 'Close plugin view', exact: true }).click();
|
||||
await settings();
|
||||
await settingsDialog.getByRole('button', { name: 'Install plugin ZIP', exact: true }).click();
|
||||
await review.getByText(/Update .* → .*Settings and enabled state stay the same/).waitFor();
|
||||
assert.equal(await review.getByRole('button', { name: 'Install and enable', exact: true }).count(), 0);
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await settingsPage.evaluate(async mode => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
saveAppearance({ theme: 'default', mode });
|
||||
}, mode);
|
||||
for (const width of [1440, 590]) {
|
||||
await settingsPage.setViewportSize({ width, height: width === 590 ? 820 : 1000 });
|
||||
await settingsPage.screenshot({ path: `.audit/plugin-update-review-${mode}-${width}.png` });
|
||||
assert.equal(await review.evaluate(element => element.scrollWidth > element.clientWidth), false);
|
||||
}
|
||||
}
|
||||
await review.getByRole('button', { name: 'Apply packages', exact: true }).click();
|
||||
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
|
||||
assert.equal(await count('plugins_remove'), 0);
|
||||
await settingsPage.setViewportSize({ width: 1440, height: 1000 });
|
||||
await uninstall();
|
||||
const confirmation = settingsPage.getByRole('dialog', { name: 'Uninstall Workspace overview?', exact: true });
|
||||
assert(await confirmation.getByRole('button', { name: 'Cancel', exact: true }).evaluate(el => el === document.activeElement));
|
||||
assert.equal(await confirmation.getByRole('button', { name: 'Continue', exact: true }).count(), 0);
|
||||
await confirmation.getByRole('button', { name: 'Cancel', exact: true }).click();
|
||||
assert.equal(await count('plugins_remove'), 0);
|
||||
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||
await uninstall();
|
||||
await confirmation.waitFor();
|
||||
await settingsPage.keyboard.press('Escape');
|
||||
assert(await settingsDialog.isVisible());
|
||||
assert(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked());
|
||||
assert.equal(await count('plugins_remove'), 0);
|
||||
await uninstall();
|
||||
await confirmation.waitFor();
|
||||
await settingsPage.screenshot({ path: '.audit/plugin-uninstall-confirmation.png' });
|
||||
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
||||
await settingsDialog.getByText('No plugins installed.', { exact: true }).waitFor();
|
||||
assert.equal(await count('plugins_remove'), 1);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.cleaned), true);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.data.preserved), true);
|
||||
await settingsPage.keyboard.press('Escape');
|
||||
assert.equal(await page.getByRole('button', { name: 'Plugin commands and views', exact: true }).count(), 0);
|
||||
await settingsPage.setViewportSize({ width: 590, height: 820 });
|
||||
await settings();
|
||||
await settingsPage.screenshot({ path: '.audit/plugin-manager-narrow.png' });
|
||||
assert.equal(await settingsDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
|
||||
await gitButton.click();
|
||||
await gitDialog.getByLabel('Repository link', { exact: true }).fill('https://git.example/owner/plugin.git');
|
||||
await settingsPage.screenshot({ path: '.audit/plugin-git-narrow.png' });
|
||||
assert.equal(await gitDialog.evaluate(element => element.scrollWidth > element.clientWidth), false);
|
||||
await gitDialog.getByRole('button', { name: 'Review release', exact: true }).click();
|
||||
await review.getByRole('button', { name: 'Install', exact: true }).click();
|
||||
await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).waitFor();
|
||||
assert.equal(await settingsDialog.getByRole('switch', { name: 'Workspace overview', exact: true }).isChecked(), false);
|
||||
assert.equal(await count('plugins_from_git'), 3);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('External plugin smoke passed: ZIP and Git-link review, download errors, token clearing, disabled installation, code loading, cancellation, focus, cleanup, and uninstall.');
|
||||
} catch (error) {
|
||||
console.log('Main page:', await page.locator('body').innerText());
|
||||
console.log('Page errors:', errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,202 @@
|
||||
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
await context.route('**/__settings-closed', route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><title>Closed settings</title>' }));
|
||||
const page = await context.newPage();
|
||||
const settingsPage = await context.newPage();
|
||||
page.setDefaultTimeout(10000);
|
||||
settingsPage.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));
|
||||
settingsPage.on("pageerror", error => errors.push(error.message));
|
||||
await page.context().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 === "settings_open_window") return;
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
await mockFeaturePlugins(page.context());
|
||||
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
const source = '# Formulas\n\n| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n\nAfter.\n';
|
||||
const table = page.locator('.live-writer table');
|
||||
const dialog = settingsPage.getByRole('dialog', { name: 'Settings', exact: true });
|
||||
const switchFor = name => dialog.getByRole('switch', { name, exact: true });
|
||||
async function settings() {
|
||||
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).click();
|
||||
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
await dialog.getByRole('button', { name: 'Plug-ins', exact: true }).click();
|
||||
}
|
||||
async function closeSettings() {
|
||||
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
|
||||
await settingsPage.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/__settings-closed');
|
||||
await page.bringToFront();
|
||||
}
|
||||
const count = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).length, command);
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text), source);
|
||||
await quickOpen('formulas.md');
|
||||
await table.waitFor();
|
||||
assert.equal(await table.locator('.md-table-formula').innerText(), '6');
|
||||
await settings();
|
||||
await switchFor('Table formulas').uncheck();
|
||||
await closeSettings();
|
||||
await page.waitForFunction(() => !document.querySelector('.md-table-formula'));
|
||||
assert.match(await table.innerText(), /=A2\*3/);
|
||||
assert.equal(await page.locator('.table-formula-tools').count(), 0);
|
||||
await table.locator('td').last().click();
|
||||
await page.locator('.writer-cell-editor').fill('=A2*4');
|
||||
await page.keyboard.press('Enter');
|
||||
await settings();
|
||||
await switchFor('Table formulas').check();
|
||||
await closeSettings();
|
||||
await page.waitForFunction(() => document.querySelector('.md-table-formula')?.textContent === '8');
|
||||
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
|
||||
const preview = page.locator('.md-page table').first();
|
||||
await preview.locator('.md-table-formula').waitFor();
|
||||
await settings();
|
||||
await switchFor('Table formulas').uncheck();
|
||||
await closeSettings();
|
||||
await page.waitForFunction(() => !document.querySelector('.md-page .md-table-formula'));
|
||||
assert.match(await preview.innerText(), /=A2\*4/);
|
||||
await settings();
|
||||
await switchFor('Table formulas').check();
|
||||
await closeSettings();
|
||||
await preview.locator('.md-table-formula').waitFor();
|
||||
assert.equal(await preview.locator('.md-table-formula').innerText(), '8');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('formulas.md').includes('=A2*4'));
|
||||
assert(!await page.evaluate(() => window.__TEST__.files.get('formulas.md').includes('>8<')));
|
||||
|
||||
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open'));
|
||||
await settings();
|
||||
await switchFor('Terminal').uncheck();
|
||||
await page.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close'));
|
||||
await settingsPage.screenshot({ path: '.audit/plugins-settings.png' });
|
||||
await closeSettings();
|
||||
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||
const opened = await count('pty_open');
|
||||
await page.keyboard.press('Control+j');
|
||||
assert.equal(await count('pty_open'), opened);
|
||||
await page.reload();
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||
await settings();
|
||||
assert(!await switchFor('Terminal').isChecked());
|
||||
|
||||
const standalone = await page.context().newPage();
|
||||
await standalone.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '?terminalWindow=C%3A%5Csmoke-workspace');
|
||||
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
|
||||
await switchFor('Terminal').check();
|
||||
await standalone.locator('.xterm').waitFor();
|
||||
await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_open'));
|
||||
await switchFor('Terminal').uncheck();
|
||||
await standalone.getByText(/Install and enable the Terminal plugin/).waitFor();
|
||||
await standalone.waitForFunction(() => window.__TEST__.calls.some(call => call.command === 'pty_close'));
|
||||
await standalone.close();
|
||||
await switchFor('Terminal').check();
|
||||
await closeSettings();
|
||||
await page.getByRole('button', { name: 'Terminal', exact: true }).click();
|
||||
await page.locator('.xterm').waitFor();
|
||||
await page.evaluate(text => window.__TEST__.files.set('formulas.md', text.replace('=A2*3', '=A2*4')), source);
|
||||
await page.getByRole('button', { name: 'Terminal', exact: true }).focus();
|
||||
await quickOpen('formulas.md');
|
||||
await settings();
|
||||
assert.equal(await dialog.getByRole('heading', { name: 'Bundled plugins' }).count(), 0);
|
||||
for (const name of ['Terminal', 'Table formulas']) {
|
||||
await settingsPage.waitForFunction(() => [...document.querySelectorAll('input[role="switch"]')].every(input => !input.disabled));
|
||||
await dialog.locator('.card').filter({ has: settingsPage.getByRole('switch', { name, exact: true }) }).getByRole('button', { name: 'Uninstall', exact: true }).click();
|
||||
const confirmation = settingsPage.getByRole('dialog', { name: `Uninstall ${name}?`, exact: true });
|
||||
await confirmation.getByRole('button', { name: 'Uninstall and delete files', exact: true }).click();
|
||||
await confirmation.waitFor({ state: 'hidden' });
|
||||
await switchFor(name).waitFor({ state: 'detached' });
|
||||
}
|
||||
await closeSettings();
|
||||
await page.waitForFunction(() => !document.querySelector('.md-table-formula') && !document.querySelector('.xterm'));
|
||||
assert.equal(await page.getByRole('button', { name: 'Terminal', exact: true }).count(), 0);
|
||||
assert.match(await table.innerText(), /=A2\*4/);
|
||||
await page.reload();
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await settings();
|
||||
await dialog.getByText('No plugins installed.', { exact: true }).waitFor();
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Plugin smoke passed: formulas, source preservation, terminal shutdown, persistence, shortcuts, cross-window enable controls, removal, and no automatic restoration.');
|
||||
} catch (error) {
|
||||
await settingsPage.screenshot({ path: ".audit/plugins-settings-failure.png" });
|
||||
console.log("Settings page:", settingsPage.url(), await settingsPage.locator('body').innerText());
|
||||
await page.screenshot({ path: ".audit/plugins-failure.png" });
|
||||
console.log(await page.locator('.md-page').allTextContents());
|
||||
console.log(errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,165 @@
|
||||
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 context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\host-todo-test';
|
||||
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
|
||||
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
|
||||
window.__HOST_TEST__ = state;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push({ command, args });
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_list') {
|
||||
const prefix = args.rel ? args.rel + '/' : '';
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
|
||||
const tail = path.slice(prefix.length), 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('Destination exists'); files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_write') {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === 'workspace_rename') {
|
||||
if (files.has(args.to)) throw new Error('Destination exists');
|
||||
if (!files.has(args.from)) throw new Error('Missing file');
|
||||
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
|
||||
}
|
||||
if (command === 'workspace_delete') { files.delete(args.rel); return; }
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:dialog|message') return 'Ok';
|
||||
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5173';
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
const item = name => page.getByRole('menuitem', { name, exact: true });
|
||||
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
|
||||
await mkdir('output/host-todo', { recursive: true });
|
||||
try {
|
||||
await page.goto(origin);
|
||||
await row('a.md').waitFor();
|
||||
await page.getByRole('button', { name: 'New file Ctrl N' }).click();
|
||||
await page.getByRole('textbox', { name: 'New file path relative to the workspace' }).waitFor();
|
||||
await page.mouse.click(5, 700);
|
||||
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses new-file dialog');
|
||||
await page.getByRole('button', { name: 'Find a file Ctrl P' }).click();
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).click();
|
||||
assert.equal(await page.locator('dialog').count(), 1, 'Inside click keeps file search open');
|
||||
await page.mouse.click(5, 700);
|
||||
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses file search');
|
||||
await row('a.md').click({ button: 'right' });
|
||||
assert.equal(await item('Copy path').count(), 0);
|
||||
assert.equal(await item('Copy system path').count(), 1);
|
||||
await item('Rename').click();
|
||||
await page.locator('.tree input').fill('renamed.md');
|
||||
await page.locator('.tree input').press('Enter');
|
||||
await row('renamed.md').waitFor();
|
||||
await row('renamed.md').click({ button: 'right' });
|
||||
assert.equal(await item('Undo rename').count(), 1);
|
||||
await page.keyboard.press('Escape');
|
||||
await row('renamed.md').focus(); await page.keyboard.press('Control+z');
|
||||
await row('a.md').waitFor();
|
||||
assert.deepEqual(await page.evaluate(() => JSON.parse(window.__HOST_TEST__.files.get('.runestone/marks.json')).pins), ['a.md']);
|
||||
await row('a.md').focus(); await page.keyboard.press('Control+y');
|
||||
await row('renamed.md').waitFor();
|
||||
await paneMenu(); await item('New note').hover();
|
||||
await item('Daily').click();
|
||||
await row('Daily.md').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Rename Daily', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Weekly');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor();
|
||||
await page.evaluate(() => window.__HOST_TEST__.files.set('.runestone/templates/Existing.md', '# Keep this template'));
|
||||
await page.getByRole('button', { name: 'Rename Weekly', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Existing');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByRole('alert').filter({ hasText: 'Destination exists' }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Existing.md')), '# Keep this template');
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await page.screenshot({ path: `output/host-todo/templates-${mode}.png` });
|
||||
}
|
||||
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'Weekly.md', exact: true }).waitFor();
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'New template', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Meeting');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'Meeting.md', exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Meeting.md')), '');
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Delete Weekly', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor({ state: 'detached' });
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks', 'Deleting template preserves notes');
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
await page.evaluate(() => { for (let i = 0; i < 40; i++) window.__HOST_TEST__.files.set(`.runestone/templates/Long template name ${i}.md`, '# Template'); });
|
||||
await page.setViewportSize({ width: 600, height: 600 });
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
assert.ok(await page.locator('dialog .list').evaluate(node => node.scrollHeight > node.clientHeight), 'Long template list scrolls');
|
||||
await page.screenshot({ path: 'output/host-todo/templates-narrow-long.png' });
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
await page.setViewportSize({ width: 1200, height: 850 });
|
||||
const settings = await context.newPage(); settings.on('pageerror', error => errors.push(error.message));
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
await settings.getByRole('button', { name: 'Export theme template' }).click();
|
||||
await settings.getByRole('status').filter({ hasText: 'Theme saved to' }).waitFor();
|
||||
assert.equal(await settings.evaluate(() => JSON.parse(window.__HOST_TEST__.calls.find(call => call.command === 'theme_export').args.contents).schema), 1);
|
||||
await settings.evaluate(() => window.__HOST_TEST__.exportResult = null);
|
||||
await settings.getByRole('button', { name: 'Export theme template' }).click();
|
||||
await settings.getByText('Export canceled.', { exact: true }).waitFor();
|
||||
await settings.evaluate(() => window.__HOST_TEST__.exportError = 'Disk is full');
|
||||
await settings.getByRole('button', { name: 'Export theme template' }).click();
|
||||
await settings.getByRole('alert').filter({ hasText: 'Disk is full' }).waitFor();
|
||||
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
|
||||
await settings.getByRole('menuitemradio', { name: 'RuneStone', exact: true }).focus();
|
||||
await settings.keyboard.press('ArrowDown'); await settings.keyboard.press('Enter');
|
||||
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), 'claude');
|
||||
assert.equal(await settings.locator('input[type=color]').count(), 0);
|
||||
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
|
||||
await page.locator('.empty').waitFor();
|
||||
await page.waitForFunction(() => document.documentElement.dataset.palette === 'claude');
|
||||
assert.equal(await page.locator('.empty').evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-bg)'; node.append(reference); const matches = getComputedStyle(node).backgroundColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true);
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'test.png', mimeType: 'image/png', buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64') });
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
await page.reload(); await page.locator('.empty').waitFor();
|
||||
assert.ok(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage.includes('blob:')), 'Background survives restart');
|
||||
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => { const { saveAppearance, parseAppearance, APPEARANCE_KEY } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ ...parseAppearance(localStorage.getItem(APPEARANCE_KEY)), theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, mode);
|
||||
await settings.setViewportSize({ width: 650, height: 760 });
|
||||
await settings.screenshot({ path: `output/host-todo/appearance-${mode}-narrow.png` });
|
||||
}
|
||||
assert.equal(await settings.getByRole('button', { name: 'Reset background', exact: true }).isDisabled(), true);
|
||||
await page.waitForFunction(() => !JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Host To Do: dialog dismissal, rename undo/redo with marks, template creation/rename/edit/delete, theme export success/cancel/error, shared theme menu, background persistence/reset passed.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,115 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../browser-runtime/node_modules/playwright');
|
||||
const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe' });
|
||||
const output = '.audit/todo-ui';
|
||||
await mkdir(output, { recursive: true });
|
||||
try {
|
||||
for (const theme of ['light', 'dark']) {
|
||||
const page = await browser.newPage({ viewport: { width: 1100, height: 780 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } }, transformCallback: () => 1, unregisterCallback() {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'workspace_last_path') return 'C:/todo-ui';
|
||||
if (command === 'workspace_open') return { root: 'C:/todo-ui', name: 'todo-ui', watch_mode: 'native' };
|
||||
if (command === 'workspace_list') return [{ name: 'sample.md', rel_path: 'sample.md', kind: 'file' }];
|
||||
if (command === 'workspace_read') return '# Selection sample\n\nThe same text color applies to each editor.\n';
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'browser_request') {
|
||||
if (args.command === 'frameAck') window.blankAcks = (window.blankAcks || 0) + 1;
|
||||
return window.browserSnapshot;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
|
||||
});
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('todo-ui', { exact: true }).waitFor();
|
||||
await page.evaluate(async theme => {
|
||||
const { saveAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
saveAppearance({ theme: 'default', mode: theme });
|
||||
const { attachTooltip } = await import('/src/lib/ui/tooltip.ts');
|
||||
const cell = document.createElement('button');
|
||||
cell.id = 'tooltip-test'; cell.textContent = 'Formula cell';
|
||||
Object.assign(cell.style, { position: 'fixed', left: '20px', top: '100px', zIndex: '2000' });
|
||||
document.body.append(cell);
|
||||
window.disposeTip = attachTooltip(cell, () => 'B6 · Click to edit · Type = for a formula');
|
||||
}, theme);
|
||||
const target = page.locator('#tooltip-test');
|
||||
await target.hover();
|
||||
const tooltip = page.locator('.rs-tooltip:popover-open');
|
||||
await tooltip.waitFor();
|
||||
assert.equal(await target.getAttribute('title'), null);
|
||||
assert.equal(await tooltip.evaluate(node => getComputedStyle(node).borderRadius), '5px');
|
||||
await page.screenshot({ path: `${output}/${theme}-tooltip.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.locator('.rs-tooltip:popover-open').count(), 0);
|
||||
await target.focus();
|
||||
await tooltip.waitFor();
|
||||
await page.setViewportSize({ width: 390, height: 620 });
|
||||
await page.locator('header').first().hover();
|
||||
await target.hover();
|
||||
await tooltip.waitFor();
|
||||
const bounds = await tooltip.boundingBox();
|
||||
assert(bounds.x >= 8 && bounds.x + bounds.width <= 382);
|
||||
await page.screenshot({ path: `${output}/${theme}-narrow-tooltip.png` });
|
||||
await page.evaluate(() => { window.disposeTip(); document.getElementById('tooltip-test').remove(); });
|
||||
await page.setViewportSize({ width: 1100, height: 780 });
|
||||
await page.keyboard.press('Control+p');
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).fill('sample.md');
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).press('Enter');
|
||||
const writer = page.getByRole('textbox', { name: 'Writing editor', exact: true });
|
||||
await writer.waitFor(); await writer.click(); await page.keyboard.press('Control+a');
|
||||
const colors = await writer.evaluate(node => {
|
||||
const probe = document.createElement('span'); probe.style.backgroundColor = 'var(--rs-selection)'; node.append(probe);
|
||||
const expected = getComputedStyle(probe).backgroundColor; probe.remove();
|
||||
return { expected, native: getComputedStyle(node, '::selection').backgroundColor,
|
||||
layer: getComputedStyle(document.querySelector('.cm-selectionBackground')).backgroundColor };
|
||||
});
|
||||
assert.equal(colors.native, colors.expected); assert.equal(colors.layer, colors.expected);
|
||||
await page.screenshot({ path: `${output}/${theme}-writer-selection.png` });
|
||||
await page.getByRole('group', { name: 'Document view', exact: true }).hover();
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
const reader = page.locator('.reading');
|
||||
await reader.waitFor();
|
||||
assert.equal(await reader.evaluate(node => getComputedStyle(node, '::selection').backgroundColor), colors.expected);
|
||||
await page.evaluate(async () => {
|
||||
const { mount } = await import('/node_modules/svelte/src/index-client.js');
|
||||
const { default: Browser } = await import('/src/lib/browser/Browser.svelte');
|
||||
const client = await import('/src/lib/browser/client.ts');
|
||||
const container = document.createElement('div'); container.id = 'browser-test';
|
||||
Object.assign(container.style, { position: 'fixed', inset: '50px 10px 20px', zIndex: '2000', background: 'linear-gradient(120deg,#945975,#395c72)' });
|
||||
document.body.append(container);
|
||||
window.browserSnapshot = { profiles: [{ id: 'user', name: 'User' }], tabs: [{ id: 'blank', profileId: 'user', url: 'about:blank', title: '', loading: false }], bookmarks: [], settings: {} };
|
||||
client.state.set(window.browserSnapshot);
|
||||
mount(Browser, { target: container, props: { initial: { tabId: 'blank' }, onSessionChange() {}, async newTab() {} } });
|
||||
window.browserClient = client;
|
||||
});
|
||||
const surface = page.locator('#browser-test .surface');
|
||||
await page.locator('#browser-test [data-browser-state="ready"]').waitFor();
|
||||
await page.evaluate(() => window.browserClient.frames.get('blank')({ tabId: 'blank', frameId: 1, width: 10, height: 10, mime: 'image/png', data: 'AA==' }));
|
||||
assert.equal(await surface.evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
|
||||
assert.equal(await surface.locator('img').count(), 0);
|
||||
assert.equal(await page.evaluate(() => window.blankAcks), 1);
|
||||
await page.screenshot({ path: `${output}/${theme}-blank-browser.png` });
|
||||
await page.evaluate(() => {
|
||||
window.browserSnapshot.tabs[0].url = 'https://example.com/minimal';
|
||||
window.browserClient.state.set({ ...window.browserSnapshot });
|
||||
const canvas = document.createElement('canvas'); canvas.width = 10; canvas.height = 10;
|
||||
const ctx = canvas.getContext('2d'); ctx.fillStyle = 'white'; ctx.fillRect(0, 0, 10, 10);
|
||||
window.browserClient.frames.get('blank')({ tabId: 'blank', frameId: 2, width: 10, height: 10, mime: 'image/png', data: canvas.toDataURL().split(',')[1] });
|
||||
});
|
||||
await surface.locator('img').waitFor();
|
||||
assert.notEqual(await surface.evaluate(node => getComputedStyle(node).backgroundColor), 'rgba(0, 0, 0, 0)');
|
||||
assert.deepEqual(errors, []);
|
||||
await page.close();
|
||||
}
|
||||
console.log('To do UI smoke passed: tooltips, selection, blank browser, light/dark/narrow.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,162 @@
|
||||
// Run against the host dev server with PLAYWRIGHT_MODULE and CHROME_PATH when needed.
|
||||
import { createRequire } from "node:module";
|
||||
import { readFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import assert from "node:assert/strict";
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(15000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const root = "C:\\kanban-root-smoke";
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="80"><rect width="100" height="80" fill="#639"/></svg>';
|
||||
const files = new Map([
|
||||
["notes/draft.md", "Before.\n\nAfter.\n"],
|
||||
["files/report [Q1] (#1).pdf", "PDF fixture"],
|
||||
["images/diagram (#1).svg", btoa(svg)],
|
||||
]);
|
||||
const calls = [], callbacks = new Map(), listeners = new Map(); let sequence = 0;
|
||||
window.kanbanRootSmoke = { files, calls };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback(callback) { callbacks.set(++sequence, callback); return sequence; },
|
||||
unregisterCallback(id) { callbacks.delete(id); },
|
||||
async invoke(command, args = {}) {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") { const values = listeners.get(args.event) || []; values.push(args.handler); listeners.set(args.event, values); return args.handler; }
|
||||
if (command === "plugin:event|unlisten" || command === "spelling_menu_install" || command === "spelling_menu_uninstall") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "kanban-root-smoke", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw Error("File missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_read_data_url") return "data:image/svg+xml;base64," + files.get(args.rel);
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error("Save conflict");
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length), name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "workspace_recent") return [root];
|
||||
if (command === "plugins_snapshot") return { plugins: [], issues: [] };
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
if (command.startsWith("plugin:window|") || command === "browser_stop") return;
|
||||
throw Error("Unhandled IPC: " + command);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
|
||||
});
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
async function drag(path, target) {
|
||||
const from = await row(path).boundingBox(), to = await page.locator(target).boundingBox();
|
||||
assert.ok(from && to, "The file and editor must be visible");
|
||||
await page.mouse.move(from.x + Math.min(80, from.width / 2), from.y + from.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to.x + 45, to.y + 12, { steps: 15 });
|
||||
await page.locator(".image-drop-target").waitFor();
|
||||
await page.mouse.up();
|
||||
}
|
||||
async function writerSource() { return page.evaluate(() => window.kanbanWriter.state.doc.toString()); }
|
||||
async function ideSource() {
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
|
||||
});
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:5173");
|
||||
await row("notes").click(); await row("notes/draft.md").dblclick();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.kanbanWriter = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
await row("files").click();
|
||||
const original = await writerSource();
|
||||
await drag("files/report [Q1] (#1).pdf", ".cm-content");
|
||||
await page.waitForFunction(() => window.kanbanWriter.state.doc.toString().includes(".pdf)"));
|
||||
const linked = await writerSource();
|
||||
assert.ok(linked.includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"), linked);
|
||||
assert.ok(!linked.includes(""));
|
||||
await page.evaluate(() => window.kanbanWriter.focus()); await page.keyboard.press("Control+z");
|
||||
assert.equal(await writerSource(), original);
|
||||
await page.keyboard.press("Control+e");
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
const originalIde = await ideSource();
|
||||
await page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
window.kanbanMonaco = editor;
|
||||
});
|
||||
await drag("files/report [Q1] (#1).pdf", ".monaco-editor .view-lines");
|
||||
await page.waitForFunction(() => window.kanbanMonaco.getValue().includes(".pdf)"));
|
||||
assert.ok((await ideSource()).includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"));
|
||||
await page.evaluate(() => window.kanbanMonaco.focus());
|
||||
assert.equal(await page.evaluate(() => window.kanbanMonaco.hasTextFocus()), true);
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.waitForFunction(expected => window.kanbanMonaco.getValue() === expected, originalIde, { timeout: 3000 });
|
||||
assert.equal(await ideSource(), originalIde, "IDE undo restores the exact source");
|
||||
await drag("images/diagram (#1).svg", ".monaco-editor .view-lines");
|
||||
assert.ok((await ideSource()).includes(""));
|
||||
assert.equal(await page.evaluate(() => window.kanbanRootSmoke.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
|
||||
console.log("PASS: real FileTree pointer drags insert escaped document links in Writer and IDE, undo restores both, and image drags still embed.");
|
||||
|
||||
// Load current Git source through the host origin without creating a distributable.
|
||||
const gitRoot = process.env.RUNESTONE_GIT_ROOT || resolve("../RuneStone_Git");
|
||||
const sources = new Map(await Promise.all(["view.js", "model.js"].map(async file => [file, await readFile(resolve(gitRoot, "src", file), "utf8")])));
|
||||
await page.route("**/__kanban_git/*", route => route.fulfill({ contentType: "text/javascript", body: sources.get(new URL(route.request().url()).pathname.split("/").pop()) || "" }));
|
||||
const css = await readFile(resolve(gitRoot, "src/style.css"), "utf8");
|
||||
await page.evaluate(async css => {
|
||||
const { mountSidebar } = await import("/__kanban_git/view.js");
|
||||
const container = document.createElement("div"); container.id = "git-smoke"; container.style.cssText = "position:fixed;inset:45px 0 0 0;z-index:1000;background:var(--rs-bg)";
|
||||
document.body.append(container);
|
||||
window.gitGraphOpens = 0;
|
||||
window.disposeGitSmoke = mountSidebar(container, {
|
||||
workspace: {},
|
||||
git: { status: async () => ({ available: true, repository: true, branch: "main", changes: [] }), pull: async () => {}, push: async () => {} },
|
||||
openView: () => window.gitGraphOpens++,
|
||||
}, css, () => {});
|
||||
}, css);
|
||||
const graph = page.locator("#git-smoke").getByRole("button", { name: "Graph", exact: true });
|
||||
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 graph.waitFor();
|
||||
assert.equal(await graph.locator("svg").count(), 1);
|
||||
assert.equal(await graph.getAttribute("title"), "Graph");
|
||||
assert.equal(await graph.evaluate(node => [...node.childNodes].filter(child => child.nodeType === Node.TEXT_NODE && child.textContent.trim()).length), 0);
|
||||
assert.equal(await graph.locator(":scope > :not(.rs-git-icon):not(.rs-git-tooltip)").count(), 0, "Graph has no visible text label");
|
||||
await page.mouse.move(800, 800); await graph.evaluate(node => node.blur());
|
||||
assert.equal(await graph.locator(".rs-git-tooltip").isVisible(), false);
|
||||
await graph.hover(); await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
|
||||
await page.mouse.move(800, 800); await page.keyboard.press("Tab"); await graph.focus();
|
||||
assert.equal(await graph.evaluate(node => node.matches(":focus-visible")), true);
|
||||
await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: `.audit/kanban-git-toolbar-${theme}.png` });
|
||||
}
|
||||
await graph.click(); assert.equal(await page.evaluate(() => window.gitGraphOpens), 1);
|
||||
await page.evaluate(() => window.disposeGitSmoke());
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: current Git Graph toolbar control is icon-only, keeps its accessible name, shows hover and focus tooltips in both themes, and opens Graph.");
|
||||
} catch (error) {
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: ".audit/kanban-root-failure.png" });
|
||||
console.error(errors); throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,152 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || '../node_modules/playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\kanban-smoke';
|
||||
const files = new Map([['a.md', '# Alpha\n\nTemplate body.\n'], ['b.md', '# Beta\n'], ['folder/keep.md', '# Keep\n'], ['.runestone/config.json', '{}']]);
|
||||
const calls = [], callbacks = new Map(); let id = 0;
|
||||
window.workspaceSmoke = { files, calls, transfer: null };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: callback => { callbacks.set(++id, callback); return id; }, unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === 'plugin:event|listen') return ++id;
|
||||
if (command === 'plugin:event|unlisten' || command === 'spelling_menu_install' || command === 'spelling_menu_uninstall') return;
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'kanban-smoke', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw Error('File missing'); return files.get(args.rel); }
|
||||
if (command === 'workspace_write') {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error('Save conflict');
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === 'workspace_create') { if (files.has(args.rel)) throw Error('Exists'); files.set(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) || (!args.rel && path.startsWith('.runestone/') && !args.showInternal)) continue;
|
||||
const tail = path.slice(prefix.length), name = tail.split('/')[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === 'workspace_rename') {
|
||||
if (files.has(args.to)) throw Error('Destination exists');
|
||||
const matches = [...files].filter(([path]) => path === args.from || path.startsWith(args.from + '/'));
|
||||
if (!matches.length) throw Error('Source missing');
|
||||
for (const [path, contents] of matches) { files.delete(path); files.set(args.to + path.slice(args.from.length), contents); }
|
||||
return;
|
||||
}
|
||||
if (command === 'workspace_copy') {
|
||||
const path = (args.parent ? args.parent + '/' : '') + args.rel.split('/').pop();
|
||||
if (files.has(path)) throw Error('Destination exists');
|
||||
files.set(path, files.get(args.rel)); return { rel_path: path, name: path.split('/').pop(), kind: 'file' };
|
||||
}
|
||||
if (command === 'workspace_open_window') { window.workspaceSmoke.transfer = args.transfer; return; }
|
||||
if (command === 'workspace_abs_path') return root + '\\' + args.rel;
|
||||
if (command === 'workspace_recent') return [root];
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:dialog|message') return 'Cancel';
|
||||
if (command === 'plugins_snapshot') return { plugins: [], issues: [] };
|
||||
if (command.startsWith('plugin:window|') || command === 'workspace_open_terminal' || command === 'workspace_open_default') return;
|
||||
if (command === 'browser_stop') return;
|
||||
throw Error('Unhandled IPC: ' + command);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
|
||||
});
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
page.setDefaultTimeout(15000);
|
||||
const url = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
const menu = label => page.getByRole('menuitem', { name: label, exact: true });
|
||||
try {
|
||||
await page.goto(url);
|
||||
await row('a.md').click();
|
||||
await page.locator('.cm-content').waitFor();
|
||||
await page.locator('.mode-switcher').first().hover();
|
||||
await page.waitForFunction(() => document.querySelector('.mode-switcher')?.classList.contains('expanded'), null, { timeout: 500 });
|
||||
await page.mouse.move(500, 400);
|
||||
await row('a.md').click({ button: 'right' });
|
||||
await menu('Save as template').click();
|
||||
await page.getByRole('textbox', { name: 'Template name' }).fill('Meeting');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.waitForFunction(() => window.workspaceSmoke.files.has('.runestone/templates/Meeting.md'));
|
||||
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'New note', exact: true }).click();
|
||||
await menu('Meeting').click();
|
||||
await page.getByRole('tab', { name: /Meeting/ }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.workspaceSmoke.files.get('Meeting.md')), '# Alpha\n\nTemplate body.\n');
|
||||
const before = await page.getByRole('tab', { selected: true }).getAttribute('data-path');
|
||||
await page.keyboard.press('Control+Tab');
|
||||
assert.notEqual(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
|
||||
await page.keyboard.press('Control+Shift+Tab');
|
||||
assert.equal(await page.getByRole('tab', { selected: true }).getAttribute('data-path'), before);
|
||||
await row('b.md').click({ button: 'right' }); await menu('Cut').click();
|
||||
await row('folder').click({ button: 'right' }); await menu('Paste').click();
|
||||
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
|
||||
await row('folder').click({ button: 'right' }); await menu('Undo file move').click();
|
||||
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
|
||||
await row('folder').click({ button: 'right' }); await menu('Redo file move').click();
|
||||
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
|
||||
await row('folder').focus();
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
|
||||
const sourceBox = await row('b.md').boundingBox(), folderBox = await row('folder').boundingBox();
|
||||
await page.mouse.move(sourceBox.x + 50, sourceBox.y + sourceBox.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(folderBox.x + 70, folderBox.y + folderBox.height / 2, { steps: 12 });
|
||||
await page.mouse.up();
|
||||
await page.waitForFunction(() => window.workspaceSmoke.files.has('folder/b.md'));
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => window.workspaceSmoke.files.has('b.md'));
|
||||
await row('folder').click({ button: 'right' }); await menu('Open in terminal').click();
|
||||
assert.ok(await page.evaluate(() => window.workspaceSmoke.calls.some(call => call.command === 'workspace_open_terminal' && call.args.rel === 'folder')));
|
||||
await page.keyboard.press('Control+,');
|
||||
const settingsPage = await context.newPage();
|
||||
await settingsPage.goto(url + '/?settingsWindow=true');
|
||||
await settingsPage.getByRole('switch', { name: 'Show .runestone folder' }).check();
|
||||
await settingsPage.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
const theme = { schema: 1, id: 'smoke', name: 'Smoke theme', light: { bg: '#fefefe', text: '#222222', accent: '#334499' }, dark: { bg: '#181820', text: '#eeeeee', accent: '#aabbff' } };
|
||||
await settingsPage.locator('input[type=file][aria-label="Theme JSON file"]').setInputFiles({ name: 'smoke.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(theme)) });
|
||||
await settingsPage.waitForFunction(() => document.documentElement.dataset.palette === 'custom:smoke');
|
||||
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#181820');
|
||||
await settingsPage.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption('light');
|
||||
assert.equal(await settingsPage.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-bg').trim()), '#fefefe');
|
||||
await mkdir('.audit', { recursive: true });
|
||||
await settingsPage.screenshot({ path: '.audit/kanban-custom-theme-light.png' });
|
||||
await settingsPage.close();
|
||||
await row('.runestone').waitFor();
|
||||
await page.getByRole('tab', { name: /Meeting/ }).click();
|
||||
const editor = page.locator('.cm-content'); await editor.click(); await page.keyboard.press('Control+End'); await page.keyboard.type('Unsaved transfer');
|
||||
await page.getByRole('tab', { name: /Meeting/ }).click({ button: 'right' });
|
||||
await menu('Open in new window').click();
|
||||
await page.waitForFunction(() => window.workspaceSmoke.transfer);
|
||||
const token = await page.evaluate(() => window.workspaceSmoke.transfer);
|
||||
const target = await context.newPage();
|
||||
target.on('pageerror', error => errors.push(error.message));
|
||||
await target.goto(url + '/?tabTransfer=' + token);
|
||||
await target.getByRole('tab', { name: /Meeting/ }).waitFor();
|
||||
await target.waitForFunction(() => document.querySelector('.cm-content')?.textContent.includes('Unsaved transfer'));
|
||||
await page.getByRole('tab', { name: /Meeting/ }).waitFor({ state: 'detached' });
|
||||
await page.evaluate(() => { window.workspaceSmoke.transfer = null; });
|
||||
const draggedTab = page.getByRole('tab').first();
|
||||
const draggedPath = await draggedTab.getAttribute('data-path');
|
||||
const tabBox = await draggedTab.boundingBox();
|
||||
await page.mouse.move(tabBox.x + tabBox.width / 2, tabBox.y + tabBox.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(1480, 180, { steps: 12 });
|
||||
await page.mouse.up();
|
||||
await page.waitForFunction(() => window.workspaceSmoke.transfer);
|
||||
assert.notEqual(await page.evaluate(() => window.workspaceSmoke.transfer), token);
|
||||
assert.equal(await page.locator(`[role="tab"][data-path="${draggedPath}"]`).count(), 1, 'Keep the source tab until the new window accepts it');
|
||||
assert.equal(errors.length, 0, errors.join('\n'));
|
||||
console.log('PASS: templates, tab shortcuts, move undo/redo, terminal action, internal folder, theme import, and acknowledged unsaved tab transfer');
|
||||
} finally { await browser.close(); }
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
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 origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1152, height: 815 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
let sequence = 0;
|
||||
const callbacks = new Map();
|
||||
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 = {}) => {
|
||||
if (command === "plugins_snapshot") return { root: "D:/RuneStone/plugins", plugins: Array.from({ length: 7 }, (_, index) => ({
|
||||
manifest: { schemaVersion: 1, id: `org.example.plugin-${index}`, name: `Example plugin ${index + 1}`, author: "RuneStone Team", description: "A plugin description with enough text to check readable wrapping.", version: "0.1.1", apiVersion: 1, entry: "main.js", access: "full-app" },
|
||||
enabled: false, hash: "test", installedAt: 1791390000000, path: `D:/RuneStone/plugins/plugin-${index}`, error: null, removal: false,
|
||||
})) };
|
||||
if (command === "workspace_last_path") return null;
|
||||
if (command === "plugin:event|listen") return args.handler;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage();
|
||||
const settings = await context.newPage();
|
||||
for (const page of [main, settings]) {
|
||||
page.setDefaultTimeout(7000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
}
|
||||
await main.goto(origin);
|
||||
await settings.goto(`${origin}/?settingsWindow=true`);
|
||||
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
|
||||
const header = settings.locator("dialog > header");
|
||||
const mainHeader = main.locator(".header");
|
||||
assert.equal((await header.boundingBox()).height, (await mainHeader.boundingBox()).height, "Settings and main title bars share their height");
|
||||
for (const name of ["Minimize window", "Maximize window", "Close window"]) {
|
||||
const a = await main.getByRole("button", { name, exact: true }).boundingBox();
|
||||
const b = await settings.getByRole("button", { name, exact: true }).boundingBox();
|
||||
assert.equal(a.width, b.width);
|
||||
assert.equal(a.height, b.height, `${name} has the same dimensions in both windows`);
|
||||
}
|
||||
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
|
||||
await settings.getByRole("switch", { name: "Example plugin 1", exact: true }).waitFor();
|
||||
const content = settings.locator(".content");
|
||||
const pluginRows = content.locator(".row");
|
||||
assert.equal(await pluginRows.count(), 7);
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await settings.evaluate(value => document.documentElement.dataset.theme = value, theme);
|
||||
for (const width of [1152, 540, 360]) {
|
||||
await settings.setViewportSize({ width, height: width === 1152 ? 815 : 420 });
|
||||
assert(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth));
|
||||
assert(await content.evaluate(element => element.scrollWidth <= element.clientWidth), "The plugin content does not scroll horizontally");
|
||||
const rows = await pluginRows.evaluateAll(elements => elements.map(element => element.getBoundingClientRect().height));
|
||||
if (width === 1152) {
|
||||
assert(rows.every(height => height <= 100), `Desktop plugin rows stay compact: ${rows}`);
|
||||
const count = await pluginRows.evaluateAll(elements => {
|
||||
const container = elements[0].closest(".content").getBoundingClientRect();
|
||||
return elements.filter(element => element.getBoundingClientRect().bottom <= container.bottom).length;
|
||||
});
|
||||
assert(count >= 5, `At least five complete plugin rows fit at the screenshot size, got ${count}`);
|
||||
}
|
||||
const copy = pluginRows.first().locator(".plugin-copy");
|
||||
const controls = pluginRows.first().locator(".controls");
|
||||
const a = await copy.boundingBox(), b = await controls.boundingBox();
|
||||
assert(a.x + a.width <= b.x + 1 || a.y + a.height <= b.y + 1, "Plugin text does not overlap its actions");
|
||||
for (const button of await controls.getByRole("button").all()) {
|
||||
const bounds = await button.boundingBox();
|
||||
assert(bounds.width >= 28 && bounds.height >= 28);
|
||||
assert(await button.getAttribute("aria-label"));
|
||||
}
|
||||
await settings.screenshot({ path: `.audit/settings-density-${theme}-${width}.png` });
|
||||
}
|
||||
}
|
||||
await settings.setViewportSize({ width: 540, height: 420 });
|
||||
await settings.getByRole("button", { name: "Install from Git link", exact: true }).click();
|
||||
const install = settings.getByRole("dialog", { name: "Install from Git link", exact: true });
|
||||
await install.waitFor();
|
||||
assert(await install.getByRole("textbox", { name: "Repository link", exact: true }).isVisible());
|
||||
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Cancel");
|
||||
await settings.keyboard.press("Escape");
|
||||
await install.waitFor({ state: "detached" });
|
||||
assert.equal(await settings.evaluate(() => document.activeElement?.textContent), "Install from Git link");
|
||||
await settings.getByRole("button", { name: "General", exact: true }).click();
|
||||
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
|
||||
await settings.evaluate(async () => {
|
||||
const { pluginTools } = await import("/src/lib/plugins/external.ts");
|
||||
pluginTools.set(Array.from({ length: 12 }, (_, index) => ({ owner: "org.example.plugin-0", id: `settings-${index}`, title: `Plugin settings ${index + 1}`, surface: "settings" })));
|
||||
});
|
||||
await settings.setViewportSize({ width: 360, height: 420 });
|
||||
const sidebar = settings.locator("dialog aside");
|
||||
assert((await sidebar.boundingBox()).height <= 154, "Many plugin categories leave space for setting controls");
|
||||
assert(await sidebar.evaluate(element => element.scrollWidth <= element.clientWidth));
|
||||
await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).scrollIntoViewIfNeeded();
|
||||
const category = await settings.getByRole("button", { name: "Plugin settings 12", exact: true }).boundingBox();
|
||||
const navigation = await sidebar.boundingBox();
|
||||
assert(category.y >= navigation.y && category.y + category.height <= navigation.y + navigation.height, "Every plugin category remains reachable");
|
||||
assert(await settings.getByRole("spinbutton", { name: "Auto-save interval", exact: true }).isVisible());
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Settings density smoke passed: matching title bars and window controls, seven plugin rows, compact layout, readable text, accessible actions, both themes, narrow layouts, Git dialog focus, and many plugin categories.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,125 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { createRequire } from 'node:module';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const errors = [];
|
||||
await mkdir('.audit/appearance-language', { recursive: true });
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\appearance-smoke";
|
||||
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
|
||||
const callbacks = new Map();
|
||||
let sequence = 0;
|
||||
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 = {}) => {
|
||||
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:event|listen") return args.handler;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const settings = await context.newPage();
|
||||
const main = await context.newPage();
|
||||
for (const page of [settings, main]) { page.on('pageerror', error => errors.push(error.message)); page.setDefaultTimeout(15000); }
|
||||
await main.goto(origin);
|
||||
await settings.goto(`${origin}/?settingsWindow=true`);
|
||||
await settings.locator('#language-picker').waitFor();
|
||||
for (const [language, name, heading, appearance, enabled, files] of [
|
||||
['fr', 'Français', 'Paramètres', 'Apparence', 'Surfaces transparentes', 'Fichiers'],
|
||||
['ja', '日本語', '設定', '外観', '背景を透過', 'ファイル'],
|
||||
['zh-CN', '简体中文', '设置', '外观', '透明界面', '文件'],
|
||||
['en', 'English', 'Settings', 'Appearance', 'Transparent surfaces', 'Files'],
|
||||
]) {
|
||||
await settings.locator('#language-picker').click();
|
||||
await settings.getByRole('menuitemradio', { name, exact: true }).click();
|
||||
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
|
||||
await main.getByRole('button', { name: files, exact: true }).waitFor();
|
||||
assert.equal(await settings.locator('html').getAttribute('lang'), language);
|
||||
assert.equal(await main.locator('html').getAttribute('lang'), language);
|
||||
assert.equal(await settings.evaluate(() => localStorage.getItem('runestone.language')), language);
|
||||
await settings.reload();
|
||||
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
|
||||
// Arrow keys and Escape retain shared menu focus behavior.
|
||||
await settings.locator('#language-picker').focus();
|
||||
await settings.keyboard.press('Enter');
|
||||
await settings.keyboard.press('End');
|
||||
await settings.keyboard.press('Home');
|
||||
await settings.keyboard.press('Escape');
|
||||
assert(await settings.locator('#language-picker').evaluate(node => node === document.activeElement));
|
||||
assert(await main.evaluate(async () => {
|
||||
const { imageControls } = await import('/src/lib/editor/imageControls.ts');
|
||||
const root = document.createElement('div'); root.innerHTML = '<img data-md-src="sample.png" alt="sample">'; document.body.append(root);
|
||||
let removed = false;
|
||||
const cleanup = imageControls(root, { remove: () => { removed = true; } });
|
||||
root.querySelector('.md-image-frame').dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
|
||||
cleanup(); root.remove(); return removed;
|
||||
}), `${language}: Delete image keyboard action`);
|
||||
assert(await main.evaluate(async () => {
|
||||
const { tableSelectionControls } = await import('/src/lib/editor/tableSelectionControls.ts');
|
||||
const root = document.createElement('div'); root.innerHTML = '<div><table><tr><th>A</th><th>B</th></tr><tr><td>one</td><td>two</td></tr></table></div>'; document.body.append(root);
|
||||
const wrapper = root.firstElementChild, table = root.querySelector('table');
|
||||
let text = '| A | B |\n| --- | --- |\n| one | two |';
|
||||
const view = { posAtDOM: () => 0, dom: root, focus() {} };
|
||||
const controls = tableSelectionControls(root, wrapper, table, view, () => text, () => {}, next => { text = next; }, { get: () => undefined, activate() {}, editSource() {} }, {});
|
||||
controls.select({ anchor: { row: 1, column: 0 }, head: { row: 1, column: 0 } });
|
||||
wrapper.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
|
||||
controls.destroy(); root.remove(); return !text.includes('one') && text.includes('two');
|
||||
}), `${language}: Delete selected table cell keyboard action`);
|
||||
await settings.screenshot({ path: `.audit/appearance-language/${language}-general.png` });
|
||||
await main.locator('[data-tree-rel="theme-0.py"]').click();
|
||||
await main.locator('.monaco-editor textarea').waitFor();
|
||||
await main.locator('.view-lines').first().click({ button: 'right' });
|
||||
await main.locator('.rs-menu').waitFor();
|
||||
const copyLabels = { fr: 'Copier', ja: 'コピー', 'zh-CN': '复制', en: 'Copy' };
|
||||
await main.locator('.rs-menu .action-label').filter({ hasText: new RegExp('^' + copyLabels[language] + '$') }).waitFor();
|
||||
await main.screenshot({ path: `.audit/appearance-language/${language}-workbench-editor-menu.png` });
|
||||
await main.keyboard.press('Escape');
|
||||
await settings.getByRole('button', { name: appearance, exact: true }).click();
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await settings.evaluate(async mode => {
|
||||
const appearance = await import('/src/lib/theme/appearance.ts');
|
||||
appearance.saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 18 } });
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
}, mode);
|
||||
const toggle = settings.getByRole('switch', { name: enabled, exact: true });
|
||||
await toggle.uncheck();
|
||||
assert.equal(await settings.locator('html').getAttribute('data-transparency'), 'off');
|
||||
await main.waitForFunction(() => document.documentElement.dataset.transparency === 'off');
|
||||
const opacity = await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim());
|
||||
assert.equal(opacity, '100%');
|
||||
await settings.locator('.picker').first().click();
|
||||
const menu = settings.getByRole('menu');
|
||||
const bg = await menu.evaluate(node => getComputedStyle(node).backgroundColor);
|
||||
assert(!bg.endsWith('/ 0.82)') && !bg.startsWith('rgba'), `Opaque menu: ${bg}`);
|
||||
await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-opaque-menu.png` });
|
||||
await settings.keyboard.press('Escape');
|
||||
await toggle.check();
|
||||
await settings.locator('#surface-transparency').fill('30');
|
||||
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim()), '70%');
|
||||
await settings.setViewportSize({ width: 360, height: 640 });
|
||||
await settings.locator("#surface-transparency").scrollIntoViewIfNeeded();
|
||||
assert(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth), `${language} ${mode}: narrow overflow`);
|
||||
await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-narrow.png` });
|
||||
await settings.setViewportSize({ width: 1100, height: 800 });
|
||||
}
|
||||
await settings.reload();
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: 4 locales, persistence, cross-window updates, keyboard menu focus, both themes, opaque menus, transparency levels, narrow layout.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,175 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { version } = JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8"));
|
||||
mkdirSync(".audit", { recursive: true });
|
||||
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 context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
|
||||
const page = await context.newPage();
|
||||
const settingsPage = await context.newPage();
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
settingsPage.on("pageerror", error => errors.push(error.message));
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const disk = { "note.txt": "Original note" };
|
||||
const writes = [];
|
||||
window.__TEST__ = { disk, writes };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => 1, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugins_snapshot") return { root: "D:\\AppData\\RuneStone\\plugins", plugins: [] };
|
||||
if (command === "workspace_last_path") return "D:\\Notes";
|
||||
if (command === "workspace_open") return { root: "D:\\Notes", name: "Notes", watch_mode: "native" };
|
||||
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }];
|
||||
if (command === "workspace_read") { if (args.rel in disk) return disk[args.rel]; throw "Missing file"; }
|
||||
if (command === "workspace_write") { disk[args.rel] = args.contents; writes.push(args); return; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const settings = settingsPage.getByRole("dialog", { name: "Settings", exact: true });
|
||||
const trigger = page.getByRole("button", { name: "Settings (Ctrl+,)", exact: true });
|
||||
async function showSettings(shortcut = false) {
|
||||
if (shortcut) await page.keyboard.press("Control+,");
|
||||
else await trigger.click();
|
||||
await settingsPage.goto(`${url}/?settingsWindow=true`);
|
||||
await settings.waitFor();
|
||||
}
|
||||
async function closeSettings() {
|
||||
await settingsPage.goto("about:blank");
|
||||
await page.bringToFront();
|
||||
}
|
||||
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
|
||||
const enabled = settings.getByRole("switch", { name: "Auto-save", exact: true });
|
||||
async function changeSeconds(value) {
|
||||
await interval.fill(String(value));
|
||||
await interval.press("Tab");
|
||||
}
|
||||
async function edit(value) {
|
||||
await page.evaluate(async text => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected).setValue(text);
|
||||
}, value);
|
||||
}
|
||||
const writes = () => page.evaluate(() => window.__TEST__.writes.length);
|
||||
try {
|
||||
await page.clock.install();
|
||||
await page.goto(url);
|
||||
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
|
||||
await showSettings();
|
||||
assert.equal(await interval.inputValue(), "5");
|
||||
assert(await enabled.isChecked());
|
||||
await changeSeconds(2);
|
||||
await settings.getByRole("status").filter({ hasText: "Changes saved." }).waitFor();
|
||||
await closeSettings();
|
||||
await page.reload();
|
||||
await showSettings();
|
||||
assert.equal(await interval.inputValue(), "2", "Interval survives reload");
|
||||
await changeSeconds(0);
|
||||
await settings.getByRole("alert").filter({ hasText: "whole number" }).waitFor();
|
||||
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 2);
|
||||
await changeSeconds(2);
|
||||
await settings.getByRole("textbox", { name: "Search settings" }).fill("plugins");
|
||||
await settings.getByText("No plugins installed.", { exact: true }).waitFor();
|
||||
assert(await settings.getByRole("button", { name: "Install plugin ZIP", exact: true }).isEnabled());
|
||||
await settings.getByRole("textbox", { name: "Search settings" }).fill("no such setting");
|
||||
await settings.getByText("No settings found", { exact: true }).waitFor();
|
||||
await settings.getByRole("button", { name: "Clear search" }).click();
|
||||
await settingsPage.screenshot({ path: ".audit/settings-general.png" });
|
||||
await closeSettings();
|
||||
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await page.clock.pauseAt(new Date(await page.evaluate(() => Date.now()) + 1000));
|
||||
await showSettings();
|
||||
await changeSeconds(3);
|
||||
await closeSettings();
|
||||
await edit("Saved at three seconds");
|
||||
const before = await writes();
|
||||
await page.clock.runFor(2100);
|
||||
assert.equal(await writes(), before, "Old two-second timer is removed");
|
||||
await page.clock.runFor(1000);
|
||||
assert.equal(await writes(), before + 1, "New interval saves the dirty buffer");
|
||||
await page.clock.runFor(3100);
|
||||
assert.equal(await writes(), before + 1, "Clean files are not rewritten");
|
||||
await showSettings();
|
||||
await enabled.uncheck();
|
||||
assert(await interval.isDisabled());
|
||||
await closeSettings();
|
||||
await edit("Manual save while auto-save is disabled");
|
||||
await page.clock.runFor(10000);
|
||||
assert.equal(await writes(), before + 1);
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(count => window.__TEST__.writes.length === count, before + 2);
|
||||
await page.locator(".monaco-editor textarea").focus();
|
||||
await showSettings(true);
|
||||
await settings.waitFor();
|
||||
await closeSettings();
|
||||
await page.locator(".monaco-editor textarea").focus();
|
||||
await page.keyboard.press("F1");
|
||||
await page.getByRole("dialog", { name: "Help and about", exact: true }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
const other = await context.newPage();
|
||||
await other.goto(`${url}/?settingsWindow=true`);
|
||||
assert.equal(await other.getByRole("spinbutton", { name: "Auto-save interval" }).inputValue(), "3");
|
||||
assert.equal(await other.getByRole("switch", { name: "Auto-save", exact: true }).isChecked(), false);
|
||||
await other.getByRole("button", { name: "Restore defaults" }).click();
|
||||
await page.waitForFunction(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveEnabled);
|
||||
await showSettings();
|
||||
await enabled.waitFor();
|
||||
assert(await enabled.isChecked(), "Other windows receive changes");
|
||||
assert.equal(await interval.inputValue(), "5");
|
||||
await closeSettings();
|
||||
await edit("Auto-save enabled from another window");
|
||||
await page.clock.runFor(5100);
|
||||
assert.equal(await writes(), before + 3);
|
||||
await other.close();
|
||||
|
||||
await showSettings();
|
||||
await settingsPage.evaluate(() => {
|
||||
window.__SET_ITEM__ = Storage.prototype.setItem;
|
||||
Storage.prototype.setItem = () => { throw new Error("Storage unavailable"); };
|
||||
});
|
||||
await changeSeconds(7);
|
||||
await settings.getByRole("alert").filter({ hasText: "Could not save" }).waitFor();
|
||||
await settingsPage.evaluate(() => { Storage.prototype.setItem = window.__SET_ITEM__; });
|
||||
await closeSettings();
|
||||
await showSettings();
|
||||
assert.equal(await interval.inputValue(), "5", "Failed writes preserve applied settings");
|
||||
await closeSettings();
|
||||
|
||||
await page.getByRole("button", { name: "Help and about (F1)" }).click();
|
||||
const help = page.getByRole("dialog", { name: "Help and about", exact: true });
|
||||
await help.getByRole("heading", { name: "RuneStone", exact: true }).waitFor();
|
||||
await help.getByText(`Version ${version}`, { exact: false }).waitFor();
|
||||
await page.screenshot({ path: ".audit/settings-help.png" });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("Control+b");
|
||||
await showSettings(true);
|
||||
await settings.waitFor();
|
||||
await closeSettings();
|
||||
await page.keyboard.press("F1");
|
||||
await help.waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
await settingsPage.setViewportSize({ width: 540, height: 420 });
|
||||
await showSettings(true);
|
||||
await settings.waitFor();
|
||||
assert(await settings.evaluate(el => el.scrollWidth === el.clientWidth), "Narrow layout fits");
|
||||
await settingsPage.screenshot({ path: ".audit/settings-narrow.png" });
|
||||
for (let i = 0; i < 12; i++) {
|
||||
await settingsPage.keyboard.press("Tab");
|
||||
assert(await settings.evaluate(el => el.contains(document.activeElement)), "Focus stays in the modal");
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Settings smoke passed: timer changes, disabled auto-save, manual saves, persistence, cross-window updates, validation, storage failure, help, search, focus, shortcuts, and narrow layout.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,96 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE and CHROME_PATH if needed.
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
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 url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
mkdirSync(".audit", { recursive: true });
|
||||
const settingsCapability = JSON.parse(readFileSync(new URL("../../../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
|
||||
assert.deepEqual(settingsCapability.windows, ["settings-main", "settings-workspace-*"]);
|
||||
for (const action of ["close", "minimize", "toggle-maximize", "start-dragging"]) {
|
||||
assert(settingsCapability.permissions.includes(`core:window:allow-${action}`));
|
||||
}
|
||||
const errors = [];
|
||||
try {
|
||||
const context = await browser.newContext({ viewport: { width: 920, height: 650 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
window.__TEST__ = { calls: [], maximized: false, fail: "", resize: () => callbacks.get(listeners.get("tauri://resize"))?.({ payload: {} }) };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "settings-main" }, currentWebview: { label: "settings-main" } },
|
||||
transformCallback: callback => { const id = callbacks.size + 1; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
window.__TEST__.calls.push(command);
|
||||
if (window.__TEST__.fail === command) throw new Error("Window action failed");
|
||||
if (command === "plugins_snapshot") return { root: "D:\\SettingsTest\\plugins", plugins: [] };
|
||||
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return args.handler; }
|
||||
if (command === "plugin:window|is_maximized") return window.__TEST__.maximized;
|
||||
if (command === "plugin:window|toggle_maximize") window.__TEST__.maximized = !window.__TEST__.maximized;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
page.setDefaultTimeout(5000);
|
||||
await page.goto(`${url}/?settingsWindow=true`);
|
||||
const dialog = page.getByRole("dialog", { name: "Settings", exact: true });
|
||||
await dialog.waitFor();
|
||||
assert.equal(await dialog.getByRole("button", { name: /^Close/ }).count(), 1);
|
||||
assert(await dialog.locator("header[data-tauri-drag-region] h1[data-tauri-drag-region]").isVisible());
|
||||
assert.equal(await dialog.locator(".window-controls [data-tauri-drag-region]").count(), 0);
|
||||
const calls = () => page.evaluate(() => window.__TEST__.calls);
|
||||
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
|
||||
assert((await calls()).includes("plugin:window|minimize"));
|
||||
await page.getByRole("button", { name: "Maximize window", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await page.getByRole("button", { name: "Maximize window", exact: true }).waitFor();
|
||||
await page.evaluate(() => { window.__TEST__.maximized = true; window.__TEST__.resize(); });
|
||||
await page.getByRole("button", { name: "Restore window", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Close window", exact: true }).focus();
|
||||
await page.getByRole("tooltip", { name: "Close window", exact: true }).waitFor();
|
||||
await page.keyboard.press("Space");
|
||||
const beforeEscape = (await calls()).filter(command => command === "plugin:window|close").length;
|
||||
assert.equal(beforeEscape, 1);
|
||||
await page.getByRole("textbox", { name: "Search settings" }).focus();
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal((await calls()).filter(command => command === "plugin:window|close").length, beforeEscape + 1);
|
||||
await page.mouse.move(400, 180);
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await page.evaluate(value => document.documentElement.setAttribute("data-theme", value), theme);
|
||||
for (const size of [{ width: 920, height: 650 }, { width: 540, height: 420 }]) {
|
||||
await page.setViewportSize(size);
|
||||
assert(await dialog.evaluate(element => element.scrollWidth === element.clientWidth));
|
||||
for (const label of ["Minimize window", "Restore window", "Close window"]) {
|
||||
const button = dialog.getByRole("button", { name: label, exact: true });
|
||||
const bounds = await button.boundingBox();
|
||||
assert(bounds.x >= 0 && bounds.x + bounds.width <= size.width && bounds.height >= 28);
|
||||
assert.notEqual(await button.evaluate(element => getComputedStyle(element).borderTopLeftRadius), "0px");
|
||||
}
|
||||
await page.screenshot({ path: `.audit/settings-window-${theme}-${size.width}.png` });
|
||||
}
|
||||
}
|
||||
await page.evaluate(() => { window.__TEST__.fail = "plugin:window|minimize"; });
|
||||
await page.getByRole("button", { name: "Minimize window", exact: true }).click();
|
||||
await dialog.getByRole("alert").filter({ hasText: "Window action failed" }).waitFor();
|
||||
await page.evaluate(() => { window.__TEST__.fail = ""; });
|
||||
await page.getByRole("button", { name: "Minimize window", exact: true }).focus();
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.textContent), "Restore defaults");
|
||||
await page.keyboard.press("Tab");
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Minimize window");
|
||||
const web = await browser.newPage();
|
||||
await web.goto(`${url}/?settingsWindow=true`);
|
||||
await web.getByRole("button", { name: "Close settings", exact: true }).waitFor();
|
||||
assert.equal(await web.getByRole("group", { name: "Window controls" }).count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Settings window smoke passed: scoped permissions, drag regions, minimize, maximize, restore, resize, close, Escape, keyboard focus, tooltips, errors, both themes, narrow layout, and browser fallback.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,92 @@
|
||||
// Run against pnpm dev. Native IPC is mocked; this does not test the operating system title bar.
|
||||
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 origin = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 760 } });
|
||||
const watch = page => page.on("pageerror", error => errors.push(error.message));
|
||||
try {
|
||||
const main = await context.newPage(); watch(main);
|
||||
await main.goto(origin);
|
||||
await main.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).click();
|
||||
assert.equal(await main.locator("dialog:modal").count(), 1, "Browser preview retains the settings dialog");
|
||||
const settings = await context.newPage(); watch(settings);
|
||||
await settings.goto(`${origin}/?settingsWindow=true`);
|
||||
await settings.getByRole("heading", { name: "General", exact: true }).waitFor();
|
||||
assert.equal(await settings.locator(".workbench").count(), 0);
|
||||
const interval = settings.getByRole("spinbutton", { name: "Auto-save interval" });
|
||||
await interval.fill("17"); await interval.press("Tab");
|
||||
await main.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "17");
|
||||
await main.getByRole("spinbutton", { name: "Auto-save interval" }).fill("29");
|
||||
await main.getByRole("spinbutton", { name: "Auto-save interval" }).press("Tab");
|
||||
await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29");
|
||||
await settings.reload();
|
||||
await settings.waitForFunction(() => document.querySelector("#autosave-seconds")?.value === "29");
|
||||
await interval.fill("301"); await interval.press("Tab");
|
||||
await settings.getByRole("alert").filter({ hasText: "Choose a whole number" }).waitFor();
|
||||
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29);
|
||||
await settings.evaluate(() => { Storage.prototype.setItem = () => { throw new Error("Storage full"); }; });
|
||||
await interval.fill("40"); await interval.press("Tab");
|
||||
await settings.getByRole("alert").filter({ hasText: "Could not save these settings" }).waitFor();
|
||||
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem("runestone.settings")).autosaveSeconds), 29);
|
||||
await settings.reload();
|
||||
await settings.getByRole("button", { name: "Plug-ins", exact: true }).click();
|
||||
await settings.getByRole("heading", { name: "Plug-ins", exact: true }).waitFor();
|
||||
await settings.getByRole("button", { name: "General", exact: true }).click();
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await settings.screenshot({ path: ".audit/settings-window.png" });
|
||||
await settings.setViewportSize({ width: 540, height: 420 });
|
||||
assert.equal(await settings.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
|
||||
await settings.keyboard.press("Escape");
|
||||
await settings.waitForURL(`${origin}/`);
|
||||
|
||||
const desktop = await context.newPage(); watch(desktop);
|
||||
await desktop.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const callbacks = new Map();
|
||||
let sequence = 0;
|
||||
window.settingsTest = { opens: 0, fail: false, closes: 0 };
|
||||
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 = {}) => {
|
||||
if (command === "settings_open_window") {
|
||||
window.settingsTest.opens++;
|
||||
if (window.settingsTest.fail) throw new Error("Native window creation failed");
|
||||
await new Promise(resolve => setTimeout(resolve, 150));
|
||||
return;
|
||||
}
|
||||
if (command === "plugins_snapshot") return { root: "C:/plugins", plugins: [] };
|
||||
if (command === "workspace_last_path") return null;
|
||||
if (command === "plugin:event|listen") return args.handler;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
if (command === "plugin:window|close") { window.settingsTest.closes++; return; }
|
||||
throw new Error(`Unexpected IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
});
|
||||
await desktop.goto(origin);
|
||||
await desktop.getByRole("button", { name: "Settings (Ctrl+,)", exact: true }).dblclick();
|
||||
assert.equal(await desktop.evaluate(() => window.settingsTest.opens), 1, "Rapid requests share the pending native open");
|
||||
assert.equal(await desktop.locator("dialog:modal").count(), 0, "Native open does not block the workbench");
|
||||
await desktop.waitForTimeout(180);
|
||||
await desktop.keyboard.press("Control+,");
|
||||
await desktop.waitForFunction(() => window.settingsTest.opens === 2);
|
||||
await desktop.waitForTimeout(180);
|
||||
await desktop.evaluate(() => { window.settingsTest.fail = true; });
|
||||
await desktop.keyboard.press("Control+,");
|
||||
await desktop.getByText(/Could not open settings: .*Native window creation failed/).waitFor();
|
||||
await desktop.goto(`${origin}/?settingsWindow=true`);
|
||||
await desktop.getByRole("heading", { name: "General", exact: true }).waitFor();
|
||||
await desktop.getByRole("button", { name: "Close window", exact: true }).click();
|
||||
assert.equal(await desktop.evaluate(() => window.settingsTest.closes), 1);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Settings window smoke passed: preview fallback, standalone layout, two-way save sync, persistence, failed saves, native open requests, and close.");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,232 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("Home");
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
|
||||
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 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'));
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('drag.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['drag.md'] });
|
||||
}, source);
|
||||
await quickOpen('drag.md');
|
||||
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
|
||||
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: '.audit/table-drag-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: '.audit/table-drag-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.
|
||||
await page.setViewportSize({ width: 760, height: 700 });
|
||||
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: '.audit/table-drag-narrow.png' });
|
||||
// Long tables scroll the document while the pointer stays at its lower edge.
|
||||
await page.setViewportSize({ width: 1440, height: 700 });
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set('long.md', '# Long table\n\n| Item | Value |\n| --- | --- |\n' + Array.from({ length: 30 }, (_, i) => `| Item ${i + 1} | ${i + 1} |`).join('\n') + '\n\nAfter.\n');
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['long.md'] });
|
||||
});
|
||||
await quickOpen('long.md');
|
||||
await page.getByRole("group", { name: "Editor layout" }).locator("button.current").press("End");
|
||||
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);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: hover/focus grips, pointer-following previews and cleanup, row/column drag in both directions, indicators, alignment, undo/redo, cancellation, keyboard movement, active edits, horizontal and vertical auto-scroll.');
|
||||
} catch (error) {
|
||||
console.error('Browser errors:', errors);
|
||||
await page.screenshot({ path: '.audit/table-drag-failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,159 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await mkdir('output/october15-editor', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
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);
|
||||
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 page.screenshot({ path: `output/october15-editor/${mode}-table-enter.png` });
|
||||
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 page.screenshot({ path: `output/october15-editor/${mode}-table-paste.png` });
|
||||
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 page.screenshot({ path: `output/october15-editor/${mode}-checklist-text.png` });
|
||||
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 page.screenshot({ path: `output/october15-editor/${mode}-checklist-source.png` });
|
||||
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 page.screenshot({ path: `output/october15-editor/${mode}-title-tab.png` });
|
||||
await page.setViewportSize({ width: 600, height: 760 });
|
||||
await reset();
|
||||
await page.screenshot({ path: `output/october15-editor/${mode}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: Enter advances and creates rows in the same column, Shift+Enter, table clipboard with line breaks, task marker editing, title Tab, both themes and narrow layouts.');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: 'output/october15-editor/failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,199 @@
|
||||
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
await mockFeaturePlugins(page);
|
||||
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
await page.locator('.live-writer').waitFor();
|
||||
await page.keyboard.press('Control+e');
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
}
|
||||
|
||||
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';
|
||||
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');
|
||||
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'));
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('formulas.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['formulas.md'] });
|
||||
}, source);
|
||||
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 page.screenshot({ path: '.audit/table-cell-hint.png' });
|
||||
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');
|
||||
await page.keyboard.press('Enter');
|
||||
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, /\\=/);
|
||||
// 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 cell(3, 1).click();
|
||||
await checkFooter();
|
||||
await page.screenshot({ path: '.audit/table-formula-footer.png' });
|
||||
await page.setViewportSize({ width: 850, height: 1000 });
|
||||
await checkFooter();
|
||||
await page.screenshot({ path: '.audit/table-formula-footer-narrow.png' });
|
||||
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 page.screenshot({ path: '.audit/table-formulas.png' });
|
||||
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', 'Split']) {
|
||||
await page.getByRole('group', { name: 'Document view', exact: true }).getByRole('button', { pressed: true }).press('ArrowRight');
|
||||
const preview = page.locator('.md-page table').first();
|
||||
await preview.waitFor();
|
||||
assert.equal(await preview.locator('tbody tr').last().locator('.md-table-formula').last().innerText(), '58');
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: live recalculation, raw formula editing, Enter/Tab, undo/redo, cycle recovery, Markdown saves, help, remount, Read, and Split');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,157 @@
|
||||
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\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']]);
|
||||
window.tabMenuTest = { files, 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: () => {} };
|
||||
});
|
||||
|
||||
const output = '.audit/table-link-caret';
|
||||
await mkdir(output, { recursive: true });
|
||||
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();
|
||||
});
|
||||
|
||||
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('.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:'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 page.screenshot({ path:`${output}/click-label-${theme}-${width}.png` });
|
||||
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 page.screenshot({ path:`${output}/edit-target-${theme}-${width}.png` });
|
||||
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.tabMenuTest.files.get('a.md')), /\[Roadmap\]\(docs\/changed.md\)/);
|
||||
|
||||
const keyboard = page.getByRole('cell', { name:'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 page.screenshot({ path:`${output}/keyboard-${theme}-${width}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
|
||||
const wiki = page.getByRole('cell', { name:'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:'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.tabMenuTest.prompts), []);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: ordinary link click reveals Markdown, exact spelling caret, keyboard entry, inline Edit link, URL selection, wiki aliases, repeated targets, formatted labels, title preservation, save, undo/redo, both themes, and narrow windows. Native WebView acceptance remains open.');
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
await page.screenshot({ path:`${output}/failure.png` });
|
||||
console.log(await page.locator('.writer-cell-editor').allTextContents());
|
||||
console.log({errors, active:await page.evaluate(() => document.activeElement?.outerHTML.slice(0,300))});
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,411 @@
|
||||
import { mockFeaturePlugins } from "../_harness/pluginMocks.mjs";
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
await mockFeaturePlugins(page);
|
||||
|
||||
async function quickOpen(name) {
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill(name);
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: name }).first().click();
|
||||
await page.locator('.live-writer .cm-content').waitFor();
|
||||
}
|
||||
|
||||
const source = '# Navigation\n\nBefore.\n\n| Name | Value | Formula |\n| --- | --- | --- |\n| Alpha | 12 | =B2*2 |\n| Beta | | tail |\n| Two<br>lines | short | end |\n\nAfter.\n';
|
||||
const table = page.locator('.live-writer table');
|
||||
const cell = (r, c) => table.locator('tr').nth(r).locator('th, td').nth(c);
|
||||
const edit = page.locator('.writer-cell-editor');
|
||||
async function expectCell(r, c) {
|
||||
await page.waitForFunction(({ r, c }) => {
|
||||
const active = document.activeElement;
|
||||
const cell = active?.closest('th, td');
|
||||
return active?.matches('.writer-cell-editor') && cell?.cellIndex === c && cell.parentElement.rowIndex === r;
|
||||
}, { r, c });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
async function at(r, c, edge = 'End') {
|
||||
await cell(r, c).click();
|
||||
// ProseMirror guards native selections at the start for 200ms after focus.
|
||||
await page.waitForTimeout(220);
|
||||
await page.keyboard.press(`Control+${edge}`);
|
||||
await expectCell(r, c);
|
||||
}
|
||||
async function arrow(key, r, c) {
|
||||
await page.keyboard.press(key);
|
||||
await expectCell(r, c);
|
||||
}
|
||||
async function expectProse(after) {
|
||||
await page.waitForFunction(after => {
|
||||
const content = document.querySelector('.live-writer .cm-content');
|
||||
const table = content?.querySelector('table');
|
||||
const caret = document.getSelection()?.focusNode;
|
||||
return content === document.activeElement && !content.querySelector('.writer-cell-editor') && table && caret &&
|
||||
(table.compareDocumentPosition(caret) & (after ? Node.DOCUMENT_POSITION_FOLLOWING : Node.DOCUMENT_POSITION_PRECEDING));
|
||||
}, after);
|
||||
}
|
||||
async function caret() {
|
||||
return edit.evaluate(el => {
|
||||
const selection = window.getSelection();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.setEnd(selection.focusNode, selection.focusOffset);
|
||||
return { offset: range.toString().length, selected: selection.toString() };
|
||||
});
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('navigation.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['navigation.md'] });
|
||||
}, source);
|
||||
await quickOpen('navigation.md');
|
||||
await table.waitFor();
|
||||
|
||||
// Reproduce the reported right-arrow escape, including formula destinations.
|
||||
await at(1, 0);
|
||||
await arrow('ArrowRight', 1, 1);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await arrow('ArrowRight', 1, 1);
|
||||
assert.equal((await caret()).offset, 1);
|
||||
await arrow('ArrowRight', 1, 1);
|
||||
await arrow('ArrowRight', 1, 2);
|
||||
assert.equal(await edit.innerText(), '=B2*2');
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await arrow('ArrowLeft', 1, 1);
|
||||
assert.equal((await caret()).offset, 2);
|
||||
await arrow('ArrowLeft', 1, 1);
|
||||
assert.equal((await caret()).offset, 1);
|
||||
|
||||
// Repeated native arrows can arrive before selectionchange is delivered.
|
||||
await at(1, 1, 'Home');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectCell(1, 2);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
|
||||
// Row wrapping, empty cells, and header/body transitions.
|
||||
await at(1, 2);
|
||||
await arrow('ArrowRight', 2, 0);
|
||||
await arrow('ArrowLeft', 1, 2);
|
||||
await at(2, 0);
|
||||
await arrow('ArrowRight', 2, 1);
|
||||
await arrow('ArrowRight', 2, 2);
|
||||
await arrow('ArrowLeft', 2, 1);
|
||||
await arrow('ArrowUp', 1, 1);
|
||||
await arrow('ArrowUp', 0, 1);
|
||||
await arrow('ArrowDown', 1, 1);
|
||||
await arrow('ArrowDown', 2, 1);
|
||||
|
||||
// Exit in all four directions, without adding rows or changing existing prose.
|
||||
await at(0, 0, 'Home');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await expectProse(false);
|
||||
await at(0, 1, 'Home');
|
||||
await page.keyboard.press('ArrowUp');
|
||||
await expectProse(false);
|
||||
await at(3, 2);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectProse(true);
|
||||
await at(3, 1);
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await expectProse(true);
|
||||
assert.equal(await table.locator('tr').count(), 4);
|
||||
await page.keyboard.press('Control+s');
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get('navigation.md')), source);
|
||||
|
||||
// Reverse each exit using only the keyboard. Horizontal entry starts at the
|
||||
// first/last cell; vertical entry uses the nearest column of the edge row.
|
||||
await at(0, 0, 'Home');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await expectProse(false);
|
||||
await arrow('ArrowRight', 0, 0);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await at(0, 1, 'Home');
|
||||
await page.keyboard.press('ArrowUp');
|
||||
await expectProse(false);
|
||||
await arrow('ArrowDown', 0, 0);
|
||||
await at(3, 2);
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectProse(true);
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await arrow('ArrowLeft', 3, 2);
|
||||
assert.equal((await caret()).offset, 3);
|
||||
await at(3, 1);
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await expectProse(true);
|
||||
await page.keyboard.press('ArrowUp');
|
||||
await arrow('ArrowUp', 3, 0);
|
||||
|
||||
// Preserve the vertical goal column when crossing an empty prose line.
|
||||
for (const after of [false, true]) {
|
||||
await page.evaluate(async after => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
const view = EditorView.findFromDOM(document.querySelector('.live-writer .cm-content'));
|
||||
const EditorSelection = view.state.selection.constructor;
|
||||
const table = view.dom.querySelector('table');
|
||||
const preview = table.closest('.writer-preview');
|
||||
const from = view.posAtDOM(preview);
|
||||
const end = view.state.doc.toString().indexOf('\n\nAfter.');
|
||||
const x = table.rows[0].cells[1].getBoundingClientRect().left + 20;
|
||||
const goal = x - view.contentDOM.getBoundingClientRect().left;
|
||||
view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(after ? end + 1 : from - 1, 0, undefined, goal)]) });
|
||||
view.focus();
|
||||
}, after);
|
||||
await arrow(after ? 'ArrowUp' : 'ArrowDown', after ? 3 : 0, 1);
|
||||
}
|
||||
|
||||
// Ordinary prose cursor movement and extending a selection must stay in the
|
||||
// outer editor, even when the selection crosses the whole table.
|
||||
await page.locator('.cm-line').filter({ hasText: 'Before.' }).click();
|
||||
await page.keyboard.press('Home');
|
||||
await page.keyboard.press('ArrowRight');
|
||||
await expectProse(false);
|
||||
await at(0, 0, 'Home');
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await page.keyboard.press('Shift+ArrowDown');
|
||||
assert.equal(await edit.count(), 0);
|
||||
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
|
||||
|
||||
// Text selection and word navigation remain within the current editor.
|
||||
await at(1, 0);
|
||||
await arrow('Shift+ArrowLeft', 1, 0);
|
||||
assert.equal((await caret()).selected, 'a');
|
||||
await arrow('ArrowRight', 1, 0);
|
||||
assert.equal((await caret()).selected, '');
|
||||
await arrow('Control+ArrowLeft', 1, 0);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
|
||||
// Up/down traverse visual lines before crossing to another row.
|
||||
await at(3, 0, 'Home');
|
||||
await arrow('ArrowDown', 3, 0);
|
||||
assert.ok((await caret()).offset > 0);
|
||||
await arrow('ArrowUp', 3, 0);
|
||||
await arrow('ArrowUp', 2, 0);
|
||||
await at(2, 0);
|
||||
await arrow('ArrowDown', 3, 0);
|
||||
assert.ok((await caret()).offset <= 3, 'Down enters the first line');
|
||||
|
||||
// A wrapped cell also retains ordinary vertical caret movement.
|
||||
await at(3, 1);
|
||||
await edit.fill('A long sentence that wraps onto multiple visual lines in a narrow table cell.');
|
||||
await page.keyboard.press('Control+Home');
|
||||
await arrow('ArrowDown', 3, 1);
|
||||
assert.ok((await caret()).offset > 0 && (await caret()).offset < (await edit.innerText()).length, 'Down moves into the next visual line');
|
||||
await arrow('ArrowUp', 3, 1);
|
||||
assert.equal((await caret()).offset, 0);
|
||||
await page.keyboard.press('Control+End');
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await expectProse(true);
|
||||
|
||||
// Edits commit when navigating; formulas update and undo restores the source.
|
||||
await at(1, 1);
|
||||
await edit.fill('15');
|
||||
await arrow('ArrowRight', 1, 2);
|
||||
await arrow('ArrowDown', 2, 2);
|
||||
assert.equal(await cell(1, 2).locator('.md-table-formula').innerText(), '30');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(() => window.__TEST__.files.get('navigation.md').includes('| Alpha | 15 | =B2*2 |'));
|
||||
await at(1, 1);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '12');
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.waitForFunction(() => document.querySelector('.writer-cell-editor')?.textContent === '15');
|
||||
await page.keyboard.press('Tab');
|
||||
await expectCell(1, 2);
|
||||
await page.keyboard.press('Shift+Tab');
|
||||
await expectCell(1, 1);
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await edit.count(), 0);
|
||||
assert.equal(await page.locator('.live-writer .cm-content').evaluate(el => el === document.activeElement), true);
|
||||
|
||||
// Focusing empty and filled cells must not resize rows or columns.
|
||||
const stableSource = '# Stable table\n\n| Column 2 | Column 1 | | |\n| --- | --- | --- | --- |\n| 2cm | Value | | |\n| text | 123 | | |\n| | | | |\n| LongUnbrokenCellValue | **Bold**<br>Two lines | A longer sentence wraps in a narrow table. | `code` |\n\nParagraph one.\nParagraph two.\n';
|
||||
const dimensions = () => table.evaluate(el => [...el.rows].map(row => [...row.cells].map(cell => {
|
||||
const rect = cell.getBoundingClientRect();
|
||||
return { width: rect.width, height: rect.height };
|
||||
})));
|
||||
async function stableDimensions(expected, label) {
|
||||
const actual = await dimensions();
|
||||
for (let r = 0; r < expected.length; r++) for (let c = 0; c < expected[r].length; c++) {
|
||||
for (const axis of ['width', 'height']) assert.ok(Math.abs(expected[r][c][axis] - actual[r][c][axis]) < 1,
|
||||
`${label}: row ${r}, column ${c} ${axis} changed from ${expected[r][c][axis]} to ${actual[r][c][axis]}`);
|
||||
}
|
||||
}
|
||||
for (const theme of ['dark', 'light']) for (const width of [1440, 800]) {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; }, theme);
|
||||
const name = `stable-${theme}-${width}.md`;
|
||||
await page.evaluate(({ name, text }) => {
|
||||
window.__TEST__.files.set(name, text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
|
||||
}, { name, text: stableSource });
|
||||
await quickOpen(name);
|
||||
await table.waitFor();
|
||||
const initial = await dimensions();
|
||||
for (const [r, c] of [[1, 3], [2, 3], [3, 3], [0, 0], [1, 0], [1, 1], [4, 0], [4, 1], [4, 2], [4, 3], [2, 1]]) {
|
||||
await at(r, c);
|
||||
await stableDimensions(initial, `${theme} ${width} focus ${r},${c}`);
|
||||
}
|
||||
await arrow('Tab', 2, 2);
|
||||
await stableDimensions(initial, `${theme} ${width} Tab`);
|
||||
await arrow('ArrowDown', 3, 2);
|
||||
await stableDimensions(initial, `${theme} ${width} ArrowDown`);
|
||||
await page.keyboard.press('Escape');
|
||||
await stableDimensions(initial, `${theme} ${width} blur`);
|
||||
|
||||
// Delete the blank line through the prose editor, then save and undo/redo.
|
||||
await page.locator('.cm-line').filter({ hasText: 'Paragraph one.' }).click();
|
||||
await page.keyboard.press('Home');
|
||||
await page.keyboard.press('Backspace');
|
||||
await page.waitForFunction(() => document.querySelectorAll('.live-writer table tr').length === 5 &&
|
||||
[...document.querySelectorAll('.cm-line')].some(line => line.textContent === 'Paragraph one.'));
|
||||
await page.keyboard.press('Control+s');
|
||||
const joined = stableSource.replace('\n\nParagraph one.', '\nParagraph one.');
|
||||
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(({ name, source }) => window.__TEST__.files.get(name) === source, { name, source: stableSource });
|
||||
await page.keyboard.press('Control+y');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined, { name, joined });
|
||||
assert.equal(await table.locator('tr').count(), 5);
|
||||
await at(1, 0);
|
||||
await edit.fill('updated');
|
||||
await page.keyboard.press('Escape');
|
||||
await page.keyboard.press('Control+s');
|
||||
await page.waitForFunction(({ name, joined }) => window.__TEST__.files.get(name) === joined.replace('| 2cm |', '| updated |'), { name, joined });
|
||||
}
|
||||
await page.setViewportSize({ width: 1440, height: 1000 });
|
||||
|
||||
// A line break in a tall table keeps the caret and viewport in the active cell.
|
||||
const tallSource = '# Tall table\n\nBefore.\n\n| Name | Value |\n| --- | --- |\n' +
|
||||
Array.from({ length: 45 }, (_, i) => `| Row ${i + 1} | |`).join('\n') + '\n\nAfter.\n';
|
||||
await page.evaluate(text => {
|
||||
window.__TEST__.files.set('line-breaks.md', text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['line-breaks.md'] });
|
||||
}, tallSource);
|
||||
await quickOpen('line-breaks.md');
|
||||
await table.waitFor();
|
||||
for (const [r, c, key] of [[1, 0, 'Shift+Enter'], [20, 0, 'Shift+Enter'], [21, 0, '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 page.evaluate(({ name, text }) => {
|
||||
window.__TEST__.files.set(name, text);
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: [name] });
|
||||
}, { name, text: loneTable });
|
||||
await quickOpen(name);
|
||||
await table.waitFor();
|
||||
await at(after ? 1 : 0, 0, after ? 'End' : 'Home');
|
||||
await page.keyboard.press(key);
|
||||
await expectProse(after);
|
||||
const reverse = { ArrowLeft: 'ArrowRight', ArrowUp: 'ArrowDown', ArrowRight: 'ArrowLeft', ArrowDown: 'ArrowUp' }[key];
|
||||
// Exiting added two newlines, so first cross the outer empty line.
|
||||
await page.keyboard.press(reverse);
|
||||
await arrow(reverse, after ? 1 : 0, 0);
|
||||
await page.keyboard.press(`Control+${after ? 'End' : 'Home'}`);
|
||||
await page.keyboard.press(key);
|
||||
await expectProse(after);
|
||||
await page.keyboard.type('Outside.');
|
||||
await page.keyboard.press('Control+s');
|
||||
const expected = after ? `${loneTable}\n\nOutside.` : `\nOutside.\n${loneTable}`;
|
||||
await page.waitForFunction(({ name, expected }) => window.__TEST__.files.get(name) === expected, { name, expected });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: arrows, caret positions, row wrapping, empty/formula/header cells, entry/exit in all directions, goal columns, document boundaries, text selection, word movement, multiline/wrapped text, line breaks and scrolling in tall tables, save, undo/redo, Tab and Escape, stable cell dimensions and table/prose boundaries in both themes at wide/narrow widths');
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: '.audit/table-navigation-failure.png' });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,222 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
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(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
try {
|
||||
await mkdir('output/todo-table', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
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());
|
||||
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 page.screenshot({path:`output/todo-table/selection-${theme}-${width}.png`});
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.screenshot({path:`output/todo-table/menu-${theme}-${width}.png`});
|
||||
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 page.screenshot({path:`output/todo-table/empty-columns-selected-${theme}-${width}.png`});
|
||||
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 page.screenshot({path:`output/todo-table/empty-columns-deleted-${theme}-${width}.png`});
|
||||
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.'));
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: drag and Shift-click ranges, keyboard range entry and extension, Delete/Backspace remove cells, explicit clear, undo, partial/row/column/all delete, outer edges, light/dark narrow screenshots.');
|
||||
} catch(error) {
|
||||
await page.screenshot({path:'output/todo-table/failure.png'});
|
||||
console.error(errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,357 @@
|
||||
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 context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
const page = await context.newPage();
|
||||
await context.exposeBinding("settingsHostInvoke", (_source, command, args) =>
|
||||
page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args }));
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
const pluginCode = `export function activate(api) {
|
||||
window.tabTest.api = api;
|
||||
const mount = (id, container) => {
|
||||
window.tabTest.mounts[id] = (window.tabTest.mounts[id] || 0) + 1;
|
||||
const input = document.createElement("input");
|
||||
input.setAttribute("aria-label", id + " state");
|
||||
container.append(input);
|
||||
return () => {
|
||||
window.tabTest.disposals[id] = (window.tabTest.disposals[id] || 0) + 1;
|
||||
input.remove();
|
||||
};
|
||||
};
|
||||
for (const [id, title, icon] of [["overview", "Overview", "puzzle"], ["browser", "Browser", "globe"]]) {
|
||||
api.registerView({ id, title, icon, placement: "editor", navigation: true, mount: container => mount(id, container) });
|
||||
}
|
||||
api.registerDocumentType({
|
||||
id: "board", title: "Board", icon: "kanban", extensions: ["board"],
|
||||
identify: (path, source) => ({ id: source }),
|
||||
mount: (container, document) => mount(document.id, container),
|
||||
});
|
||||
}`;
|
||||
await context.addInitScript(({ pluginCode }) => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false, autosaveSeconds: 5 }));
|
||||
const root = "C:\\plugin-tab-workspace";
|
||||
const files = new Map(["a.md", "b.md", "c.md", ...Array.from({ length: 14 }, (_, index) => `note-${index}.md`)].map(name => [name, `# ${name}\n\nOriginal text.\n`]));
|
||||
files.set("project.board", "project-board");
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
let sequence = 0, enabled = true;
|
||||
const manifest = { schemaVersion: 1, id: "test.tabs", name: "Tab fixtures", author: "Tests", description: "Test editor tabs.", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
|
||||
const emit = async (event, payload) => {
|
||||
await Promise.all((listeners.get(event) || []).map(id => callbacks.get(id)?.({ event, id, payload })));
|
||||
};
|
||||
window.tabTest = { mounts: {}, disposals: {}, answer: "Cancel", prompts: 0, closeRequests: 0, destroys: 0, files };
|
||||
const label = location.search.includes("secondary") ? "workspace-2" : "main";
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label }, currentWebview: { label } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (location.search.includes("settingsWindow") && !command.startsWith("plugin:event|") && !command.startsWith("plugin:window|"))
|
||||
return window.settingsHostInvoke(command, args);
|
||||
if (command === "settings_open_window") return;
|
||||
if (command === "plugin:event|listen") {
|
||||
const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "plugin:window|is_maximized") return false;
|
||||
if (command === "plugin:window|close") {
|
||||
window.tabTest.closeRequests++;
|
||||
await emit("tauri://close-requested");
|
||||
return;
|
||||
}
|
||||
if (command === "plugin:window|destroy") { window.tabTest.destroys++; return; }
|
||||
if (command.startsWith("plugin:window|")) return;
|
||||
if (command === "plugins_snapshot") return { root, plugins: [{ manifest, hash: "test", enabled, path: root, error: null, removal: false }] };
|
||||
if (command === "plugins_load") return pluginCode;
|
||||
if (command === "plugins_data") return "null";
|
||||
if (command === "plugins_release") return;
|
||||
if (command === "plugins_set_enabled") { enabled = args.enabled; emit("plugins-changed"); return; }
|
||||
if (command === "workspace_last_path") return location.search.includes("no-workspace") ? null : root;
|
||||
if (command === "workspace_open") return { root, name: "plugin-tab-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") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:dialog|message") { window.tabTest.prompts++; return window.tabTest.answer; }
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
}, { pluginCode });
|
||||
|
||||
const tab = name => page.getByRole("tab", { name, exact: true });
|
||||
const bar = page.getByRole("tablist", { name: "Working tabs" });
|
||||
const order = () => bar.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
|
||||
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
async function openFile(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 settle();
|
||||
}
|
||||
async function openView(name) {
|
||||
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name, exact: true }).click();
|
||||
await tab(name).waitFor();
|
||||
}
|
||||
async function drag(from, to, side = "before", cancel) {
|
||||
const source = await tab(from).boundingBox(), target = await tab(to).boundingBox();
|
||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 });
|
||||
if (cancel === "escape") await page.keyboard.press("Escape");
|
||||
if (cancel === "outside") await page.mouse.move(target.x, target.y + 100);
|
||||
await page.mouse.up();
|
||||
await settle();
|
||||
}
|
||||
async function menu(name) {
|
||||
await tab(name).click({ button: "right" });
|
||||
await page.getByRole("menu", { name: "Tab actions" }).waitFor();
|
||||
}
|
||||
|
||||
try {
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
await page.goto(url);
|
||||
await page.getByText("plugin-tab-workspace", { exact: true }).waitFor();
|
||||
await tab("New tab").waitFor();
|
||||
for (const close of ["button", "middle", "shortcut", "all"]) {
|
||||
const before = await tab("New tab").getAttribute("data-path");
|
||||
if (close === "button") await page.getByRole("button", { name: "Close New tab", exact: true }).click();
|
||||
if (close === "middle") await tab("New tab").click({ button: "middle" });
|
||||
if (close === "shortcut") await page.keyboard.press("Control+w");
|
||||
if (close === "all") {
|
||||
await menu("New tab");
|
||||
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
|
||||
}
|
||||
await page.waitForFunction(before => {
|
||||
const tabs = document.querySelectorAll('.header [role="tab"]');
|
||||
return tabs.length === 1 && tabs[0].getAttribute("data-path") !== before;
|
||||
}, before);
|
||||
assert.equal(await tab("New tab").getAttribute("aria-selected"), "true");
|
||||
}
|
||||
for (const name of ["a.md", "b.md", "c.md", "note-0.md"]) await openFile(name);
|
||||
await page.getByRole("textbox", { name: "Writing editor", exact: true }).filter({ hasText: "# note-0.md" }).waitFor();
|
||||
for (const width of [880, 1280, 1440]) {
|
||||
await page.setViewportSize({ width, height: 1000 });
|
||||
await settle();
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
const dimensions = await page.locator(".header").evaluate(header => {
|
||||
const bar = header.querySelector('[role="tablist"]');
|
||||
const rows = [...bar.querySelectorAll(".tab")];
|
||||
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]');
|
||||
const bounds = bar.getBoundingClientRect();
|
||||
return {
|
||||
overflow: bar.scrollWidth - bar.clientWidth,
|
||||
left: bounds.left,
|
||||
navigationRight: header.querySelector(".header-left").getBoundingClientRect().right,
|
||||
tabWidth: Math.min(...rows.map(row => row.getBoundingClientRect().width)),
|
||||
gap: plus.getBoundingClientRect().left - Math.min(bounds.right, rows.at(-1).getBoundingClientRect().right),
|
||||
fits: header.scrollWidth <= header.clientWidth,
|
||||
};
|
||||
});
|
||||
if (width >= 1280) assert.ok(dimensions.overflow <= 1, JSON.stringify(dimensions));
|
||||
assert.ok(Math.abs(dimensions.left - dimensions.navigationRight) <= 2, JSON.stringify(dimensions));
|
||||
assert.ok(dimensions.tabWidth >= 96, JSON.stringify(dimensions));
|
||||
assert.ok(dimensions.gap >= 0 && dimensions.gap <= 8, JSON.stringify(dimensions));
|
||||
assert.ok(dimensions.fits);
|
||||
const plus = page.getByRole("button", { name: "New tab (Ctrl T)", exact: true });
|
||||
await plus.evaluate(button => button.blur());
|
||||
await plus.focus();
|
||||
await page.locator('[role="tooltip"]:popover-open').filter({ hasText: "New tab (Ctrl T)" }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.locator(".header").screenshot({ path: `.audit/compact-tabs-${width}-${theme}.png` });
|
||||
}
|
||||
}
|
||||
await menu("note-0.md");
|
||||
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
|
||||
await tab("New tab").waitFor();
|
||||
assert.deepEqual(await order(), ["New tab"]);
|
||||
console.log("PASS: the last tab becomes a new tab, tabs retain usable widths, and the adjacent plus button has a focus tooltip");
|
||||
await openFile("a.md");
|
||||
await openFile("b.md");
|
||||
await openView("Overview");
|
||||
await page.getByRole("textbox", { name: "overview state" }).fill("Keep this state");
|
||||
await openView("Browser");
|
||||
const siteIcon = "data:image/svg+xml;base64," + Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" rx="3" fill="#e35336"/></svg>').toString('base64');
|
||||
await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon);
|
||||
await tab("Browser").locator("img.tab-icon").waitFor();
|
||||
await page.waitForFunction(() => document.querySelector('.header img.tab-icon')?.naturalWidth === 16);
|
||||
assert.equal(await tab("Browser").locator("img").getAttribute("alt"), "");
|
||||
assert.equal(await tab("Browser").locator("img").getAttribute("draggable"), "false");
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
await mkdir("output", { recursive: true });
|
||||
await page.locator(".header").screenshot({ path: `output/tab-site-icon-${theme}.png` });
|
||||
}
|
||||
await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", "data:image/png;base64,aW1hZ2U="));
|
||||
await tab("Browser").locator("img").waitFor({ state: "detached" });
|
||||
assert.equal(await tab("Browser").locator("svg").count(), 1);
|
||||
await page.evaluate(image => window.tabTest.api.updateViewIcon("browser", image), siteIcon);
|
||||
await tab("Browser").locator("img").waitFor();
|
||||
await page.evaluate(() => window.tabTest.api.updateViewIcon("browser", null));
|
||||
await tab("Browser").locator("img").waitFor({ state: "detached" });
|
||||
assert.equal(await tab("Browser").locator("svg").count(), 1);
|
||||
console.log("PASS: site icons appear in both themes and missing or broken icons use the fallback");
|
||||
await openFile("project.board");
|
||||
await tab("project").waitFor();
|
||||
assert.equal(await page.locator(".header").getByRole("tablist").count(), 1);
|
||||
assert.deepEqual(await order(), ["a.md", "b.md", "Overview", "Browser", "project"]);
|
||||
await drag("Overview", "a.md");
|
||||
await drag("project", "b.md");
|
||||
await drag("a.md", "Browser", "after");
|
||||
const mixed = ["Overview", "project", "b.md", "Browser", "a.md"];
|
||||
assert.deepEqual(await order(), mixed);
|
||||
assert.equal(await tab("project").getAttribute("aria-selected"), "true");
|
||||
for (const cancel of ["escape", "outside"]) {
|
||||
await drag("Browser", "Overview", "before", cancel);
|
||||
assert.deepEqual(await order(), mixed);
|
||||
}
|
||||
await tab("Browser").press("Alt+Shift+Home");
|
||||
assert.equal((await order())[0], "Browser");
|
||||
await tab("Browser").press("ArrowRight");
|
||||
assert.equal(await tab("Overview").getAttribute("aria-selected"), "true");
|
||||
assert.equal(await page.getByRole("textbox", { name: "overview state" }).inputValue(), "Keep this state");
|
||||
await tab("Overview").press("ArrowRight");
|
||||
assert.equal(await tab("project").getAttribute("aria-selected"), "true");
|
||||
await page.evaluate(() => window.tabTest.api.updateViewTitle("browser", "Browser page"));
|
||||
await tab("Browser page").waitFor();
|
||||
assert.equal((await order())[0], "Browser page");
|
||||
assert.deepEqual(await page.evaluate(() => window.tabTest.mounts), { overview: 1, browser: 1, "project-board": 1 });
|
||||
assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), {});
|
||||
assert.equal(await tab("project").getAttribute("aria-controls"), await page.getByRole("tabpanel", { name: "project" }).getAttribute("id"));
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await page.evaluate(theme => document.documentElement.dataset.theme = theme, theme);
|
||||
await menu("Browser page");
|
||||
assert.equal(await page.getByRole("menuitem", { name: "Pin", exact: true }).count(), 1);
|
||||
await page.getByRole("menuitem", { name: "Move tab", exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: "Move tab right", exact: true }).click();
|
||||
}
|
||||
console.log("PASS: mixed file, feature, and plugin document tabs move without remounting or changing selection");
|
||||
|
||||
await tab("Browser page").press("Alt+Shift+End");
|
||||
await tab("project").press("Alt+Shift+End");
|
||||
await tab("a.md").press("Alt+Shift+Home");
|
||||
await tab("Overview").press("Alt+Shift+Home");
|
||||
await tab("b.md").press("Alt+Shift+Home");
|
||||
await menu("b.md");
|
||||
await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
await tab("a.md").click();
|
||||
await page.locator(".cm-content").fill("Unsaved text");
|
||||
await tab("a.md •").waitFor();
|
||||
assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]);
|
||||
await menu("Overview");
|
||||
await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click();
|
||||
await page.waitForFunction(() => window.tabTest.prompts === 1);
|
||||
assert.deepEqual(await order(), ["b.md", "Overview", "a.md •", "Browser page", "project"]);
|
||||
await page.evaluate(() => window.tabTest.answer = "Ok");
|
||||
await menu("Overview");
|
||||
await page.getByRole("menuitem", { name: "Close tabs after", exact: true }).click();
|
||||
await tab("project").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["b.md", "Overview"]);
|
||||
assert.equal(await tab("Overview").getAttribute("aria-selected"), "true");
|
||||
await menu("Overview");
|
||||
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
|
||||
await tab("Overview").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["b.md"]);
|
||||
assert.deepEqual(await page.evaluate(() => window.tabTest.disposals), { browser: 1, "project-board": 1, overview: 1 });
|
||||
console.log("PASS: mixed close actions follow visual order, preserve pins, and respect cancelled discards");
|
||||
|
||||
await openView("Overview");
|
||||
for (let index = 0; index < 14; index++) await openFile(`note-${index}.md`);
|
||||
await tab("Overview").press("Alt+Shift+Home");
|
||||
const source = await tab("Overview").boundingBox(), bounds = await bar.boundingBox();
|
||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 });
|
||||
await page.waitForFunction(() => {
|
||||
const bar = document.querySelector('[aria-label="Working tabs"]');
|
||||
return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2;
|
||||
});
|
||||
await page.mouse.up();
|
||||
await settle();
|
||||
assert.equal((await order()).at(-1), "Overview");
|
||||
await page.keyboard.press("Control+t");
|
||||
await tab("New tab").press("Alt+Shift+Home");
|
||||
await openFile("c.md");
|
||||
assert.equal((await order())[0], "c.md");
|
||||
const fileOrder = (await order()).filter(name => name !== "Overview");
|
||||
await page.keyboard.press("Control+,");
|
||||
const settingsPage = await context.newPage();
|
||||
settingsPage.on("pageerror", error => errors.push(error.message));
|
||||
await settingsPage.goto(url + '/?settingsWindow=true');
|
||||
await settingsPage.getByRole("button", { name: "Plug-ins", exact: true }).click();
|
||||
await settingsPage.getByRole("switch", { name: "Tab fixtures", exact: true }).click();
|
||||
await settingsPage.waitForFunction(() => document.getElementById("external-test.tabs")?.checked === false);
|
||||
await tab("Overview").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), fileOrder);
|
||||
console.log("PASS: plugin drag auto-scroll, empty-tab replacement, and plugin disable preserve the mixed order");
|
||||
await settingsPage.close();
|
||||
|
||||
await page.goto(`${url}?no-workspace`);
|
||||
await tab("New tab").waitFor();
|
||||
await openView("Overview");
|
||||
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
|
||||
await openView("Browser");
|
||||
await drag("Browser", "Overview");
|
||||
assert.deepEqual(await order(), ["Browser", "Overview"]);
|
||||
await page.setViewportSize({ width: 880, height: 700 });
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: ".audit/plugin-tab-order.png" });
|
||||
await tab("Browser").click({ button: "middle" });
|
||||
assert.deepEqual(await order(), ["Overview"]);
|
||||
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
|
||||
await tab("New tab").waitFor();
|
||||
assert.deepEqual(await order(), ["New tab"]);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: plugin tabs reorder and close without an open workspace");
|
||||
for (const close of ["button", "middle", "shortcut", "all", "plugin", "dirty"]) {
|
||||
await page.goto(`${url}?secondary`);
|
||||
await tab("New tab").waitFor();
|
||||
if (close === "plugin") {
|
||||
await openView("Overview");
|
||||
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.tabTest.closeRequests), 0);
|
||||
await page.getByRole("button", { name: "Close Overview", exact: true }).click();
|
||||
} else if (close === "dirty") {
|
||||
await openFile("a.md");
|
||||
await page.locator(".cm-content").fill("Keep these unsaved edits");
|
||||
await page.keyboard.press("Control+w");
|
||||
await page.waitForFunction(() => window.tabTest.prompts === 1);
|
||||
assert.equal(await page.evaluate(() => window.tabTest.destroys), 0);
|
||||
assert.match(await page.locator(".cm-content").innerText(), /Keep these unsaved edits/);
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: ".audit/secondary-last-tab-cancel.png" });
|
||||
await page.evaluate(() => window.tabTest.answer = "Ok");
|
||||
await page.keyboard.press("Control+w");
|
||||
} else if (close === "button") {
|
||||
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
|
||||
} else if (close === "middle") {
|
||||
await tab("New tab").click({ button: "middle" });
|
||||
} else if (close === "shortcut") {
|
||||
await page.keyboard.press("Control+w");
|
||||
} else {
|
||||
await openFile("a.md");
|
||||
await openFile("b.md");
|
||||
await menu("b.md");
|
||||
await page.getByRole("menuitem", { name: "Close all", exact: true }).click();
|
||||
}
|
||||
await page.waitForFunction(() => window.tabTest.destroys === 1);
|
||||
assert.equal(await page.evaluate(() => window.tabTest.closeRequests), close === "dirty" ? 2 : 1);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: secondary windows close through the window guard for the last empty, document, or plugin tab; Cancel preserves unsaved edits");
|
||||
} catch (error) {
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: ".audit/plugin-tab-order-failure.png" });
|
||||
console.error("Browser errors:", errors);
|
||||
throw error;
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
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 context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
|
||||
const pluginCode = `export function activate(api) {
|
||||
let state = "Board state";
|
||||
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
|
||||
saveTabState: () => state, restoreTabState: value => { state = value; },
|
||||
mount(container) {
|
||||
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
|
||||
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
|
||||
return () => input.remove();
|
||||
}
|
||||
});
|
||||
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
|
||||
identify: (path, source) => source === "board document" ? { id: path } : null,
|
||||
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
|
||||
});
|
||||
}`;
|
||||
await context.addInitScript(({ pluginCode }) => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const params = new URLSearchParams(location.search);
|
||||
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
|
||||
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
|
||||
files.set("saved.board", "board document");
|
||||
if (params.has("missing")) files.delete("a.md");
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
|
||||
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
|
||||
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command.startsWith("plugin:window|")) return;
|
||||
if (command === "plugin:dialog|message") return window.lifecycle.answer;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
|
||||
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
|
||||
if (command === "plugins_load") return pluginCode;
|
||||
if (command === "plugins_data") return "null";
|
||||
if (command === "plugins_release") return;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, { pluginCode });
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
const dragSources = new Map();
|
||||
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
|
||||
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
|
||||
async function create(query = "") {
|
||||
const page = await context.newPage(); page.setDefaultTimeout(15000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
|
||||
}
|
||||
async function open(page, name) {
|
||||
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
|
||||
}
|
||||
async function openBoard(page) {
|
||||
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
}
|
||||
async function pin(page, name) {
|
||||
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
}
|
||||
async function start(page, name) {
|
||||
const data = await tab(page, name).evaluate(node => {
|
||||
assertDraggable(node);
|
||||
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
|
||||
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
dragSources.set(data, { page, name });
|
||||
return data;
|
||||
}
|
||||
async function drop(page, data) {
|
||||
await bar(page).evaluate((node, data) => {
|
||||
const transfer = new DataTransfer(); transfer.setData("application/x-runestone-tab", data);
|
||||
const options = { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer };
|
||||
node.dispatchEvent(new DragEvent("dragover", options)); node.dispatchEvent(new DragEvent("drop", options));
|
||||
}, data);
|
||||
const source = dragSources.get(data);
|
||||
if (source) {
|
||||
await tab(source.page, source.name).evaluateAll(nodes => nodes[0]?.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
}
|
||||
}
|
||||
async function screenshots(page, prefix) {
|
||||
await mkdir("output/tab-lifecycle", { recursive: true });
|
||||
for (const mode of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-${mode}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: 700, height: 700 });
|
||||
await page.screenshot({ path: `output/tab-lifecycle/${prefix}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
}
|
||||
try {
|
||||
const page = await create();
|
||||
for (const name of ["a.md", "b.md", "c.md"]) await open(page, name);
|
||||
await tab(page, "c.md").focus(); await page.keyboard.press("Alt+Shift+ArrowLeft"); await page.keyboard.press("Alt+Shift+ArrowLeft");
|
||||
await pin(page, "b.md"); await tab(page, "b.md").click();
|
||||
await page.evaluate(() => window.lifecycle.close());
|
||||
const session = await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`)));
|
||||
assert.deepEqual(session.documents.map(item => item.path), ["c.md", "a.md", "b.md"]);
|
||||
assert.equal(session.activePath, "b.md"); assert.equal(session.documents[2].pinned, true);
|
||||
assert.ok(!JSON.stringify(session).includes("Saved text"));
|
||||
await page.goto(url + "?missing"); await tab(page, "b.md").waitFor();
|
||||
assert.deepEqual(await bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["c.md", "b.md"]);
|
||||
assert.equal(await tab(page, "b.md").getAttribute("aria-selected"), "true");
|
||||
await tab(page, "b.md").click({ button: "right" }); await page.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await page.keyboard.press("Escape");
|
||||
await screenshots(page, "restored-documents");
|
||||
await page.locator(".cm-content").fill("Unsaved draft");
|
||||
await page.evaluate(() => window.lifecycle.close());
|
||||
assert.deepEqual(await page.evaluate(() => JSON.parse(localStorage.getItem(`runestone.document-session.${encodeURIComponent(window.lifecycle.root)}`))), session);
|
||||
await page.evaluate(() => { window.lifecycle.answer = "Ok"; return window.lifecycle.close(); });
|
||||
page.on("dialog", dialog => dialog.accept());
|
||||
await page.reload(); await tab(page, "b.md").waitFor();
|
||||
assert.match(await page.locator(".cm-content").innerText(), /Saved text/);
|
||||
await open(page, "saved.board"); await page.getByText("Saved board document", { exact: true }).waitFor();
|
||||
await page.evaluate(() => window.lifecycle.close()); await page.reload();
|
||||
await tab(page, "saved").waitFor(); await page.getByText("Saved board document", { exact: true }).waitFor();
|
||||
const source = await create("?plugins"), target = await create("?plugins"), other = await create("?other"), disabled = await create("?plugins&disabled");
|
||||
assert.equal(await tab(other, "New tab").count(), 1);
|
||||
await openBoard(source); await source.getByRole("textbox", { name: "Board state" }).fill("Transferred board state"); await pin(source, "Board");
|
||||
let data = await start(source, "Board"); assert.ok(JSON.parse(data).tabTransfer);
|
||||
await drop(other, data); await other.getByText("Move tabs only between windows of the same workspace.").waitFor();
|
||||
await drop(disabled, data); await disabled.getByText("Enable this tab's plugin before moving it to this window.").waitFor();
|
||||
assert.equal(await tab(source, "Board").count(), 1);
|
||||
await drop(target, data); await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
|
||||
await tab(target, "Board").click({ button: "right" }); await target.getByRole("menuitem", { name: "Unpin", exact: true }).waitFor(); await target.keyboard.press("Escape");
|
||||
await screenshots(target, "joined-plugin");
|
||||
data = await start(target, "Board"); await drop(source, data); await tab(target, "Board").waitFor({ state: "detached" });
|
||||
await openBoard(target); await target.getByRole("textbox", { name: "Board state" }).fill("Destination state");
|
||||
data = await start(source, "Board"); await drop(target, data);
|
||||
await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor();
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Destination state"); assert.equal(await tab(source, "Board").count(), 1);
|
||||
await tab(source, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
await tab(source, "Board").click({ button: "right" }); await source.getByRole("menuitem", { name: "Open in new window", exact: true }).click();
|
||||
const token = await source.evaluate(() => window.lifecycle.transfer); assert.ok(token);
|
||||
const detached = await create(`?plugins&tabTransfer=${token}`); await detached.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
await tab(source, "Board").waitFor({ state: "detached" });
|
||||
data = await start(detached, "Board"); await drop(source, data); await tab(detached, "Board").waitFor({ state: "detached" });
|
||||
assert.equal(await source.getByRole("textbox", { name: "Board state" }).inputValue(), "Transferred board state");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: normal-close restore, order, active tab, pins, missing files, workspace isolation, canceled close, disk-only restore, plugin documents, plugin join, duplicate protection, disabled plugin, and tear-out return");
|
||||
} catch (reason) {
|
||||
for (const page of context.pages()) console.error(page.url(), (await page.locator("body").innerText()).slice(-1000));
|
||||
throw reason;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,139 @@
|
||||
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`]));
|
||||
window.tabMenuTest = { prompts: [], answer: "Cancel", revealed: null, clipboard: null };
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { window.tabMenuTest.clipboard = text; } } });
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
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 ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "workspace_write") throw new Error("Keep unsaved edits for the close test");
|
||||
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 tab = name => page.getByRole("tab", { name, exact: true });
|
||||
const menu = () => page.getByRole("menu", { name: "Tab actions", exact: true });
|
||||
const item = name => page.getByRole("menuitem", { name, exact: true });
|
||||
const order = () => page.getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path));
|
||||
async function open(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 tab(name).waitFor();
|
||||
}
|
||||
async function show(name) { await tab(name).click({ button: "right" }); await menu().waitFor(); }
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("tab-menu-workspace", { exact: true }).waitFor();
|
||||
for (const name of ["a.md", "b.md", "c.md", "d.md"]) await open(name);
|
||||
await page.locator(".cm-content").filter({ hasText: "Original text." }).waitFor();
|
||||
await show("b.md");
|
||||
assert.equal(await tab("d.md").getAttribute("aria-selected"), "true");
|
||||
assert.equal(await item("Rename…").count(), 0);
|
||||
assert.equal(await item("Reading view").count(), 0);
|
||||
assert.doesNotMatch(await menu().innerText(), /Alt|Shift|Ctrl/);
|
||||
await page.screenshot({ path: ".audit/tab-menu-inactive.png" });
|
||||
await item("Pin").click();
|
||||
assert.equal(await tab("d.md").getAttribute("aria-selected"), "true");
|
||||
assert.ok(await tab("b.md").getAttribute("aria-describedby"));
|
||||
await show("d.md");
|
||||
assert.equal(await item("Close tabs after").isDisabled(), true);
|
||||
await page.screenshot({ path: ".audit/tab-menu-active.png" });
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await tab("d.md").evaluate(node => node === document.activeElement), true);
|
||||
await tab("d.md").press("Shift+F10");
|
||||
assert.equal(await item("Close").evaluate(node => node === document.activeElement), true);
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await item("Move tab left").evaluate(node => node === document.activeElement), true);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await page.keyboard.press("Escape");
|
||||
await show("d.md");
|
||||
await item("Reading view").click();
|
||||
await page.locator(".md-page").waitFor();
|
||||
await show("d.md");
|
||||
await item("Editing view").click();
|
||||
await page.locator(".cm-editor").waitFor();
|
||||
await show("d.md");
|
||||
await item("Source mode").click();
|
||||
await page.locator(".monaco-editor").waitFor();
|
||||
await show("d.md");
|
||||
await item("Writing mode").click();
|
||||
await page.locator(".cm-editor").waitFor();
|
||||
await show("d.md");
|
||||
await item("Copy path").click();
|
||||
await item("Workspace path").click();
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.clipboard), "d.md");
|
||||
await show("d.md");
|
||||
await item("Show in system explorer").click();
|
||||
assert.equal(await page.evaluate(() => window.tabMenuTest.revealed), "d.md");
|
||||
await show("d.md");
|
||||
await item("Rename…").click();
|
||||
await page.getByRole("dialog").getByRole("textbox").fill("renamed.md");
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Continue", exact: true }).click();
|
||||
await tab("renamed.md").waitFor();
|
||||
await show("a.md");
|
||||
await item("Close tabs after").click();
|
||||
await tab("renamed.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["a.md", "b.md"]);
|
||||
await open("c.md");
|
||||
await show("c.md");
|
||||
await item("Close others").click();
|
||||
await tab("a.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["b.md", "c.md"]);
|
||||
await page.locator(".cm-content").click();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Unsaved text");
|
||||
await tab("c.md •").waitFor();
|
||||
await show("c.md •");
|
||||
await item("Close all").click();
|
||||
await page.waitForFunction(() => window.tabMenuTest.prompts.length === 1);
|
||||
assert.deepEqual(await order(), ["b.md", "c.md"]);
|
||||
await page.evaluate(() => { window.tabMenuTest.answer = "Ok"; });
|
||||
await show("c.md •");
|
||||
await item("Close all").click();
|
||||
await tab("c.md •").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(), ["b.md"]);
|
||||
await show("b.md");
|
||||
assert.equal(await item("Close all").isDisabled(), true);
|
||||
await item("Unpin").click();
|
||||
await show("b.md");
|
||||
await item("Close").click();
|
||||
await tab("b.md").waitFor({ state: "detached" });
|
||||
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
|
||||
await show("New tab");
|
||||
assert.equal(await item("Rename…").count(), 0);
|
||||
assert.equal(await item("Reading view").count(), 0);
|
||||
await page.keyboard.press("Escape");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: active/inactive menus, keyboard focus, pinning, view modes, file actions, ordered closes, cancelled discard, and empty tabs");
|
||||
} catch (error) {
|
||||
await page.screenshot({ path: ".audit/tab-menu-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,128 @@
|
||||
// Run against pnpm dev with PLAYWRIGHT_MODULE set if Playwright is shared.
|
||||
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("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tab-order-workspace";
|
||||
const files = new Map(Array.from({ length: 16 }, (_, i) => [`note-${String(i).padStart(2, "0")}.md`, `# Note ${i}\n\nKeep this text.\n`]));
|
||||
files.set("note-00.md", Array.from({ length: 200 }, (_, i) => `Paragraph ${i}.\n\n`).join(""));
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence,
|
||||
unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tab-order-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") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const tab = name => page.getByRole("tab", { name, exact: true });
|
||||
const order = () => page.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path));
|
||||
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
async function open(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 tab(name).waitFor();
|
||||
}
|
||||
async function drag(from, to, side, cancel) {
|
||||
const source = await tab(from).boundingBox();
|
||||
const target = await tab(to).boundingBox();
|
||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(side === "before" ? target.x + 2 : target.x + target.width - 2, target.y + target.height / 2, { steps: 10 });
|
||||
if (cancel === "escape") await page.keyboard.press("Escape");
|
||||
if (cancel === "outside") await page.mouse.move(target.x, target.y + 100);
|
||||
await page.mouse.up();
|
||||
await settle();
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("tab-order-workspace", { exact: true }).waitFor();
|
||||
for (const name of ["note-00.md", "note-01.md", "note-02.md"]) await open(name);
|
||||
await drag("note-00.md", "note-02.md", "after");
|
||||
assert.deepEqual(await order(), ["note-01.md", "note-02.md", "note-00.md"]);
|
||||
assert.equal(await tab("note-02.md").getAttribute("aria-selected"), "true");
|
||||
await drag("note-00.md", "note-01.md", "before");
|
||||
assert.deepEqual(await order(), ["note-00.md", "note-01.md", "note-02.md"]);
|
||||
for (const cancel of ["escape", "outside"]) {
|
||||
await drag("note-00.md", "note-02.md", "after", cancel);
|
||||
assert.deepEqual(await order(), ["note-00.md", "note-01.md", "note-02.md"]);
|
||||
}
|
||||
await tab("note-00.md").click();
|
||||
assert.equal(await tab("note-00.md").getAttribute("aria-selected"), "true");
|
||||
await page.locator(".cm-scroller").evaluate(node => { node.scrollTop = 1200; });
|
||||
await settle();
|
||||
const scrollTop = await page.locator(".cm-scroller").evaluate(node => node.scrollTop);
|
||||
assert.ok(scrollTop > 1000);
|
||||
await tab("note-00.md").press("Alt+Shift+ArrowRight");
|
||||
await settle();
|
||||
assert.deepEqual(await order(), ["note-01.md", "note-00.md", "note-02.md"]);
|
||||
assert.ok(Math.abs(await page.locator(".cm-scroller").evaluate(node => node.scrollTop) - scrollTop) < 5);
|
||||
assert.equal(await tab("note-00.md").evaluate(node => document.activeElement === node), true);
|
||||
await tab("note-00.md").press("ArrowRight");
|
||||
assert.equal(await tab("note-02.md").getAttribute("aria-selected"), "true");
|
||||
await tab("note-02.md").press("Shift+F10");
|
||||
await page.getByRole("menuitem", { name: "Move tab", exact: true }).click();
|
||||
assert.equal(await page.getByRole("menuitem", { name: /Move tab right/ }).isDisabled(), true);
|
||||
await page.getByRole("menuitem", { name: /Move tab left/ }).click();
|
||||
assert.deepEqual(await order(), ["note-01.md", "note-02.md", "note-00.md"]);
|
||||
await tab("note-01.md").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Move tab", exact: true }).click();
|
||||
assert.equal(await page.getByRole("menuitem", { name: /Move tab left/ }).isDisabled(), true);
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(await page.getByRole("menu", { name: "Tab actions" }).count(), 0);
|
||||
console.log("PASS: pointer moves, cancellation, keyboard moves, and tab menus");
|
||||
|
||||
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
|
||||
await tab("New tab").press("Alt+Shift+Home");
|
||||
assert.match((await order())[0], /^empty:/);
|
||||
await page.getByRole("button", { name: "Close New tab", exact: true }).click();
|
||||
await tab("note-01.md").click({ button: "middle" });
|
||||
assert.deepEqual(await order(), ["note-02.md", "note-00.md"]);
|
||||
console.log("PASS: empty tabs and middle-click close after reorder");
|
||||
|
||||
for (let i = 3; i < 16; i++) await open(`note-${String(i).padStart(2, "0")}.md`);
|
||||
const bar = page.getByRole("tablist", { name: "Working tabs" });
|
||||
assert.ok(await bar.evaluate(node => node.scrollLeft > 0));
|
||||
await tab("note-15.md").press("Alt+Shift+Home");
|
||||
assert.equal((await order())[0], "note-15.md");
|
||||
assert.equal(await bar.evaluate(node => node.scrollLeft), 0);
|
||||
const source = await tab("note-15.md").boundingBox();
|
||||
const bounds = await bar.boundingBox();
|
||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2, { steps: 10 });
|
||||
await page.waitForFunction(() => {
|
||||
const bar = document.querySelector('[aria-label="Working tabs"]');
|
||||
return bar.scrollLeft >= bar.scrollWidth - bar.clientWidth - 2;
|
||||
});
|
||||
// Native drag needs a fresh pointer event after the strip scrolls beneath it.
|
||||
await page.mouse.move(bounds.x + bounds.width - 4, source.y + source.height / 2);
|
||||
await page.mouse.move(bounds.x + bounds.width - 3, source.y + source.height / 2);
|
||||
await page.mouse.up();
|
||||
await settle();
|
||||
assert.equal((await order()).at(-1), "note-15.md");
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: automatic scrolling and drag to the end of an overflowing tab bar");
|
||||
if (process.env.SCREENSHOT_PATH) await page.screenshot({ path: process.env.SCREENSHOT_PATH });
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
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 context = await browser.newContext({ viewport: { width: 1400, height: 900 } });
|
||||
const pluginCode = `export function activate(api) {
|
||||
let state = "Board state";
|
||||
api.registerView({ id: "board", title: "Board", icon: "kanban", placement: "editor", navigation: true,
|
||||
saveTabState: () => state, restoreTabState: value => { state = value; },
|
||||
mount(container) {
|
||||
const input = document.createElement("input"); input.setAttribute("aria-label", "Board state");
|
||||
input.value = state; input.oninput = () => { state = input.value; }; container.append(input);
|
||||
return () => input.remove();
|
||||
}
|
||||
});
|
||||
api.registerDocumentType({ id: "document", title: "Board document", extensions: ["board"], icon: "kanban",
|
||||
identify: (path, source) => source === "board document" ? { id: path } : null,
|
||||
mount(container) { container.textContent = "Saved board document"; return () => { container.textContent = ""; }; }
|
||||
});
|
||||
}`;
|
||||
await context.addInitScript(({ pluginCode }) => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const params = new URLSearchParams(location.search);
|
||||
const root = params.has("other") ? "C:\\other-lifecycle" : params.has("plugins") ? "C:\\plugins-lifecycle" : "C:\\document-lifecycle";
|
||||
const files = new Map(["a.md", "b.md", "c.md"].map(name => [name, `# ${name}\n\nSaved text.\n`]));
|
||||
files.set("saved.board", "board document");
|
||||
if (params.has("missing")) files.delete("a.md");
|
||||
let sequence = 0;
|
||||
const callbacks = new Map(), listeners = new Map();
|
||||
const emit = async event => { for (const id of listeners.get(event) || []) await callbacks.get(id)?.({ event, id, payload: null }); };
|
||||
window.lifecycle = { answer: "Cancel", close: () => emit("tauri://close-requested"), root, transfer: null };
|
||||
const manifest = { schemaVersion: 1, id: "test.lifecycle", name: "Lifecycle", author: "Tests", description: "Tab fixture", version: "1.0.0", apiVersion: 1, entry: "main.js", access: "full-app" };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: fn => { const id = ++sequence; callbacks.set(id, fn); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") { const ids = listeners.get(args.event) || []; ids.push(args.handler); listeners.set(args.event, ids); return args.handler; }
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command.startsWith("plugin:window|")) return;
|
||||
if (command === "plugin:dialog|message") return window.lifecycle.answer;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "Lifecycle", watch_mode: "native" };
|
||||
if (command === "workspace_open_window") { window.lifecycle.transfer = args.transfer; return; }
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("Missing file"); return files.get(args.rel); }
|
||||
if (command === "workspace_list") return args.rel ? [] : [...files.keys()].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: params.has("disabled") ? [] : [{ manifest, hash: "test", enabled: true, path: root, error: null, removal: false }] };
|
||||
if (command === "plugins_load") return pluginCode;
|
||||
if (command === "plugins_data") return "null";
|
||||
if (command === "plugins_release") return;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, { pluginCode });
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const errors = [];
|
||||
const tab = (page, name) => page.getByRole("tab", { name, exact: true });
|
||||
const bar = page => page.getByRole("tablist", { name: "Working tabs" });
|
||||
async function create(query = "") {
|
||||
const page = await context.newPage(); page.setDefaultTimeout(15000);
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.goto(url + query); await page.getByRole("tab").first().waitFor(); return page;
|
||||
}
|
||||
async function open(page, name) {
|
||||
await page.bringToFront(); 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 tab(page, name === "saved.board" ? "saved" : name).waitFor();
|
||||
}
|
||||
async function openBoard(page) {
|
||||
await page.getByRole("navigation", { name: "Plugin shortcuts" }).getByRole("button", { name: "Board", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Board state" }).waitFor();
|
||||
}
|
||||
async function pin(page, name) {
|
||||
await tab(page, name).click({ button: "right" }); await page.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
}
|
||||
async function start(page, name) {
|
||||
const data = await tab(page, name).evaluate(node => {
|
||||
assertDraggable(node);
|
||||
function assertDraggable(node) { if (node.getAttribute("draggable") !== "true") throw new Error("The tab must support native transfer."); }
|
||||
const transfer = new DataTransfer(); node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
return data;
|
||||
}
|
||||
async function screenshots(page, prefix) {
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const mode of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-${mode}.png` });
|
||||
}
|
||||
await page.setViewportSize({ width: 700, height: 700 });
|
||||
await page.screenshot({ path: `output/tab-ribbon-drop/${prefix}-narrow.png` });
|
||||
await page.setViewportSize({ width: 1400, height: 900 });
|
||||
}
|
||||
const order = page => bar(page).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.textContent.trim()));
|
||||
async function eventAt(page, data, point, type = "dragover", mime = "application/x-runestone-tab") {
|
||||
return page.evaluate(({ data, point, type, mime }) => {
|
||||
const transfer = new DataTransfer(); transfer.setData(mime, data);
|
||||
const node = document.elementFromPoint(point.x, point.y) || document.body;
|
||||
const event = new DragEvent(type, { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y, dataTransfer: transfer });
|
||||
node.dispatchEvent(event);
|
||||
return event.defaultPrevented;
|
||||
}, { data, point, type, mime });
|
||||
}
|
||||
async function receive(page, data, point) {
|
||||
assert.equal(await eventAt(page, data, point), true);
|
||||
assert.equal(await eventAt(page, data, point, "drop"), true);
|
||||
}
|
||||
async function point(page, kind) {
|
||||
return page.locator(".header").evaluate((header, kind) => {
|
||||
const bounds = header.getBoundingClientRect();
|
||||
const bar = header.querySelector('[role="tablist"]').getBoundingClientRect();
|
||||
const plus = header.querySelector('[aria-label="New tab (Ctrl T)"]').getBoundingClientRect();
|
||||
const first = header.querySelector('.tab').getBoundingClientRect();
|
||||
if (kind === "near") return { x: first.left + first.width / 2, y: bounds.bottom + 18 };
|
||||
if (kind === "outside") return { x: first.left + first.width / 2, y: bounds.bottom + 80 };
|
||||
if (kind === "precise") return { x: bar.left + 2, y: bar.top + bar.height / 2 };
|
||||
if (kind === "controls") { const controls = header.querySelector('.window-controls').getBoundingClientRect(); return { x: controls.left + 10, y: controls.top + controls.height / 2 }; }
|
||||
if (kind === "blank") return { x: plus.right + 16, y: bounds.top + bounds.height / 2 };
|
||||
return { x: plus.left + plus.width / 2, y: plus.top + plus.height / 2 };
|
||||
}, kind);
|
||||
}
|
||||
try {
|
||||
const source = await create("?plugins"), target = await create("?plugins");
|
||||
await open(target, "b.md");
|
||||
await open(source, "a.md"); await pin(source, "a.md");
|
||||
await source.locator(".cm-content").fill("Unsaved ribbon transfer");
|
||||
let data = await start(source, "a.md •");
|
||||
const broad = await point(target, "blank");
|
||||
assert.equal(await eventAt(target, data, broad), true, "Blank titlebar space accepts transferred tabs");
|
||||
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), true);
|
||||
assert.equal(await eventAt(target, data, await point(target, "outside")), false, "The document body stays outside the drop target");
|
||||
assert.equal(await bar(target).evaluate(node => node.classList.contains("receiving")), false);
|
||||
assert.equal(await eventAt(target, data, await point(target, "controls")), false, "Window controls stay outside the drop target");
|
||||
assert.equal(await eventAt(target, data, broad, "dragover", "text/plain"), false, "Ordinary file and text drags retain their behavior");
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const mode of ["light", "dark"]) {
|
||||
await target.evaluate(async mode => { const { applyAppearance } = await import("/src/lib/theme/appearance.ts"); await applyAppearance({ theme: "default", mode }); }, mode);
|
||||
await eventAt(target, data, broad);
|
||||
await target.screenshot({ path: `output/tab-ribbon-drop/${mode}-blank-receiving.png` });
|
||||
}
|
||||
await receive(target, data, broad);
|
||||
await tab(target, "a.md •").waitFor(); await tab(source, "a.md •").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["b.md", "a.md •"]);
|
||||
assert.match(await target.locator(".cm-content").innerText(), /Unsaved ribbon transfer/);
|
||||
assert.ok(await tab(target, "a.md •").getAttribute("aria-describedby"));
|
||||
await open(source, "c.md"); data = await start(source, "c.md");
|
||||
await receive(target, data, await point(target, "precise"));
|
||||
await tab(target, "c.md").waitFor(); await tab(source, "c.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •"]);
|
||||
await openBoard(source); await pin(source, "Board"); await source.getByRole("textbox", { name: "Board state" }).fill("Plugin ribbon state");
|
||||
data = await start(source, "Board");
|
||||
await target.setViewportSize({ width: 700, height: 700 });
|
||||
const nearby = await point(target, "near");
|
||||
await eventAt(target, data, nearby);
|
||||
await bar(target).and(target.locator('.receiving')).waitFor();
|
||||
await target.screenshot({ path: "output/tab-ribbon-drop/narrow-near-receiving.png" });
|
||||
await receive(target, data, nearby);
|
||||
await tab(target, "Board").waitFor(); await tab(source, "Board").waitFor({ state: "detached" });
|
||||
assert.deepEqual(await order(target), ["c.md", "b.md", "a.md •", "Board"]);
|
||||
assert.equal(await target.getByRole("textbox", { name: "Board state" }).inputValue(), "Plugin ribbon state");
|
||||
assert.ok(await tab(target, "Board").getAttribute("aria-describedby"));
|
||||
await screenshots(target, "ribbon-plugin-pinned");
|
||||
data = await start(target, "Board");
|
||||
assert.equal(await eventAt(target, data, await point(target, "near")), false, "Same-window reordering stays precise");
|
||||
await receive(target, data, await point(target, "precise"));
|
||||
assert.deepEqual(await order(target), ["Board", "c.md", "b.md", "a.md •"]);
|
||||
await tab(target, "Board").evaluate(node => node.dispatchEvent(new DragEvent("dragend", { bubbles: true })));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: broad titlebar and nearby ribbon drops, exact tab ordering, rejection outside the ribbon and over window controls, ordinary drag isolation, pinned unsaved documents, narrow plugin transfers, and source acknowledgement");
|
||||
} catch (error) {
|
||||
await mkdir("output/tab-ribbon-drop", { recursive: true });
|
||||
for (const [index, page] of context.pages().entries()) await page.screenshot({ path: `output/tab-ribbon-drop/failure-${index}.png` });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function open(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();
|
||||
}
|
||||
async function settle() {
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
async function roundTrip(selector, label) {
|
||||
const scroller = page.locator(selector);
|
||||
const position = async (top) => label === 'IDE'
|
||||
? page.evaluate(async top => {
|
||||
const { monaco } = await import('/src/lib/editor/monacoEnv.ts');
|
||||
const editor = monaco.editor.getEditors().find(view => view.getDomNode()?.isConnected);
|
||||
if (top !== undefined) editor.setScrollTop(top, 1);
|
||||
return editor.getScrollTop();
|
||||
}, top)
|
||||
: scroller.evaluate((el, top) => {
|
||||
if (top !== undefined) el.scrollTop = top;
|
||||
return el.scrollTop;
|
||||
}, top);
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
await position(1800);
|
||||
await settle();
|
||||
const first = await position();
|
||||
assert.ok(first > 1000, `${label}: first document is scrollable`);
|
||||
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
await position(650);
|
||||
await settle();
|
||||
const second = await position();
|
||||
for (let repeat = 0; repeat < 2; repeat++) {
|
||||
for (const [name, expected] of [['scroll-a.md', first], ['scroll-b.md', second]]) {
|
||||
await page.getByRole('tab', { name, exact: true }).click();
|
||||
await scroller.waitFor({ state: 'visible' });
|
||||
await settle();
|
||||
const actual = await position();
|
||||
assert.ok(Math.abs(actual - expected) < 5, `${label}: ${name} expected ${expected}, got ${actual}`);
|
||||
}
|
||||
}
|
||||
console.log(`PASS: ${label} retains independent tab scroll positions`);
|
||||
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.evaluate(() => {
|
||||
for (const name of ['scroll-a.md', 'scroll-b.md']) {
|
||||
window.__TEST__.files.set(name, Array.from({ length: 200 }, (_, i) => `Paragraph ${i} of ${name}.\n\n`).join(''));
|
||||
}
|
||||
window.__TEST__.emit('workspace-event', { root: window.__TEST__.root, kind: 'create', paths: ['scroll-a.md', 'scroll-b.md'] });
|
||||
});
|
||||
await open('scroll-b.md');
|
||||
await open('scroll-a.md');
|
||||
if (await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).count()) {
|
||||
await page.getByRole('button', { name: 'Switch to writing layout (Ctrl E)', exact: true }).click();
|
||||
}
|
||||
await roundTrip('.cm-scroller', 'Writing');
|
||||
await page.getByRole('button', { name: 'Read', exact: true }).click();
|
||||
await roundTrip('.md-page', 'Reading');
|
||||
await page.getByRole('button', { name: 'Split', exact: true }).click();
|
||||
await roundTrip('.md-page', 'Split preview');
|
||||
await page.getByRole('button', { name: 'Edit', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'scroll-b.md', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Switch to IDE layout (Ctrl E)', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'scroll-a.md', exact: true }).click();
|
||||
await roundTrip('.monaco-scrollable-element', 'IDE');
|
||||
assert.deepEqual(errors, []);
|
||||
} catch (error) {
|
||||
console.error('Browser errors:', errors);
|
||||
console.error((await page.locator('body').innerText()).slice(-2000));
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -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 context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const root = location.search.includes("other") ? "C:\\other" : "C:\\transfer";
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten" || command.startsWith("plugin:window|")) return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "transfer", watch_mode: "native" };
|
||||
if (command === "workspace_read") return "# " + args.rel + "\n\nOriginal text.\n";
|
||||
if (command === "workspace_list") return args.rel ? [] : ["a.md", "b.md"].map(name => ({ name, rel_path: name, kind: "file" }));
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugins_snapshot") return { root, plugins: [] };
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const url = process.env.SMOKE_URL || "http://127.0.0.1:1420";
|
||||
const source = await context.newPage(), target = await context.newPage(), other = await context.newPage();
|
||||
for (const page of [source, target, other]) page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
for (const page of [source, target, other]) page.on("pageerror", error => errors.push(error.message));
|
||||
const tab = (page, name) => page.locator('[role="tab"]').filter({ hasText: name });
|
||||
async function open(page, name) {
|
||||
await page.bringToFront();
|
||||
await page.getByRole("tablist", { name: "Working tabs" }).waitFor();
|
||||
await page.getByRole("tab").first().waitFor();
|
||||
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 tab(page, name).waitFor();
|
||||
}
|
||||
async function start(page, name) {
|
||||
return tab(page, name).evaluate(node => {
|
||||
const transfer = new DataTransfer();
|
||||
node.dispatchEvent(new DragEvent("dragstart", { bubbles: true, dataTransfer: transfer }));
|
||||
return transfer.getData("application/x-runestone-tab");
|
||||
});
|
||||
}
|
||||
async function drop(page, data) {
|
||||
await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.setData("application/x-runestone-tab", data);
|
||||
node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
|
||||
node.dispatchEvent(new DragEvent("drop", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
|
||||
}, data);
|
||||
}
|
||||
async function captureTransfer(page, data) {
|
||||
await mkdir("output/tab-transfer", { recursive: true });
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await page.evaluate(async mode => {
|
||||
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
await applyAppearance({ theme: 'default', mode });
|
||||
}, theme);
|
||||
await page.getByRole("tablist", { name: "Working tabs" }).evaluate((node, data) => {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.setData("application/x-runestone-tab", data);
|
||||
node.dispatchEvent(new DragEvent("dragover", { bubbles: true, cancelable: true, clientX: node.getBoundingClientRect().left, dataTransfer: transfer }));
|
||||
}, data);
|
||||
await page.screenshot({ path: `output/tab-transfer/${theme}-receiving.png` });
|
||||
}
|
||||
}
|
||||
try {
|
||||
await Promise.all([source.goto(url), target.goto(url), other.goto(url + "/?other")]);
|
||||
await open(source, "a.md");
|
||||
await open(target, "b.md");
|
||||
await tab(source, "a.md").click({ button: "right" });
|
||||
await source.getByRole("menuitem", { name: "Pin", exact: true }).click();
|
||||
await source.locator(".cm-content").fill("Unsaved transfer text");
|
||||
let data = await start(source, "a.md");
|
||||
assert.ok(JSON.parse(data).tabTransfer);
|
||||
await drop(other, data);
|
||||
await other.getByText("Move tabs only between windows of the same workspace.").waitFor();
|
||||
assert.equal(await tab(source, "a.md").count(), 1);
|
||||
await captureTransfer(target, data);
|
||||
await drop(target, data);
|
||||
console.log("Dropped into matching workspace");
|
||||
await tab(target, "a.md").waitFor();
|
||||
await tab(source, "a.md").waitFor({ state: "detached" });
|
||||
console.log("Source acknowledged transfer");
|
||||
assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/);
|
||||
const changedTarget = await context.newPage();
|
||||
changedTarget.on("pageerror", error => errors.push(error.message));
|
||||
await changedTarget.goto(url);
|
||||
await changedTarget.getByRole("tab").first().waitFor();
|
||||
await open(source, "a.md");
|
||||
data = await start(source, "a.md");
|
||||
await source.locator(".cm-content").fill("Changed during transfer");
|
||||
await drop(changedTarget, data);
|
||||
await tab(changedTarget, "a.md").waitFor();
|
||||
assert.equal(await tab(source, "a.md").count(), 1);
|
||||
assert.match(await source.locator(".cm-content").innerText(), /Changed during transfer/);
|
||||
assert.ok(await tab(target, "a.md").getAttribute("aria-describedby"));
|
||||
assert.deepEqual(await target.getByRole("tablist", { name: "Working tabs" }).getByRole("tab").evaluateAll(nodes => nodes.map(node => node.dataset.path)), ["a.md", "b.md"]);
|
||||
await open(source, "a.md");
|
||||
data = await start(source, "a.md");
|
||||
await drop(target, data);
|
||||
await target.getByText("This tab is already open in this window. The source tab remains open.").waitFor();
|
||||
assert.equal(await tab(source, "a.md").count(), 1);
|
||||
assert.match(await target.locator(".cm-content").innerText(), /Unsaved transfer text/);
|
||||
await mkdir("output/tab-transfer", { recursive: true });
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await target.evaluate(async mode => {
|
||||
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
await applyAppearance({ theme: 'default', mode });
|
||||
}, theme);
|
||||
await target.screenshot({ path: `output/tab-transfer/${theme}.png` });
|
||||
}
|
||||
await target.setViewportSize({ width: 700, height: 700 });
|
||||
await target.screenshot({ path: "output/tab-transfer/narrow.png" });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: same-workspace transfer, unsaved text, pinned state, insertion order, other-workspace rejection, duplicate protection, and source edits during transfer");
|
||||
} catch (reason) {
|
||||
console.log(await other.locator("body").innerText());
|
||||
console.log(await target.locator("body").innerText());
|
||||
throw reason;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,198 @@
|
||||
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("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tree-actions-test";
|
||||
const files = new Map([
|
||||
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
|
||||
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
|
||||
]);
|
||||
const calls = [];
|
||||
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
|
||||
let sequence = 0;
|
||||
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence,
|
||||
unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tree-actions-test", 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") { files.set(args.rel, args.contents); 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_delete") {
|
||||
if (args.rel === state.fail) throw new Error("Access denied");
|
||||
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_copy") {
|
||||
const to = args.rel + "-copy";
|
||||
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
|
||||
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
|
||||
}
|
||||
if (command === "workspace_rename") {
|
||||
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
|
||||
for (const [path, text] of [...files]) if (contains(args.from, path)) {
|
||||
files.delete(path);
|
||||
files.set(args.to + path.slice(args.from.length), text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
|
||||
if (command === "workspace_reveal") return;
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:dialog|message") return state.answer;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
window.__TEST__ = state;
|
||||
});
|
||||
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
|
||||
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
|
||||
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
|
||||
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
async function reset() {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await row("notes").waitFor();
|
||||
}
|
||||
async function action(path, name) {
|
||||
await row(path).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name, exact: true }).click();
|
||||
await settle();
|
||||
}
|
||||
async function selectFiles() {
|
||||
await row("a.md").click();
|
||||
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
|
||||
await settle();
|
||||
await row("b.md").click({ modifiers: ["Control"] });
|
||||
await settle();
|
||||
}
|
||||
async function drag(sourcePath, targetPath, place = "inside") {
|
||||
const source = await row(sourcePath).boundingBox();
|
||||
const target = await row(targetPath).boundingBox();
|
||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
|
||||
await page.mouse.up();
|
||||
await settle();
|
||||
}
|
||||
try {
|
||||
await reset();
|
||||
await selectFiles();
|
||||
await row("a.md").click({ button: "right" });
|
||||
assert.deepEqual(await selected(), ["a.md", "b.md"]);
|
||||
assert.equal(await page.getByRole("menuitem", { name: "Rename", exact: true }).isDisabled(), true);
|
||||
await page.keyboard.press("Escape");
|
||||
await action("a.md", "Copy workspace paths");
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), "a.md\nb.md");
|
||||
await action("b.md", "Copy system paths");
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.clipboard), "C:\\tree-actions-test\\a.md\nC:\\tree-actions-test\\b.md");
|
||||
await action("a.md", "Show in Explorer");
|
||||
assert.deepEqual((await calls("workspace_reveal")).map(args => args.rel), ["a.md", "b.md"]);
|
||||
await action("a.md", "Bookmark");
|
||||
await action("b.md", "Pin");
|
||||
let marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
|
||||
assert.deepEqual(marks.bookmarks, ["a.md", "b.md"]);
|
||||
assert.deepEqual(marks.pins, ["a.md", "b.md"]);
|
||||
await action("a.md", "Unpin");
|
||||
await action("a.md", "Remove bookmarks");
|
||||
await action("a.md", "Make copies (2)");
|
||||
assert.deepEqual((await calls("workspace_copy")).map(args => args.rel), ["a.md", "b.md"]);
|
||||
await row("c.md").click({ button: "right" });
|
||||
assert.deepEqual(await selected(), ["c.md"]);
|
||||
assert.equal(await page.getByRole("menuitem", { name: "Rename", exact: true }).isDisabled(), false);
|
||||
await page.keyboard.press("Escape");
|
||||
console.log("PASS: selection, clipboard paths, marks, copies, reveal, and single-item menus");
|
||||
|
||||
await reset();
|
||||
await selectFiles();
|
||||
await page.evaluate(() => { window.__TEST__.answer = "Cancel"; });
|
||||
await action("a.md", "Delete (2)");
|
||||
assert.equal((await calls("workspace_delete")).length, 0);
|
||||
assert.deepEqual(await selected(), ["a.md", "b.md"]);
|
||||
await page.evaluate(() => { window.__TEST__.answer = "Ok"; window.__TEST__.fail = "a.md"; });
|
||||
await row("c.md").click({ modifiers: ["Control"] });
|
||||
await action("a.md", "Delete (3)");
|
||||
await row("c.md").waitFor({ state: "detached" });
|
||||
assert.deepEqual((await calls("workspace_delete")).map(args => args.rel), ["a.md", "b.md", "c.md"]);
|
||||
assert.match(await page.locator(".tree .error").textContent(), /a.md: Access denied/);
|
||||
assert.deepEqual(await selected(), ["a.md"]);
|
||||
console.log("PASS: cancellation, one confirmation per batch, partial failure, and selection after deletion");
|
||||
|
||||
await reset();
|
||||
await row("notes").click();
|
||||
await row("notes/nested").click();
|
||||
await row("notes").click({ modifiers: ["Control"] });
|
||||
await row("notes/a.md").click({ modifiers: ["Control"] });
|
||||
await row("notes/nested/b.md").click({ modifiers: ["Control"] });
|
||||
await row("c.md").click({ modifiers: ["Control"] });
|
||||
await action("notes/a.md", "Make copies (5)");
|
||||
assert.deepEqual((await calls("workspace_copy")).map(args => args.rel), ["notes", "c.md"]);
|
||||
await action("notes/nested/b.md", "Delete (5)");
|
||||
await row("notes").waitFor({ state: "detached" });
|
||||
assert.deepEqual((await calls("workspace_delete")).map(args => args.rel), ["notes", "c.md"]);
|
||||
assert.equal((await calls("plugin:dialog|message")).length, 1);
|
||||
console.log("PASS: recursive copy and delete process selected folders and children once");
|
||||
|
||||
await reset();
|
||||
await selectFiles();
|
||||
await drag("a.md", "target");
|
||||
await row("target/b.md").waitFor();
|
||||
assert.deepEqual((await calls("workspace_rename")), [{ from: "a.md", to: "target/a 2.md" }, { from: "b.md", to: "target/b.md" }]);
|
||||
assert.deepEqual(await selected(), ["target/a 2.md", "target/b.md"]);
|
||||
console.log("PASS: group move into a collapsed folder preserves an existing same-name file");
|
||||
|
||||
await reset();
|
||||
await row("notes").click();
|
||||
await row("notes/a.md").click({ modifiers: ["Control"] });
|
||||
await row("c.md").click({ modifiers: ["Control"] });
|
||||
await drag("notes/a.md", "notes/nested");
|
||||
assert.equal((await calls("workspace_rename")).length, 0);
|
||||
await drag("notes/a.md", "target");
|
||||
await row("target/notes").waitFor();
|
||||
assert.deepEqual(await calls("workspace_rename"), [{ from: "notes", to: "target/notes" }, { from: "c.md", to: "target/c.md" }]);
|
||||
assert.deepEqual(await selected(), ["target/notes", "target/c.md"]);
|
||||
await row("target/notes").click();
|
||||
await row("target/notes/a.md").waitFor();
|
||||
console.log("PASS: mixed folder and file moves skip selected descendants and reject drops into the same folder");
|
||||
|
||||
await reset();
|
||||
await selectFiles();
|
||||
await drag("a.md", "c.md", "after");
|
||||
marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
|
||||
assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["c.md", "a.md", "b.md"]);
|
||||
await drag("b.md", "c.md", "before");
|
||||
marks = await page.evaluate(() => JSON.parse(window.__TEST__.files.get(".runestone/marks.json")));
|
||||
assert.deepEqual(marks.order[""].filter(name => name.endsWith(".md")), ["a.md", "b.md", "c.md"]);
|
||||
assert.deepEqual(errors, []);
|
||||
if (process.env.SCREENSHOT_PATH) {
|
||||
await row("a.md").click({ button: "right" });
|
||||
await page.screenshot({ path: process.env.SCREENSHOT_PATH });
|
||||
}
|
||||
console.log("PASS: group reorder preserves selected row order in both directions");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, writeFile } 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 context = await browser.newContext({ viewport: { width: 1280, height: 850 } });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\navigation-check';
|
||||
const folders = new Set(['Untitled', 'Parent', 'Empty']);
|
||||
const files = new Map([['note.md', '# Note'], ['Parent/existing.md', '# Existing']]);
|
||||
const state = { folders, files, calls: [] };
|
||||
window.__NAVIGATION_CHECK__ = state;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push({ command, args });
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'workspace_last_path') return state.noWorkspace ? null : root;
|
||||
if (command === 'workspace_open') return { root, name: 'navigation-check', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_write') { files.set(args.rel, args.contents); return; }
|
||||
if (command === 'workspace_list') {
|
||||
const prefix = args.rel ? args.rel + '/' : '';
|
||||
return [...[...folders].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'folder' })),
|
||||
...[...files.keys()].filter(path => path.startsWith(prefix) && !path.slice(prefix.length).includes('/') && !path.startsWith('.runestone/')).map(path => ({ name: path.slice(prefix.length), rel_path: path, kind: 'file' }))];
|
||||
}
|
||||
if (command === 'workspace_create') { if (folders.has(args.rel) || files.has(args.rel)) throw new Error('Destination exists'); if (args.kind === 'folder') folders.add(args.rel); else files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_rename') {
|
||||
if (folders.has(args.to) || files.has(args.to)) throw new Error('Destination exists');
|
||||
if (folders.delete(args.from)) folders.add(args.to);
|
||||
else { files.set(args.to, files.get(args.from)); files.delete(args.from); }
|
||||
return;
|
||||
}
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'workspace_recent' || command === 'workspace_search') return [];
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const output = '.audit/todo-navigation';
|
||||
await mkdir(output, { recursive: true });
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
const input = () => page.locator('.tree input');
|
||||
const folderAction = () => page.getByRole('menuitem', { name: 'New folder', exact: true });
|
||||
async function checkRename(name) {
|
||||
await input().waitFor();
|
||||
await page.waitForFunction(() => document.activeElement?.matches('.tree input'));
|
||||
const state = await input().evaluate(node => ({ name: node.value, start: node.selectionStart, end: node.selectionEnd }));
|
||||
assert.deepEqual(state, { name, start: 0, end: name.length });
|
||||
assert.equal(await page.getByRole('dialog').count(), 0, 'New folder uses inline rename');
|
||||
}
|
||||
async function setMode(mode) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
|
||||
await row('Untitled').waitFor();
|
||||
const welcome = page.locator('.welcome-actions');
|
||||
await welcome.waitFor();
|
||||
await welcome.getByRole('button', { name: 'Open browser', exact: true }).waitFor();
|
||||
assert.deepEqual(await welcome.locator('button').allTextContents().then(values => values.map(value => value.replace(/Ctrl [NOP]/g, '').trim())), ['New file', 'New note', 'Find file', 'Open folder', 'Open browser']);
|
||||
const firstRow = welcome.locator('.welcome-row').first();
|
||||
assert.equal(await firstRow.locator('button').count(), 3);
|
||||
const tops = await firstRow.locator('button').evaluateAll(nodes => nodes.map(node => node.getBoundingClientRect().top));
|
||||
assert.ok(tops.every(top => top === tops[0]), 'Wide layout has three actions in the first row');
|
||||
await welcome.getByRole('button', { name: /^New file/ }).focus();
|
||||
for (const name of ['New note', 'Find file', 'Open folder', 'Open browser']) {
|
||||
await page.keyboard.press('Tab');
|
||||
assert.ok((await page.evaluate(() => document.activeElement.textContent)).includes(name), `Tab reaches ${name} in order`);
|
||||
}
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await setMode(mode);
|
||||
await welcome.getByRole('button', { name: /^New file/ }).focus();
|
||||
await page.screenshot({ path: `${output}/splash-${mode}.png` });
|
||||
await page.setViewportSize({ width: 850, height: 650 });
|
||||
await page.screenshot({ path: `${output}/splash-${mode}-narrow.png` });
|
||||
assert.ok(await welcome.locator('button').evaluateAll(nodes => nodes.every(node => { const rect = node.getBoundingClientRect(); return rect.left >= 0 && rect.right <= innerWidth; })), 'Narrow splash controls fit');
|
||||
await page.setViewportSize({ width: 1280, height: 850 });
|
||||
}
|
||||
await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 80, y: 320 } });
|
||||
await folderAction().focus();
|
||||
await page.keyboard.press('Enter');
|
||||
await checkRename('untitled 2');
|
||||
await input().fill('Created folder');
|
||||
await input().press('Enter');
|
||||
await row('Created folder').waitFor();
|
||||
await row('Parent').click();
|
||||
await row('Parent').click();
|
||||
assert.equal(await row('Parent').getAttribute('aria-expanded'), 'false');
|
||||
await row('Parent').click({ button: 'right' });
|
||||
await folderAction().click();
|
||||
await checkRename('untitled');
|
||||
assert.equal(await row('Parent').getAttribute('aria-expanded'), 'true', 'Cached collapsed parent opens for rename');
|
||||
await input().press('Escape');
|
||||
await row('Parent/untitled').waitFor();
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await setMode(mode);
|
||||
await row('Parent').click({ button: 'right' });
|
||||
await folderAction().click();
|
||||
const expected = mode === 'dark' ? 'untitled 2' : 'untitled 3';
|
||||
await checkRename(expected);
|
||||
await page.screenshot({ path: `${output}/new-folder-${mode}.png` });
|
||||
await page.setViewportSize({ width: 850, height: 650 });
|
||||
await page.screenshot({ path: `${output}/new-folder-${mode}-narrow.png` });
|
||||
await input().press('Escape');
|
||||
await page.setViewportSize({ width: 1280, height: 850 });
|
||||
}
|
||||
await row('Empty').click({ button: 'right' });
|
||||
await folderAction().click();
|
||||
await checkRename('untitled');
|
||||
await input().fill('First folder');
|
||||
await input().press('Enter');
|
||||
await row('Empty/First folder').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__NAVIGATION_CHECK__.folders.has('Empty/First folder')), true);
|
||||
const emptyPage = await context.newPage();
|
||||
await emptyPage.addInitScript(() => { window.__NAVIGATION_CHECK__.noWorkspace = true; });
|
||||
await emptyPage.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5194');
|
||||
await emptyPage.locator('.welcome-actions').waitFor();
|
||||
await emptyPage.locator('.welcome-actions').getByRole('button', { name: 'Open browser', exact: true }).waitFor();
|
||||
assert.deepEqual(await emptyPage.locator('.welcome-actions button').allTextContents().then(values => values.map(value => value.replace(/Ctrl O/g, '').trim())), ['Open folder', 'Open browser']);
|
||||
await emptyPage.screenshot({ path: `${output}/splash-no-workspace.png` });
|
||||
await emptyPage.close();
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile(`${output}/checks.json`, JSON.stringify({ passed: true, checks: ['Case-insensitive root name collision', 'Selected inline name and no dialog', 'Enter saves rename', 'Escape retains created folder', 'Collapsed cached parent opens', 'Empty parent', 'Repeated unique names', 'Splash order and three-column maximum', 'Keyboard tab order', 'No workspace actions', 'Dark/light wide/narrow screenshots'], errors }, null, 2));
|
||||
console.log(`Navigation checks passed. Evidence: ${output}`);
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,142 @@
|
||||
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: 1280, height: 900 } });
|
||||
page.setDefaultTimeout(15000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\editor-files-smoke";
|
||||
const files = new Map([
|
||||
["note.md", "Mispelled text.\n\n| Word | Value |\n| --- | --- |\n| Speling | Other |\n"],
|
||||
["hello.txt", "print('hello')\n"],
|
||||
["notes/existing.md", "Existing note"],
|
||||
]);
|
||||
window.editorFilesTest = { files, calls: [] };
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
window.editorFilesTest.calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "editor-files-smoke", 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") { files.set(args.rel, args.contents); return; }
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length), 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("path already exists");
|
||||
files.set(args.rel, ""); return;
|
||||
}
|
||||
if (command === "workspace_rename") {
|
||||
if (files.has(args.to)) throw new Error("destination already exists");
|
||||
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
|
||||
}
|
||||
if (command === "workspace_search") return [];
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const row = name => page.locator(`[data-tree-rel="${name}"]`);
|
||||
async function enterName(name) {
|
||||
await page.locator("#text-request").fill(name);
|
||||
await page.getByRole("button", { name: "Continue", exact: true }).click();
|
||||
}
|
||||
async function modelDetails() {
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
return editor && { language: editor.getModel().getLanguageId(), value: editor.getValue(), fontSize: editor.getOption(monaco.editor.EditorOption.fontSize) };
|
||||
});
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await row("note.md").waitFor();
|
||||
await page.getByRole("button", { name: "New file", exact: true }).click();
|
||||
await enterName("LICENSE");
|
||||
await row("LICENSE").waitFor();
|
||||
await page.evaluate(() => window.editorFilesTest.files.set("LICENSE", "Keep this content"));
|
||||
await page.getByRole("button", { name: "New file", exact: true }).click();
|
||||
await enterName("LICENSE");
|
||||
await page.getByText("path already exists", { exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.editorFilesTest.files.get("LICENSE")), "Keep this content");
|
||||
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("LICENSE 2")), false);
|
||||
await row("notes").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "New file…", exact: true }).click();
|
||||
await enterName("hello_world.py");
|
||||
await row("notes/hello_world.py").waitFor();
|
||||
assert.equal(await page.evaluate(() => window.editorFilesTest.files.has("notes/hello_world.py.md")), false);
|
||||
await row("hello.txt").dblclick();
|
||||
await page.waitForFunction(() => !!document.querySelector(".monaco-editor .view-line"));
|
||||
await row("hello.txt").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
|
||||
assert.equal(await row("hello.txt").locator("input.rename").inputValue(), "hello.txt");
|
||||
await row("hello.txt").locator("input.rename").fill("hello.py");
|
||||
await page.keyboard.press("Enter");
|
||||
await row("hello.py").waitFor();
|
||||
await page.waitForFunction(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().some(editor => editor.getDomNode()?.isConnected && editor.getModel()?.getLanguageId() === "python");
|
||||
});
|
||||
const code = await modelDetails();
|
||||
assert.equal(code.value, "print('hello')\n");
|
||||
assert.equal(code.fontSize, 13);
|
||||
await page.keyboard.press("Control+e");
|
||||
assert.equal((await modelDetails()).fontSize, code.fontSize, "Code size stays the same in both layouts");
|
||||
await row("note.md").dblclick();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.writerTest = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
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);
|
||||
const nativeAllowed = await page.evaluate(() => {
|
||||
window.writerTest.dispatch({ selection: { anchor: 3 } });
|
||||
const line = document.querySelector(".cm-line"), rect = line.getBoundingClientRect();
|
||||
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: rect.left + 15, clientY: rect.top + 5 });
|
||||
line.dispatchEvent(event);
|
||||
return !event.defaultPrevented;
|
||||
});
|
||||
assert.equal(nativeAllowed, true, "The native spelling menu is available on plain text");
|
||||
assert.equal(await page.getByRole("menu").count(), 0);
|
||||
await page.evaluate(() => { window.writerTest.focus(); });
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.evaluate(() => window.writerTest.dispatch({ selection: { anchor: 0, head: 9 } }));
|
||||
await page.getByText("Mispelled text.", { exact: true }).click({ button: "right" });
|
||||
await page.getByRole("menu", { name: "Markdown text actions", exact: true }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".live-writer td").first().click({ button: "right" });
|
||||
await page.getByRole("menu", { name: "Table actions", exact: true }).waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".writer-cell-editor").click();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert.equal(await page.locator(".writer-cell-editor p").evaluate(node => {
|
||||
const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true });
|
||||
node.dispatchEvent(event);
|
||||
return !event.defaultPrevented;
|
||||
}), true, "Active table text permits the native spelling menu");
|
||||
await page.locator(".cm-line").first().click();
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: exact filenames, extensionless creation, extension rename and language, equal code font sizes, native spelling event, shared selection and table menus in both themes");
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,132 @@
|
||||
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("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\tree-actions-test";
|
||||
const files = new Map([
|
||||
["notes/a.md", "# A"], ["notes/nested/b.md", "# B"],
|
||||
["target/a.md", "# Existing"], ["a.md", "# A"], ["b.md", "# B"], ["c.md", "# C"],
|
||||
]);
|
||||
const calls = [];
|
||||
const state = { files, calls, answer: "Ok", fail: "", clipboard: "" };
|
||||
Object.defineProperty(navigator, "clipboard", { value: { writeText: async text => { state.clipboard = text; } } });
|
||||
let sequence = 0;
|
||||
const contains = (parent, path) => path === parent || path.startsWith(parent + "/");
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => ++sequence,
|
||||
unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") return ++sequence;
|
||||
if (command === "plugin:event|unlisten") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "tree-actions-test", 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") { files.set(args.rel, args.contents); 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_delete") {
|
||||
if (args.rel === state.fail) throw new Error("Access denied");
|
||||
for (const path of [...files.keys()]) if (contains(args.rel, path)) files.delete(path);
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_copy") {
|
||||
const to = args.rel + "-copy";
|
||||
for (const [path, text] of [...files]) if (contains(args.rel, path)) files.set(to + path.slice(args.rel.length), text);
|
||||
return { name: to.split("/").pop(), rel_path: to, kind: files.has(to) ? "file" : "folder" };
|
||||
}
|
||||
if (command === "workspace_rename") {
|
||||
if ([...files.keys()].some(path => contains(args.to, path))) throw new Error("Destination exists");
|
||||
for (const [path, text] of [...files]) if (contains(args.from, path)) {
|
||||
files.delete(path);
|
||||
files.set(args.to + path.slice(args.from.length), text);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_abs_path") return root + "\\" + args.rel.replaceAll("/", "\\");
|
||||
if (command === "workspace_reveal") return;
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "plugin:dialog|message") return state.answer;
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
window.__TEST__ = state;
|
||||
});
|
||||
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
|
||||
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(nodes => nodes.map(node => node.dataset.treeRel));
|
||||
const calls = command => page.evaluate(command => window.__TEST__.calls.filter(call => call.command === command).map(call => call.args), command);
|
||||
const settle = () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
async function reset() {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await row("notes").waitFor();
|
||||
}
|
||||
async function action(path, name) {
|
||||
await row(path).click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name, exact: true }).click();
|
||||
await settle();
|
||||
}
|
||||
async function selectFiles() {
|
||||
await row("a.md").click();
|
||||
await page.getByRole("tab", { name: "a.md", exact: true }).waitFor();
|
||||
await settle();
|
||||
await row("b.md").click({ modifiers: ["Control"] });
|
||||
await settle();
|
||||
}
|
||||
async function drag(sourcePath, targetPath, place = "inside") {
|
||||
const source = await row(sourcePath).boundingBox();
|
||||
const target = await row(targetPath).boundingBox();
|
||||
await page.mouse.move(source.x + source.width / 2, source.y + source.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(target.x + target.width / 2, target.y + target.height * (place === "before" ? 0.1 : place === "after" ? 0.9 : 0.5), { steps: 10 });
|
||||
await page.mouse.up();
|
||||
await settle();
|
||||
}
|
||||
try {
|
||||
await reset();
|
||||
for (const [theme, width] of [['dark',1440],['light',620]]) {
|
||||
await page.setViewportSize({width,height:850});
|
||||
await page.evaluate(theme => { document.documentElement.dataset.theme = theme; document.documentElement.dataset.palette = 'default'; },theme);
|
||||
await row('a.md').click();
|
||||
await row('a.md').focus();
|
||||
await page.keyboard.press('F2');
|
||||
const input=row('a.md').locator('input');
|
||||
await input.waitFor();
|
||||
assert.deepEqual(await input.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
|
||||
await page.screenshot({path:'.audit/rename-selection-'+theme+'.png'});
|
||||
await input.press('Escape');
|
||||
await row('notes').click();
|
||||
await row('notes').focus();
|
||||
await page.keyboard.press('F2');
|
||||
const folder=row('notes').locator('input');
|
||||
await folder.waitFor();
|
||||
assert.deepEqual(await folder.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,5,'notes']);
|
||||
await folder.press('Escape');
|
||||
await page.getByRole('tab',{name:'a.md',exact:true}).click();
|
||||
await page.getByRole('tab',{name:'a.md',exact:true}).click({button:'right'});
|
||||
await page.getByRole('menuitem',{name:'Rename…',exact:true}).click();
|
||||
const dialogInput=page.locator('#text-request');
|
||||
await dialogInput.waitFor();
|
||||
assert.deepEqual(await dialogInput.evaluate(node=>[node.selectionStart,node.selectionEnd,node.value]),[0,1,'a.md']);
|
||||
await dialogInput.press('Escape');
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('Rename selection passed: file, folder, editor dialog, dark/wide and light/narrow.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,158 @@
|
||||
// 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 "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
async function 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("button", { name: "Rename note", exact: true }).waitFor();
|
||||
}
|
||||
const title = page.getByRole("button", { name: "Rename note", exact: true });
|
||||
const input = page.getByRole("textbox", { name: "Note filename", exact: true });
|
||||
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
|
||||
async function editTitle(value) { await title.click(); await input.fill(value); }
|
||||
const renamed = name => page.waitForFunction(expected => document.querySelector(".breadcrumb")?.textContent === expected, name);
|
||||
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await openNote("welcome.md");
|
||||
const original = await page.evaluate(() => window.__TEST__.files.get("notes/welcome.md"));
|
||||
await writer.click();
|
||||
await page.keyboard.press("Control+End");
|
||||
await page.keyboard.type("Unsaved text");
|
||||
await editTitle("Release 1.2");
|
||||
await input.press("Enter");
|
||||
await renamed("notes/Release 1.2.md");
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.has("notes/welcome.md")), false);
|
||||
await page.getByRole("tab", { name: /Release 1\.2\.md/ }).waitFor();
|
||||
await page.locator('.tree').getByText("notes", { exact: true }).click();
|
||||
await page.locator('.tree').getByText("Release 1.2", { exact: true }).waitFor();
|
||||
await writer.click();
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original);
|
||||
await page.keyboard.press("Control+y");
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(text => window.__TEST__.files.get("notes/Release 1.2.md") === text, original + "Unsaved text");
|
||||
|
||||
await editTitle("Cancelled");
|
||||
await input.press("Escape");
|
||||
await renamed("notes/Release 1.2.md");
|
||||
assert.equal(await input.isVisible(), false);
|
||||
// Keyboard activation and filename errors stay outside Markdown editing.
|
||||
await title.focus(); await title.press("Enter");
|
||||
await input.fill(" "); await input.press("Enter");
|
||||
await page.getByRole("alert").filter({ hasText: "Name is empty" }).waitFor();
|
||||
await input.fill("folder/note"); await input.press("Enter");
|
||||
await page.getByRole("alert").filter({ hasText: "path separator" }).waitFor();
|
||||
await input.fill("second"); await input.press("Enter");
|
||||
await page.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
|
||||
assert.equal(await input.inputValue(), "second");
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.files.get("notes/second.md")), "# Second note\n");
|
||||
await input.fill("Renamed.md"); await input.press("Tab");
|
||||
await renamed("notes/Renamed.md");
|
||||
await page.mouse.move(10, 10);
|
||||
await page.screenshot({ path: ".audit/rename-title.png" });
|
||||
|
||||
// A pending rename belongs to its original document even if the tab changes.
|
||||
await page.evaluate(() => { window.__TEST__.delayRename = true; });
|
||||
await editTitle("Background"); await input.press("Enter");
|
||||
await page.waitForFunction(() => !!window.__TEST__.resumeRename);
|
||||
await page.locator('.tree').getByText("second", { exact: true }).click();
|
||||
await renamed("notes/second.md");
|
||||
await page.evaluate(() => { window.__TEST__.resumeRename(); window.__TEST__.delayRename = false; });
|
||||
await page.getByRole("tab", { name: "Background.md", exact: true }).waitFor();
|
||||
await renamed("notes/second.md");
|
||||
await page.getByRole("tab", { name: "Background.md", exact: true }).click();
|
||||
await renamed("notes/Background.md");
|
||||
// Disk reload after rename must not restore the old displayed title.
|
||||
await page.evaluate(() => {
|
||||
window.__TEST__.files.set("notes/Background.md", "Reloaded\n");
|
||||
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "modify", paths: ["notes/Background.md"] });
|
||||
});
|
||||
await page.waitForFunction(() => document.querySelector(".cm-line")?.textContent === "Reloaded");
|
||||
assert.ok((await title.innerText()).startsWith("Background"));
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: inline filename rename, folder/extension preservation, tabs/tree, contents and undo, Enter/blur/Escape, validation/collisions, tab switching during rename, and reload (mocked desktop IPC).");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
console.error("Visible text:", (await page.locator("body").innerText()).slice(0, 3000));
|
||||
await page.screenshot({ path: ".audit/rename-title-failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,182 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, readFile } 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 context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
const gitRoot = new URL('../../../../RuneStone_Git/dist/', import.meta.url);
|
||||
const git = {
|
||||
manifest: JSON.parse(await readFile(new URL('plugin.json', gitRoot), 'utf8')),
|
||||
code: await readFile(new URL('main.js', gitRoot), 'utf8'),
|
||||
css: (await readFile(new URL('style.css', gitRoot))).toString('base64'),
|
||||
};
|
||||
await context.addInitScript(git => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\host-todo-test';
|
||||
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['folder/nested/note.md', '# Nested'], ['other/keep.md', '# Keep'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
|
||||
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
|
||||
window.__HOST_TEST__ = state;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push({ command, args });
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] };
|
||||
if (command === 'plugins_load') return git.code;
|
||||
if (command === 'plugins_asset') return git.css;
|
||||
if (command === 'plugins_data') return 'null';
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_list') {
|
||||
const prefix = args.rel ? args.rel + '/' : '';
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
|
||||
const tail = path.slice(prefix.length), 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('Destination exists'); files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_write') {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === 'workspace_rename') {
|
||||
if (files.has(args.to)) throw new Error('Destination exists');
|
||||
if (![...files.keys()].some(path => path === args.from || path.startsWith(args.from + '/'))) throw new Error('Missing file');
|
||||
for (const [path, contents] of [...files]) { if (path === args.from || path.startsWith(args.from + '/')) { files.set(args.to + path.slice(args.from.length), contents); files.delete(path); } } return;
|
||||
}
|
||||
if (command === 'workspace_delete') { files.delete(args.rel); return; }
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:dialog|message') return 'Ok';
|
||||
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, git);
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5186';
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
const item = name => page.getByRole('menuitem', { name, exact: true });
|
||||
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
|
||||
async function rename(path, name) {
|
||||
await row(path).click({ button: 'right' }); await item('Rename').click();
|
||||
await page.locator('.tree input').fill(name); await page.locator('.tree input').press('Enter');
|
||||
}
|
||||
async function expanded(path) { assert.equal(await row(path).getAttribute('aria-expanded'), 'true', `${path} stays expanded`); }
|
||||
await mkdir('output/host-navigation-pass3', { recursive: true });
|
||||
try {
|
||||
await page.goto(origin);
|
||||
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
|
||||
await rename('folder/nested/note.md', 'renamed.md'); await row('folder/nested/renamed.md').waitFor();
|
||||
await row('folder/nested/renamed.md').focus(); await page.keyboard.press('Control+z');
|
||||
await row('folder/nested/note.md').waitFor();
|
||||
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
|
||||
await page.keyboard.press('Control+y'); await row('folder/nested/renamed.md').waitFor();
|
||||
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
|
||||
await rename('folder', 'renamed-folder'); await row('renamed-folder/nested/renamed.md').waitFor();
|
||||
await row('renamed-folder').focus(); await page.keyboard.press('Control+z');
|
||||
await row('folder/nested/renamed.md').waitFor();
|
||||
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
|
||||
await page.keyboard.press('Control+y'); await row('renamed-folder/nested/renamed.md').waitFor();
|
||||
for (const path of ['renamed-folder', 'renamed-folder/nested', 'other']) await expanded(path);
|
||||
await paneMenu(); assert.equal(await item('Manage templates…').isVisible(), false);
|
||||
await item('New note').click(); await row('untitled.md').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('untitled.md')), '');
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
await item('Daily').click(); await row('Daily.md').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
await page.screenshot({ path: `output/host-navigation-pass3/note-menu-${mode}.png` });
|
||||
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
|
||||
}
|
||||
await page.setViewportSize({ width: 600, height: 600 });
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
await page.screenshot({ path: 'output/host-navigation-pass3/note-menu-dark-narrow.png' });
|
||||
assert.ok(await item('Manage templates…').evaluate(node => node.getBoundingClientRect().right <= innerWidth));
|
||||
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({ width: 1200, height: 850 });
|
||||
await page.evaluate(() => { window.__HOST_TEST__.files.delete('.runestone/templates/Daily.md'); window.dispatchEvent(new Event('runestone-templates-changed')); });
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
assert.equal(await item('Daily').count(), 0);
|
||||
await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
const creations = await page.evaluate(() => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length);
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('Enter');
|
||||
await page.waitForFunction(count => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
|
||||
await page.getByRole('button', { name: 'Source control', exact: true }).waitFor();
|
||||
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
const graph = page.getByRole('menuitem', { name: /Show Git graph/ });
|
||||
await graph.waitFor();
|
||||
assert.equal(await page.getByRole('menuitem', { name: /source control/i }).count(), 0);
|
||||
const graphIcon = await graph.locator('.action-icon').innerHTML();
|
||||
const expectedIcon = await page.evaluate(async () => (await import('/src/lib/ui/actionIcons.ts')).actionIcon('git').innerHTML);
|
||||
assert.equal(graphIcon, expectedIcon, 'The real Git graph command uses the shared Git icon');
|
||||
await page.screenshot({ path: 'output/host-navigation-pass3/real-git-command-dark.png' });
|
||||
await page.keyboard.press('Escape');
|
||||
await page.evaluate(async () => {
|
||||
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
external.pluginNavigation.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', icon: 'kanban', placement: 'editor', toolbar: true }, { owner: 'git-test', id: 'source', title: 'Source control', icon: 'git', placement: 'sidebar', toolbar: true }]);
|
||||
external.pluginTools.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', kind: 'view', surface: 'open' }, { owner: 'git-test', id: 'graph', title: 'Graph view', kind: 'command', surface: 'open', icon: 'git' }]);
|
||||
external.pluginTools.update(items => [...items, { owner: 'runestone.browser', id: 'new-tab', title: 'New browser tab', kind: 'command', surface: 'open' }]);
|
||||
const registry = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/registry.ts').name);
|
||||
registry.pluginHost.get('browser').newTab = async () => { window.__HOST_TEST__.browserOpened = true; };
|
||||
});
|
||||
await page.locator('.header-right').getByRole('button', { name: 'New browser tab', exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.browserOpened), true);
|
||||
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Project Management', exact: true }).count(), 0);
|
||||
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
|
||||
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Source control', exact: true }).count(), 0);
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
assert.equal(await page.getByRole('menuitem', { name: /Project Management/ }).count(), 1);
|
||||
assert.equal(await page.getByRole('menuitem', { name: /New browser tab/ }).count(), 0);
|
||||
await page.getByRole('menuitem', { name: /Graph view/ }).waitFor(); await page.keyboard.press('Escape');
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
await page.screenshot({ path: `output/host-navigation-pass3/plugin-navigation-${mode}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
const token = '00000000-0000-4000-8000-000000000001';
|
||||
const saved = await page.evaluate(token => {
|
||||
const layout = JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 280, rightWidth: 260, leftView: 'files' });
|
||||
localStorage.setItem('runestone.workbenchLayout', layout);
|
||||
localStorage.setItem(`runestone.tab-transfer.${token}`, JSON.stringify({ root: 'C:\\host-todo-test', created: Date.now(), buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }));
|
||||
return layout;
|
||||
}, token);
|
||||
const detached = await context.newPage();
|
||||
detached.on('pageerror', error => errors.push(error.message));
|
||||
await detached.goto(`${origin}/?tabTransfer=${token}`);
|
||||
await detached.getByRole('tab', { name: /a.md/ }).waitFor();
|
||||
await detached.getByText('# Transferred', { exact: true }).waitFor();
|
||||
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
|
||||
assert.equal(await detached.getByRole('button', { name: 'Show outline', exact: true }).count(), 0);
|
||||
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
|
||||
assert.equal(await detached.getByRole('button', { name: 'Files', exact: true }).count(), 0);
|
||||
await detached.keyboard.press('Control+b');
|
||||
await detached.keyboard.press('Control+Shift+f');
|
||||
assert.equal(await detached.locator('aside.left,aside.right,.plugin-ribbon,.gutter-v').count(), 0);
|
||||
await detached.keyboard.press('Escape');
|
||||
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await detached.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await detached.setViewportSize({ width: 650, height: 600 });
|
||||
await detached.screenshot({ path: `output/host-navigation-pass3/detached-${mode}-narrow.png` });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Host navigation passed: nested file/folder rename undo/redo, expanded folders, blank New note parent, template submenu, plugin navigation dedup, detached layout isolation.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,123 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
const row = rel => page.locator(`[data-tree-rel="${rel}"]`);
|
||||
const selected = () => page.locator('[role="treeitem"][aria-selected="true"]').evaluateAll(rows => rows.map(row => row.dataset.treeRel));
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await row('notes').waitFor();
|
||||
await row('notes').click();
|
||||
await row('notes/second.md').waitFor();
|
||||
assert.deepEqual(await selected(), ['notes']);
|
||||
await row('notes/second.md').click({ modifiers: ['Control'] });
|
||||
await row('src').click({ modifiers: ['Control'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'src']);
|
||||
assert.equal(await row('src').getAttribute('aria-expanded'), 'false');
|
||||
assert.equal(await page.getByRole('tab').count(), 1);
|
||||
assert.equal(await page.getByRole('tab', { name: 'New tab', exact: true }).count(), 1);
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
assert.deepEqual(await selected(), ['notes/second.md', 'src']);
|
||||
assert.equal(await row('notes').getAttribute('aria-expanded'), 'true');
|
||||
await row('notes/second.md').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md']);
|
||||
await row('src').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md', 'src']);
|
||||
await page.keyboard.press('F2');
|
||||
assert.equal(await page.locator('.tree .rename').count(), 0);
|
||||
await row('notes/welcome.md').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'notes/second.md', 'notes/welcome.md']);
|
||||
await row('notes/second.md').click();
|
||||
assert.deepEqual(await selected(), ['notes/second.md']);
|
||||
await page.getByRole('tab', { name: /second/ }).waitFor();
|
||||
await row('notes/second.md').click({ modifiers: ['Control'] });
|
||||
assert.deepEqual(await selected(), []);
|
||||
await row('src').click({ modifiers: ['Control'] });
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
await page.keyboard.press('F2');
|
||||
assert.equal(await page.locator('.tree .rename').inputValue(), 'src');
|
||||
await page.keyboard.press('Escape');
|
||||
await row('notes/second.md').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes/second.md', 'notes/welcome.md', 'src']);
|
||||
const colors = await page.locator('.tree .row.selected').evaluateAll(rows => rows.map(row => getComputedStyle(row).backgroundColor));
|
||||
assert.equal(new Set(colors).size, 1);
|
||||
await page.screenshot({ path: '.audit/tree-selection.png' });
|
||||
await page.getByRole('button', { name: 'Collapse all', exact: true }).click();
|
||||
assert.deepEqual(await selected(), ['src']);
|
||||
await row('notes').click({ modifiers: ['Shift'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'src']);
|
||||
await row('notes').click({ modifiers: ['Control'] });
|
||||
await row('notes').click({ modifiers: ['Shift', 'Control'] });
|
||||
assert.deepEqual(await selected(), ['notes', 'src']);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Tree selection browser checks passed.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,145 @@
|
||||
// Run against pnpm dev; use PLAYWRIGHT_MODULE for a shared Playwright 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: 1100, height: 800 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", err => errors.push(err.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
let current = "D:\\Notes";
|
||||
let recent = ["D:\\Writing\\Notes", current, "D:\\Missing"];
|
||||
let picked = null;
|
||||
let contents = "Original note";
|
||||
const calls = [];
|
||||
const windows = [];
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: () => 1, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "workspace_last_path") return current;
|
||||
if (command === "workspace_recent") return recent;
|
||||
if (command === "workspace_forget") { recent = recent.filter(path => path !== args.path); return recent; }
|
||||
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }];
|
||||
if (command === "workspace_read") { if (args.rel === "note.txt") return contents; throw "File not found"; }
|
||||
if (command === "workspace_write") { contents = args.contents; return; }
|
||||
if (command === "pty_profiles") return [{ id: "powershell", title: "PowerShell", kind: "powershell" }];
|
||||
if (command === "plugin:dialog|open") return picked;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
if (command === "workspace_new") {
|
||||
if (args.name === "Existing") throw "A file or folder with that name already exists.";
|
||||
const root = args.parent + "\\" + args.name;
|
||||
recent = [root, ...recent]; windows.push(root);
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_open_window") {
|
||||
if (args.path.endsWith("Missing")) throw "folder does not exist";
|
||||
windows.push(args.path);
|
||||
recent = [args.path, ...recent.filter(p => p !== args.path)];
|
||||
return;
|
||||
}
|
||||
if (command === "workspace_open") {
|
||||
if (args.path.endsWith("Missing")) throw "folder does not exist";
|
||||
current = args.path; recent = [current, ...recent.filter(p => p !== current)];
|
||||
return { root: current, name: current.split("\\").pop(), watch_mode: "native" };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
window.__TEST__ = { calls, windows, pick: path => picked = path, clear: () => recent = [], reorder: () => recent = ["D:\\Writing\\Notes", current, "D:\\Missing"] };
|
||||
});
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.locator(".ws").filter({ hasText: "Notes" }).waitFor();
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("note.txt");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "note.txt" }).first().click();
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
window.__MONACO__ = (await import("/src/lib/editor/monacoEnv.ts")).monaco;
|
||||
window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected).setValue("My pending edit");
|
||||
});
|
||||
const trigger = page.getByRole("button", { name: "Open folder", exact: true });
|
||||
const menu = page.getByRole("dialog", { name: "Workspaces", exact: true });
|
||||
await page.evaluate(() => window.__TEST__.reorder());
|
||||
await trigger.click();
|
||||
await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor();
|
||||
await page.mouse.move(1000, 50);
|
||||
assert.equal(await menu.locator('.workspace-row').first().evaluate(node => node === document.activeElement), false, "Pointer opening does not force focus onto a different workspace");
|
||||
assert.equal(await menu.locator('.workspace-row').first().evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)", "The first workspace has no stuck highlight");
|
||||
assert.equal(await menu.locator('[aria-current="true"]').count(), 1);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0);
|
||||
await page.screenshot({ path: ".audit/workspaces-menu.png" });
|
||||
const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length);
|
||||
await menu.getByRole("button").filter({ hasText: "Current" }).click();
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
|
||||
await page.keyboard.press("Control+o");
|
||||
await menu.getByRole("button").filter({ hasText: "Missing" }).click();
|
||||
await menu.getByRole("alert").filter({ hasText: "folder does not exist" }).waitFor();
|
||||
await menu.getByRole("button", { name: "Open another folder…" }).click();
|
||||
assert(await menu.isVisible(), "Cancelling folder picker keeps history available");
|
||||
await menu.getByRole("button").filter({ hasText: "D:\\Writing\\Notes" }).click();
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
assert.equal(await page.locator(".ws").textContent(), "Notes");
|
||||
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes"]);
|
||||
await trigger.click();
|
||||
await page.evaluate(() => window.__TEST__.pick("D:\\Other"));
|
||||
await menu.getByRole("button", { name: "Open another folder…" }).click();
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
assert.equal(await page.locator(".ws").textContent(), "Notes");
|
||||
await trigger.click();
|
||||
await menu.getByRole("button", { name: "New workspace…" }).click();
|
||||
const dialog = page.getByRole("dialog", { name: "New workspace", exact: true });
|
||||
assert(await dialog.getByRole("button", { name: "Create workspace", exact: true }).isDisabled());
|
||||
await dialog.getByLabel("Workspace name").fill("Existing");
|
||||
await page.evaluate(() => window.__TEST__.pick("D:\\Projects"));
|
||||
await dialog.getByRole("button", { name: "Browse…" }).click();
|
||||
await dialog.getByRole("button", { name: "Create workspace", exact: true }).click();
|
||||
await dialog.getByRole("alert").filter({ hasText: "already exists" }).waitFor();
|
||||
await dialog.getByLabel("Workspace name").fill("Fresh notes");
|
||||
await page.screenshot({ path: ".audit/workspaces-create.png" });
|
||||
await dialog.getByRole("button", { name: "Create workspace", exact: true }).click();
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
assert.equal(await page.locator(".ws").textContent(), "Notes");
|
||||
assert.deepEqual(await page.evaluate(() => window.__TEST__.windows), ["D:\\Writing\\Notes", "D:\\Other", "D:\\Projects\\Fresh notes"]);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length), opened);
|
||||
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|message").length), 0);
|
||||
assert.equal(await page.evaluate(() => window.__MONACO__.editor.getEditors().find(e => e.getDomNode()?.isConnected)?.getValue()), "My pending edit");
|
||||
assert(await page.getByRole("tab", { name: /note\.txt/ }).isVisible());
|
||||
await trigger.click();
|
||||
await page.keyboard.press("End");
|
||||
assert.equal(await page.locator(":focus").textContent(), " Open another folder…");
|
||||
await page.keyboard.press("Escape");
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
for (const theme of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => {
|
||||
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
|
||||
applyAppearance({ theme: 'default', mode });
|
||||
}, theme);
|
||||
await page.setViewportSize({ width: theme === 'light' ? 1100 : 380, height: 800 });
|
||||
await trigger.click();
|
||||
await menu.getByRole('button', { name: 'Remove D:\\Missing from recent workspaces', exact: true }).focus();
|
||||
await page.screenshot({ path: `.audit/workspaces-remove-${theme}.png` });
|
||||
if (theme === 'dark') {
|
||||
await page.keyboard.press('Enter');
|
||||
await menu.getByText('D:\\Missing', { exact: true }).waitFor({ state: 'detached' });
|
||||
assert.equal(await page.locator('.ws').textContent(), 'Notes', 'History removal does not close the current workspace');
|
||||
await page.keyboard.press('Escape');
|
||||
await trigger.click();
|
||||
assert.equal(await menu.getByText('D:\\Missing', { exact: true }).count(), 0, 'Removed paths stay absent after reopening');
|
||||
}
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
await page.setViewportSize({ width: 1100, height: 800 });
|
||||
await page.evaluate(() => window.__TEST__.clear());
|
||||
await trigger.click();
|
||||
await menu.getByText("No recent workspaces yet.").waitFor();
|
||||
await page.getByRole("button", { name: "New tab (Ctrl T)", exact: true }).click();
|
||||
await menu.waitFor({ state: "hidden" });
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("Workspace smoke passed: history, opening and creating in new windows, original workspace preserved, cancellation, errors, keyboard and empty state.");
|
||||
} finally { await browser.close(); }
|
||||
Reference in New Issue
Block a user