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:
@@ -1,206 +0,0 @@
|
||||
// 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(); }
|
||||
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { parseCustomTheme } from '../src/lib/theme/customThemes.ts';
|
||||
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../src/lib/theme/characterThemes.ts';
|
||||
import { parseAppearance, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, THEMES, themeModes } from '../src/lib/theme/appearance.ts';
|
||||
|
||||
test('Removed palettes preserve the saved mode with the default palette', () => {
|
||||
for (const theme of ['gpt', 'terminal', 'unknown', 'renamon', 'asuka-school']) {
|
||||
for (const mode of ['light', 'dark'] as const) {
|
||||
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme: 'default', mode });
|
||||
}
|
||||
}
|
||||
assert.deepEqual(THEMES, ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent']);
|
||||
assert.deepEqual(BUILTIN_THEMES.map(theme => theme.id), THEMES);
|
||||
});
|
||||
|
||||
test('Renamed palettes preserve saved choices and backgrounds', () => {
|
||||
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
|
||||
for (const [previous, theme] of [['holo', 'harvest-moon'], ['asuka', 'crimson-pilot'], ['malfoid', 'silver-serpent']]) {
|
||||
for (const mode of ['light', 'dark']) {
|
||||
assert.deepEqual(parseAppearance(JSON.stringify({ theme: previous, mode, newTabBackground })), { theme, mode: 'dark', newTabBackground });
|
||||
}
|
||||
}
|
||||
for (const theme of ['constructor', '__proto__', 'toString']) {
|
||||
assert.deepEqual(normalizeAppearance({ theme, mode: 'light' }), { theme: 'default', mode: 'light' });
|
||||
}
|
||||
});
|
||||
|
||||
test('Removed character themes retain the saved background', () => {
|
||||
const newTabBackground = { imageId: '01234567-89ab-cdef-0123-456789abcdef', position: 'top left', size: 'auto', overlay: -0.4 };
|
||||
for (const theme of ['renamon', 'asuka-school']) {
|
||||
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode: 'light', newTabBackground })), { theme: 'default', mode: 'light', newTabBackground });
|
||||
}
|
||||
});
|
||||
|
||||
function luminance(color: string) {
|
||||
const rgb = color.slice(1).match(/../g)!.map(value => parseInt(value, 16) / 255)
|
||||
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4);
|
||||
return rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722;
|
||||
}
|
||||
function contrast(foreground: string, background: string) {
|
||||
const values = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
|
||||
return (values[0] + 0.05) / (values[1] + 0.05);
|
||||
}
|
||||
test('Character palettes restore one appearance and export readable surfaces and syntax', () => {
|
||||
for (const theme of Object.keys(CHARACTER_THEMES) as (keyof typeof CHARACTER_THEMES)[]) {
|
||||
const exported = exportAppearanceTheme(theme);
|
||||
for (const mode of ['light', 'dark'] as const) {
|
||||
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode });
|
||||
const colors = exported.colors;
|
||||
for (const foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) {
|
||||
for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) {
|
||||
if (foreground === 'accent' && background === 'selection') continue;
|
||||
assert(contrast(colors[foreground]!, colors[background]!) >= 4.5, `${theme} ${mode}: ${foreground} on ${background}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.deepEqual(themeModes(theme), [CHARACTER_THEMES[theme].mode]);
|
||||
assert.equal(exported.schema, 2);
|
||||
assert.deepEqual(parseCustomTheme(exported), exported);
|
||||
for (const role of SYNTAX_ROLES) {
|
||||
for (const background of ['bg', 'bg-active'] as const) {
|
||||
assert(contrast(exported.colors[`syntax-${role}`]!, exported.colors[background]!) >= 4.5, `${theme}: ${role} on ${background}`);
|
||||
}
|
||||
}
|
||||
assert(new Set(SYNTAX_ROLES.map(role => exported.colors[`syntax-${role}`])).size >= 7);
|
||||
assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors);
|
||||
}
|
||||
});
|
||||
test('Sakura cannot restore or save a dark appearance', () => {
|
||||
assert.deepEqual(parseAppearance('{"theme":"sakura","mode":"dark"}'), { theme: 'sakura', mode: 'light' });
|
||||
assert.deepEqual(normalizeAppearance({ theme: 'sakura', mode: 'dark' }), { theme: 'sakura', mode: 'light' });
|
||||
});
|
||||
test('Malformed storage returns a valid default appearance', () => {
|
||||
for (const raw of [null, '', '{', 'null', '42', '[]']) {
|
||||
assert.deepEqual(parseAppearance(raw), { theme: 'default', mode: 'dark' });
|
||||
}
|
||||
});
|
||||
|
||||
test('Saved image layout restores valid choices and rejects CSS injection', () => {
|
||||
const imageId = '01234567-89ab-cdef-0123-456789abcdef';
|
||||
const restored = parseAppearance(JSON.stringify({ newTabBackground: { imageId, position: 'top left', size: 'auto', overlay: -0.4 } }));
|
||||
assert.deepEqual(restored.newTabBackground, { imageId, position: 'top left', size: 'auto', overlay: -0.4 });
|
||||
const invalid = normalizeAppearance({ newTabBackground: { imageId, position: 'url(https://example.com)', size: '100000px', overlay: Infinity } });
|
||||
assert.deepEqual(invalid.newTabBackground, { imageId, position: 'center', size: 'cover', overlay: 0 });
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId } }).newTabBackground, { imageId, overlay: 0, position: 'center', size: 'cover' });
|
||||
});
|
||||
|
||||
test('New tab backgrounds keep supported image data and reject active or remote content', () => {
|
||||
const value = { theme: 'claude', mode: 'light', newTabBackground: { image: 'data:image/png;base64,YQ==', overlay: 0, position: 'center', size: 'cover' } };
|
||||
assert.deepEqual(parseAppearance(JSON.stringify(value)), value);
|
||||
for (const image of ['https://example.com/photo.png', 'javascript:alert(1)', 'data:image/svg+xml;base64,YQ==', 'data:image/png;base64,' + 'A'.repeat(3_000_000)]) {
|
||||
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: '#224466', image } }).newTabBackground, undefined);
|
||||
}
|
||||
assert.equal(normalizeAppearance({ ...value, newTabBackground: { color: 'red' } }).newTabBackground, undefined);
|
||||
assert.equal(normalizeAppearance({ ...value, newTabBackground: undefined }).newTabBackground, undefined);
|
||||
});
|
||||
|
||||
test('Background image references clamp the overlay and discard obsolete colors', () => {
|
||||
const imageId = 'd10adda6-a2ec-4d73-a0a6-2cb1ed43bebc';
|
||||
const layout = { position: 'center', size: 'cover' };
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, color: '#224466', overlay: 3 } }).newTabBackground, { imageId, overlay: 1, ...layout });
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: -3 } }).newTabBackground, { imageId, overlay: -1, ...layout });
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: NaN } }).newTabBackground, { imageId, overlay: 0, ...layout });
|
||||
assert.equal(normalizeAppearance({ newTabBackground: { imageId: 'invalid' } }).newTabBackground, undefined);
|
||||
});
|
||||
@@ -1,125 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,154 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,44 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { characterTheme, SYNTAX_ROLES } from '../src/lib/theme/characterThemes.ts';
|
||||
|
||||
const rgb = (color: string) => color.slice(1).match(/../g)!.map(value => parseInt(value, 16));
|
||||
const mix = (foreground: string, background: string, opacity: number) => '#' + rgb(foreground)
|
||||
.map((value, index) => Math.round(value * opacity + rgb(background)[index] * (1 - opacity)).toString(16).padStart(2, '0')).join('');
|
||||
function luminance(color: string) {
|
||||
return rgb(color).map(value => value / 255)
|
||||
.map(value => value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4)
|
||||
.reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);
|
||||
}
|
||||
function contrast(foreground: string, background: string) {
|
||||
const [high, low] = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
|
||||
return (high + 0.05) / (low + 0.05);
|
||||
}
|
||||
|
||||
test('Crimson Pilot text and syntax remain readable in active and selected states', () => {
|
||||
const palette = characterTheme('crimson-pilot')!;
|
||||
const [background, elevated, active, , dim, text, strong, accent, selection] = palette.surfaces;
|
||||
const foregrounds = { dim, text, strong, accent, secondary: palette.secondary,
|
||||
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])) };
|
||||
for (const [role, foreground] of Object.entries(foregrounds)) {
|
||||
for (const surface of [background, elevated, active, selection]) {
|
||||
assert(contrast(foreground, surface) >= 4.5, `${role} on ${surface} needs 4.5:1 contrast`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Crimson Pilot text remains readable on image-tinted editor and panel surfaces', () => {
|
||||
const palette = characterTheme('crimson-pilot')!;
|
||||
const [background, elevated, , , dim, text, strong] = palette.surfaces;
|
||||
const editor = mix(background, '#ffffff', 0.9);
|
||||
const codeBlock = mix(elevated, editor, 0.82);
|
||||
const panel = mix(elevated, '#ffffff', 0.82);
|
||||
for (const foreground of palette.syntax) {
|
||||
for (const surface of [editor, codeBlock]) {
|
||||
assert(contrast(foreground, surface) >= 4.5, `${foreground} on ${surface} needs 4.5:1 contrast`);
|
||||
}
|
||||
}
|
||||
for (const foreground of [dim, text, strong]) {
|
||||
assert(contrast(foreground, panel) >= 4.5, `${foreground} on image panel ${panel} needs 4.5:1 contrast`);
|
||||
}
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,76 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,155 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { BackgroundHub, backgroundHub } from '../src/lib/plugins/backgrounds.ts';
|
||||
import { ExternalSession } from '../src/lib/plugins/externalSession.ts';
|
||||
import type { BackgroundFrame, PluginApi } from '../src/lib/plugins/sdk.ts';
|
||||
|
||||
const frame: BackgroundFrame = { url: 'blob:http://localhost/example', overlay: 0.3, position: 'center', size: 'cover' };
|
||||
|
||||
test('frames retain ownership, reveal earlier owners, and cannot mutate hub state', () => {
|
||||
const hub = new BackgroundHub(() => undefined);
|
||||
const first = Symbol(), second = Symbol();
|
||||
const events: string[] = [];
|
||||
hub.subscribe(target => events.push(target));
|
||||
hub.set(first, 'pm-all', frame);
|
||||
const received = hub.get('pm-all')!;
|
||||
received.url = 'blob:changed';
|
||||
assert.equal(hub.get('pm-all')!.url, frame.url);
|
||||
hub.set(second, 'pm-all', { ...frame, overlay: -0.4 });
|
||||
hub.set(first, 'app', frame);
|
||||
assert.equal(hub.get('pm-all')!.overlay, -0.4);
|
||||
hub.removeOwner(second);
|
||||
assert.equal(hub.get('pm-all')!.overlay, 0.3);
|
||||
hub.removeOwner(first);
|
||||
assert.equal(hub.get('pm-all'), null);
|
||||
assert.equal(hub.get('app'), null);
|
||||
assert.deepEqual(events, ['pm-all', 'pm-all', 'app', 'pm-all', 'pm-all', 'app']);
|
||||
});
|
||||
|
||||
test('app override uses body properties and removes them without changing current root appearance', () => {
|
||||
const root = new Map([['--rs-background-image', 'saved image']]);
|
||||
const properties = new Map<string, string>();
|
||||
const style = {
|
||||
getPropertyValue: (key: string) => properties.get(key) ?? '',
|
||||
getPropertyPriority: () => '',
|
||||
setProperty: (key: string, value: string) => properties.set(key, value),
|
||||
removeProperty: (key: string) => { properties.delete(key); },
|
||||
};
|
||||
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement);
|
||||
const owner = Symbol();
|
||||
hub.set(owner, 'app', frame);
|
||||
assert.match(properties.get('--rs-background-image')!, /blob:http/);
|
||||
assert.equal(properties.get('--rs-workarea-surface-opacity'), 'var(--rs-surface-opacity, 82%)');
|
||||
assert.equal(properties.get('--rs-workarea-plugin-bg'), 'var(--rs-transparent-plugin-bg, transparent)');
|
||||
root.set('--rs-background-image', 'new saved image');
|
||||
hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' });
|
||||
assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/);
|
||||
hub.removeOwner(owner);
|
||||
assert.equal(properties.size, 0);
|
||||
assert.equal(root.get('--rs-background-image'), 'new saved image');
|
||||
});
|
||||
|
||||
test('invalid frames and targets do not enter the hub', () => {
|
||||
const hub = new BackgroundHub(() => undefined), owner = Symbol();
|
||||
for (const target of ['pm-board:../../x', 'unknown', 'pm-board:']) assert.throws(() => hub.set(owner, target, frame), /target/);
|
||||
for (const invalid of [{ ...frame, url: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'https://example.com/image.png' }, { ...frame, blurredUrl: 'blob:bad")' }, { ...frame, overlay: NaN }, { ...frame, overlay: 2 }, { ...frame, url: 'blob:bad")' }]) {
|
||||
assert.throws(() => hub.set(owner, 'app', invalid), /frame/);
|
||||
}
|
||||
hub.set(owner, 'pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1', frame);
|
||||
hub.removeOwner(owner);
|
||||
});
|
||||
|
||||
test('portrait frames retain a contained foreground and cover underlay through transitions and cleanup', () => {
|
||||
const properties = new Map<string, string>();
|
||||
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
|
||||
setProperty: (key: string, value: string) => properties.set(key, value), removeProperty: (key: string) => properties.delete(key) };
|
||||
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
|
||||
hub.set(owner, 'app', { ...frame, size: 'contain', blurredUrl: 'blob:blurred', previous: frame, transitionMs: 2000 });
|
||||
assert.equal(properties.get('--rs-background-layer-sizes'), '100% 100%, contain, cover');
|
||||
assert.equal(properties.get('--rs-background-layer-positions'), 'center, center, center');
|
||||
assert.equal(properties.get('--rs-background-previous-layer-sizes'), '100% 100%, cover');
|
||||
assert.match(properties.get('--rs-background-image')!, /blob:blurred/);
|
||||
const received = hub.get('app')!;
|
||||
received.blurredUrl = 'blob:changed';
|
||||
assert.equal(hub.get('app')!.blurredUrl, 'blob:blurred');
|
||||
hub.removeOwner(owner);
|
||||
assert.equal(properties.size, 0);
|
||||
});
|
||||
|
||||
test('fade frames validate previous images and keep nested data private', () => {
|
||||
const hub = new BackgroundHub(() => undefined), owner = Symbol();
|
||||
const fading = { ...frame, previous: { ...frame, url: 'blob:previous' }, transitionMs: 800 };
|
||||
hub.set(owner, 'pm-all', fading);
|
||||
fading.previous.url = 'blob:mutated';
|
||||
const received = hub.get('pm-all')!;
|
||||
assert.equal(received.previous!.url, 'blob:previous');
|
||||
received.previous!.url = 'blob:changed';
|
||||
assert.equal(hub.get('pm-all')!.previous!.url, 'blob:previous');
|
||||
for (const invalid of [
|
||||
{ ...frame, previous: { ...frame, url: 'https://example.com/image.png' } },
|
||||
{ ...frame, transitionMs: NaN }, { ...frame, transitionMs: -1 }, { ...frame, transitionMs: 5001 },
|
||||
]) assert.throws(() => hub.set(owner, 'pm-all', invalid), /frame/);
|
||||
});
|
||||
|
||||
test('subscriber errors do not prevent frame cleanup or remaining notifications', () => {
|
||||
const hub = new BackgroundHub(() => undefined), owner = Symbol();
|
||||
let events = 0;
|
||||
hub.subscribe(() => { throw new Error('Subscriber failure'); });
|
||||
hub.subscribe(() => { events++; });
|
||||
hub.set(owner, 'pm-all', frame);
|
||||
hub.removeOwner(owner);
|
||||
assert.equal(events, 2);
|
||||
assert.equal(hub.get('pm-all'), null);
|
||||
});
|
||||
|
||||
test('disable removes frames and subscriptions before cleanup and rejects pending file results', async () => {
|
||||
let api!: PluginApi;
|
||||
let finishRead!: (value: Uint8Array) => void;
|
||||
let finishList!: (value: { name: string }[]) => void;
|
||||
let finishPicker!: (value: string | null) => void;
|
||||
const session = new ExternalSession('org.test.backgrounds', {
|
||||
workspace: { list: async () => [], read: async () => '', write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
backgrounds: {
|
||||
chooseFolder: () => new Promise(resolve => { finishPicker = resolve; }),
|
||||
list: () => new Promise(resolve => { finishList = resolve; }),
|
||||
read: () => new Promise(resolve => { finishRead = resolve; }),
|
||||
},
|
||||
}, () => {}, () => {});
|
||||
let notifications = 0;
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.backgrounds!.subscribe(() => { notifications++; });
|
||||
api.backgrounds!.set('app', frame);
|
||||
api.backgrounds!.set('pm-all', frame);
|
||||
api.onDispose(() => {
|
||||
assert.equal(backgroundHub.get('app'), null);
|
||||
assert.equal(backgroundHub.get('pm-all'), null);
|
||||
assert.throws(() => api.backgrounds!.get('app'), /disabled/);
|
||||
});
|
||||
} });
|
||||
const pending = [api.backgrounds!.read('folder', 'file.png'), api.backgrounds!.list('folder'), api.backgrounds!.chooseFolder()];
|
||||
const rejected = pending.map(request => assert.rejects(request, /disabled/));
|
||||
await session.stop();
|
||||
finishRead(new Uint8Array([1])); finishList([{ name: 'file.png' }]); finishPicker('folder');
|
||||
await Promise.all(rejected);
|
||||
assert.equal(notifications, 2);
|
||||
assert.throws(() => api.backgrounds!.set('app', frame), /disabled/);
|
||||
assert.throws(() => api.backgrounds!.read('folder', 'file.png'), /disabled/);
|
||||
assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/);
|
||||
assert.equal(backgroundHub.get('app'), null);
|
||||
});
|
||||
|
||||
|
||||
test('background commands are allowed in main and settings windows', () => {
|
||||
const build = readFileSync(new URL('../src-tauri/build.rs', import.meta.url), 'utf8');
|
||||
for (const scope of ['default', 'settings']) {
|
||||
const capability = JSON.parse(readFileSync(new URL(`../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
|
||||
for (const command of ['backgrounds_choose_folder', 'backgrounds_default_folder', 'backgrounds_list', 'backgrounds_read', 'backgrounds_read_image_settings', 'backgrounds_write_image_settings']) {
|
||||
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
|
||||
assert(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), `${scope} must allow ${command}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,153 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { writeFile } from 'node:fs/promises';
|
||||
const require = createRequire(path.resolve('browser-runtime/package.json'));
|
||||
const { chromium } = require('playwright');
|
||||
const browser = await chromium.connectOverCDP(process.env.BROWSER_NATIVE_CDP || 'http://127.0.0.1:9224');
|
||||
const page = browser.contexts()[0].pages()[0];
|
||||
const raw = (command, args = {}) => page.evaluate(({ command, args }) => window.__TAURI_INTERNALS__.invoke(command, args), { command, args });
|
||||
const profile = await raw('plugins_snapshot');
|
||||
assert.ok(/[\\/]com\.runestone\.(?:browser|spelling)-test[\\/]plugins$/.test(profile.root), 'Native acceptance requires an isolated test profile.');
|
||||
const session = await raw('browser_connect');
|
||||
const request = (command, args = {}) => raw('browser_request', { command, args, session });
|
||||
const initialTabs = (await request('state')).tabs.map(tab => tab.id);
|
||||
let tabId;
|
||||
try {
|
||||
await page.keyboard.press('Control+t');
|
||||
await page.getByRole('button', { name: 'Open browser', exact: true }).click();
|
||||
const surface = page.getByRole('application', { name: 'Web page', exact: true }).last();
|
||||
await page.locator('.browser[data-browser-state="ready"]').last().waitFor();
|
||||
tabId = await page.locator('.browser[data-browser-state="ready"]').last().getAttribute('data-browser-tab');
|
||||
const address = page.getByRole('textbox', { name: 'Address or search', exact: true }).last();
|
||||
await address.fill('https://example.com/'); await address.press('Enter');
|
||||
for (let attempt = 0; attempt < 60; attempt++) {
|
||||
const snapshot = await request('agentSnapshot', { tabId });
|
||||
if (snapshot.text.includes('documentation examples')) break;
|
||||
if (attempt === 59) throw Error(`Public test page did not load: ${snapshot.text}`);
|
||||
await page.waitForTimeout(250);
|
||||
}
|
||||
await page.waitForFunction(() => [...document.querySelectorAll('.surface img')].some(image => image.complete && image.naturalWidth > 0));
|
||||
const dimensions = await surface.locator('img').evaluate(image => ({ width: image.naturalWidth, height: image.naturalHeight,
|
||||
css: image.getBoundingClientRect().width, scale: devicePixelRatio, source: image.src.slice(0, 30) }));
|
||||
assert.ok(dimensions.width >= dimensions.css * dimensions.scale - 2, JSON.stringify(dimensions));
|
||||
const bounds = await surface.boundingBox();
|
||||
await page.mouse.click(bounds.x + 20, bounds.y + 20, { button: 'right' });
|
||||
const menu = page.getByRole('menu', { name: 'Browser page actions', exact: true });
|
||||
await menu.waitFor();
|
||||
assert.equal(await menu.getByRole('menuitem', { name: 'Reload', exact: true }).count(), 1);
|
||||
await page.keyboard.press('Escape'); await menu.waitFor({ state: 'detached' });
|
||||
await request('edit', { tabId, action: 'selectAll' });
|
||||
await page.waitForTimeout(100);
|
||||
await request('edit', { tabId, action: 'copy' });
|
||||
await page.waitForTimeout(100);
|
||||
await address.focus(); await page.keyboard.press('Control+a'); await page.keyboard.press('Control+v');
|
||||
assert.match(await address.inputValue(), /documentation examples/);
|
||||
await address.fill('https://example.com/');
|
||||
await assert.rejects(raw('browser_request', { command: 'edit', args: { tabId, action: 'copy' }, session: 'invalid-session' }), /session/i);
|
||||
await assert.rejects(request('contextAction', { tabId, token: 'stale-menu', action: 'saveImage' }), /no longer available/);
|
||||
await page.screenshot({ path: 'output/browser-native-acceptance.png' });
|
||||
await writeFile('output/browser-native-acceptance.json', JSON.stringify({ dimensions, passed: [
|
||||
'Native Tauri-to-Electron page rendering and high-DPI frame delivery', 'Native page context event opens the shared host menu',
|
||||
'Native editing commands copy real webpage text', 'Session and stale-menu checks reject invalid requests',
|
||||
] }, null, 2));
|
||||
console.log('PASS native browser transport, rendering, context menu, editing and session protection');
|
||||
} finally {
|
||||
if (tabId && !initialTabs.includes(tabId)) { await page.keyboard.press('Escape'); await page.keyboard.press('Control+w'); }
|
||||
await browser.close();
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ContributionRegistry } from "../src/lib/plugins/registry.ts";
|
||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
||||
|
||||
test("browser contributions and view updates are revoked when the plugin stops", async () => {
|
||||
const registry = new ContributionRegistry();
|
||||
let api!: PluginApi;
|
||||
let disposed = false;
|
||||
const received: string[] = [];
|
||||
const session = new ExternalSession("runestone.browser", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {}, registry);
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.registerView({ id: "tab-test", title: "Browser", placement: "editor", icon: "globe", mount: () => {} });
|
||||
api.registerTabDrop!(data => { received.push(data); });
|
||||
api.contribute("browser", { mountSettings: () => () => {}, mountBookmarks: () => () => {}, open: async () => true });
|
||||
api.onDispose(() => { disposed = true; });
|
||||
} });
|
||||
assert.ok(registry.get("browser"));
|
||||
await session.dropTab("live-tab");
|
||||
assert.deepEqual(received, ["live-tab"]);
|
||||
api.updateViewTitle!("tab-test", "Example · User");
|
||||
assert.equal(session.views.get("tab-test")?.title, "Example · User");
|
||||
const icon = "data:image/png;base64,aW1hZ2U=";
|
||||
api.updateViewIcon!("tab-test", icon);
|
||||
assert.equal(session.views.get("tab-test")?.iconImage, icon);
|
||||
assert.throws(() => api.updateViewIcon!("tab-test", "https://example.com/icon.png"), /Invalid/);
|
||||
assert.throws(() => api.updateViewIcon!("tab-test", "data:text/html;base64,aW1hZ2U="), /Invalid/);
|
||||
assert.throws(() => api.updateViewIcon!("tab-test", "data:image/png;base64," + "a".repeat(90_000)), /Invalid/);
|
||||
api.updateViewIcon!("tab-test", null);
|
||||
assert.equal(session.views.get("tab-test")?.iconImage, null);
|
||||
await session.stop();
|
||||
assert.equal(registry.get("browser"), undefined);
|
||||
assert.equal(disposed, true);
|
||||
assert.throws(() => api.updateViewTitle!("tab-test", "Other"), /disabled/);
|
||||
assert.throws(() => api.updateViewIcon!("tab-test", icon), /disabled/);
|
||||
await assert.rejects(session.dropTab("closed-tab"), /disabled/);
|
||||
assert.throws(() => api.registerTabDrop!(() => {}), /disabled/);
|
||||
assert.deepEqual(received, ["live-tab"]);
|
||||
});
|
||||
@@ -1,108 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,218 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,109 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,231 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,41 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { detectChrome, extensionOf, treeFileParts } from "../src/lib/workspace/chrome.ts";
|
||||
import { monacoChrome } from "../src/lib/editor/monacoChrome.ts";
|
||||
|
||||
test("markdown files open in writing chrome", () => {
|
||||
assert.equal(detectChrome("notes/inbox.md"), "Writing");
|
||||
assert.equal(detectChrome("README.markdown"), "Writing");
|
||||
});
|
||||
|
||||
test("scripts open in ide chrome", () => {
|
||||
assert.equal(detectChrome("src/hello.py"), "Ide");
|
||||
assert.equal(detectChrome("tools/setup.sh"), "Ide");
|
||||
assert.equal(detectChrome("Makefile"), "Ide");
|
||||
});
|
||||
|
||||
test("writing chrome wraps and hides line numbers", () => {
|
||||
assert.equal(monacoChrome("Writing").wordWrap, "on");
|
||||
assert.equal(monacoChrome("Writing").lineNumbers, "off");
|
||||
assert.equal(monacoChrome("Writing").minimap.enabled, false);
|
||||
});
|
||||
|
||||
test("ide chrome shows line numbers and no wrap", () => {
|
||||
assert.equal(monacoChrome("Ide").wordWrap, "off");
|
||||
assert.equal(monacoChrome("Ide").lineNumbers, "on");
|
||||
assert.equal(monacoChrome("Ide").minimap.enabled, true);
|
||||
});
|
||||
|
||||
test("extensionOf reads the last suffix", () => {
|
||||
assert.equal(extensionOf("a/b.c.py"), "py");
|
||||
assert.equal(extensionOf(".gitignore"), "");
|
||||
});
|
||||
|
||||
test("treeFileParts splits a display name from its extension", () => {
|
||||
assert.deepEqual(treeFileParts("inbox.md"), { label: "inbox", ext: "md" });
|
||||
assert.deepEqual(treeFileParts("chrome_extensions.json"), {
|
||||
label: "chrome_extensions",
|
||||
ext: "json",
|
||||
});
|
||||
assert.deepEqual(treeFileParts(".gitignore"), { label: ".gitignore", ext: "" });
|
||||
});
|
||||
@@ -1,135 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,35 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CompletionHub, eligible } from '../src/lib/completion/hub.ts';
|
||||
import type { CompletionSnapshot } from '../src/lib/completion/contracts.ts';
|
||||
const snapshot = (): CompletionSnapshot => ({ documentId: 'doc', revision: 1, text: 'The ', caret: 4, selectionEnd: 4, focused: true, kind: 'prose' });
|
||||
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
|
||||
test('sensitive fields, composition, selections, code blocks and link targets are excluded', () => {
|
||||
assert(eligible(snapshot()));
|
||||
for (const change of [{ sensitive: true }, { composing: true }, { readOnly: true }, { selectionEnd: 0 }, { focused: false }]) assert(!eligible({ ...snapshot(), ...change }));
|
||||
for (const text of ['```js\nlet ', '[name](http', '| cell ', '`source', '---\nname: ']) assert(!eligible({ ...snapshot(), text, caret: text.length, selectionEnd: text.length }));
|
||||
assert(eligible({ ...snapshot(), kind: 'code', text: 'let ', caret: 4 }));
|
||||
});
|
||||
test('a new revision blocks stale insertion even when the provider ignores cancellation', async () => {
|
||||
const hub = new CompletionHub(); let state = snapshot(), emit!: (text: string) => void, finish!: (text: string) => void, visible = '', edits = 0;
|
||||
hub.registerProvider({ id: 'model', complete: (_request, publish) => { emit = publish; return new Promise(resolve => finish = resolve); } });
|
||||
const field = hub.registerSurface({ id: 'field', snapshot: () => state, preview: text => visible = text || '', insert: () => { edits++; return true; } });
|
||||
field.request(); emit('harbor'); assert.equal(visible, 'harbor');
|
||||
state = { ...state, revision: 2, text: 'The old ', caret: 8, selectionEnd: 8 };
|
||||
assert.equal(field.accept(), false); finish('late'); await tick(); assert.equal(visible, ''); assert.equal(edits, 0); field.dispose();
|
||||
});
|
||||
test('acceptance is explicit and provider removal clears all surfaces', async () => {
|
||||
const hub = new CompletionHub(); let visible = '', inserted = '';
|
||||
const remove = hub.registerProvider({ id: 'model', complete: async () => 'quiet harbor' });
|
||||
const field = hub.registerSurface({ id: 'field', snapshot, preview: text => visible = text || '', insert: text => { inserted = text; return true; } });
|
||||
field.request(); await tick(); assert.equal(inserted, ''); assert.equal(visible, 'quiet harbor');
|
||||
assert(field.accept(true)); assert.equal(inserted, 'quiet '); assert.equal(visible, '');
|
||||
field.request(); await tick(); remove(); assert.equal(visible, ''); assert.equal(field.accept(), false); field.dispose();
|
||||
});
|
||||
test('moving between fields cancels the previous request', async () => {
|
||||
const hub = new CompletionHub(); const signals: AbortSignal[] = [];
|
||||
hub.registerProvider({ id: 'model', complete: request => { signals.push(request.signal); return new Promise(() => {}); } });
|
||||
const a = hub.registerSurface({ id: 'a', snapshot, preview() {}, insert: () => true });
|
||||
const b = hub.registerSurface({ id: 'b', snapshot, preview() {}, insert: () => true });
|
||||
a.request(); b.request(); assert(signals[0].aborted); assert(!signals[1].aborted); a.dispose(); b.dispose();
|
||||
});
|
||||
@@ -1,111 +0,0 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { COLOR_TOKENS, parseCustomTheme } from '../src/lib/theme/customThemes.ts';
|
||||
import { applyTransparency, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, themeModes } from '../src/lib/theme/appearance.ts';
|
||||
const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' };
|
||||
const theme = { schema: 2, id: 'my-theme', name: 'My theme', colors: palette };
|
||||
test('Fixed theme palettes retain all supplied colors', () => {
|
||||
assert.deepEqual(parseCustomTheme(theme), theme);
|
||||
});
|
||||
test('Legacy import selects the current appearance and validates both palettes', () => {
|
||||
const light = { ...palette, bg: '#fff' };
|
||||
const legacy = { schema: 1, id: theme.id, name: theme.name, light, dark: palette };
|
||||
assert.deepEqual(parseCustomTheme(legacy).colors, palette);
|
||||
assert.deepEqual(parseCustomTheme(legacy, 'light').colors, light);
|
||||
assert.throws(() => parseCustomTheme({ ...legacy, light: {} }));
|
||||
});
|
||||
test('Theme files reject CSS injection, unknown tokens, and incomplete palettes', () => {
|
||||
for (const colors of [{ ...palette, bg: 'url(https://invalid.test)' }, { ...palette, position: 'fixed' }, { bg: '#000' }, []]) {
|
||||
assert.throws(() => parseCustomTheme({ ...theme, colors }));
|
||||
}
|
||||
assert.throws(() => parseCustomTheme({ ...theme, id: '../unsafe' }));
|
||||
});
|
||||
test('Every built-in template contains every current color token and one palette', () => {
|
||||
for (const item of BUILTIN_THEMES) for (const mode of themeModes(item.id)) {
|
||||
const exported = exportAppearanceTheme(item.id, mode);
|
||||
assert.deepEqual(Object.keys(exported.colors).sort(), [...COLOR_TOKENS].sort());
|
||||
assert.deepEqual(parseCustomTheme(exported), exported);
|
||||
assert.equal('light' in exported, false);
|
||||
assert.equal('dark' in exported, false);
|
||||
}
|
||||
assert.notDeepEqual(exportAppearanceTheme('default', 'light').colors, exportAppearanceTheme('default', 'dark').colors);
|
||||
});
|
||||
test('Transparency normalizes old, invalid, and extreme saved values', () => {
|
||||
assert.equal(normalizeAppearance(null).transparency, undefined);
|
||||
assert.deepEqual(normalizeAppearance({ transparency: { enabled: false, amount: 27 } }).transparency, { enabled: false, amount: 27 });
|
||||
for (const [amount, expected] of [[-10, 0], [55, 55], [100, 100], [120, 100], [NaN, 18], [Infinity, 18], [12.8, 13]]) {
|
||||
assert.equal(normalizeAppearance({ transparency: { amount } }).transparency?.amount, expected);
|
||||
}
|
||||
});
|
||||
|
||||
test('Theme font roles round-trip and reject CSS injection', () => {
|
||||
const fonts = { ui: 'Arial, sans-serif', prose: '"Times New Roman", serif', heading: 'Georgia, serif', mono: 'Consolas, monospace' };
|
||||
assert.deepEqual(parseCustomTheme({ ...theme, fonts }).fonts, fonts);
|
||||
for (const fonts of [{ ui: 'url(https://example.test)' }, { ui: 'Arial; color: red' }, { unknown: 'Arial' }, { ui: '' }, { ui: 'Arial,,serif' }, { ui: '"Arial' }, []]) {
|
||||
assert.throws(() => parseCustomTheme({ ...theme, fonts }));
|
||||
}
|
||||
for (const item of BUILTIN_THEMES) {
|
||||
const exported = exportAppearanceTheme(item.id);
|
||||
assert.deepEqual(Object.keys(exported.fonts!).sort(), ['heading', 'mono', 'prose', 'ui']);
|
||||
assert.deepEqual(parseCustomTheme(exported), exported);
|
||||
}
|
||||
assert.match(exportAppearanceTheme('claude').fonts!.heading!, /Poppins/);
|
||||
assert.match(exportAppearanceTheme('harvest-moon').fonts!.ui!, /Candara/);
|
||||
});
|
||||
|
||||
test('Full transparency range produces valid surface opacity values', () => {
|
||||
const values = new Map<string, string>();
|
||||
const root = { dataset: {}, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
|
||||
for (const amount of [0, 18, 40, 55, 99, 100]) {
|
||||
applyTransparency({ enabled: true, amount }, root);
|
||||
assert.equal(values.get('--rs-surface-opacity'), `${100 - amount}%`);
|
||||
for (const key of ['--rs-surface-opacity', '--rs-editor-surface-opacity', '--rs-hover-surface-opacity']) {
|
||||
const opacity = parseFloat(values.get(key)!);
|
||||
assert(opacity >= 0 && opacity <= 100);
|
||||
}
|
||||
}
|
||||
});
|
||||
test('Opaque mode retains background ownership and the amount for re-enabling', () => {
|
||||
const values = new Map<string, string>();
|
||||
const root = { dataset: {} as Record<string, string>, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
|
||||
applyTransparency({ enabled: false, amount: 32 }, root);
|
||||
assert.equal(values.get('--rs-surface-opacity'), '100%');
|
||||
assert.equal(values.get('--rs-editor-surface-opacity'), '100%');
|
||||
assert.equal(values.get('--rs-transparent-plugin-bg'), 'transparent');
|
||||
assert.equal(root.dataset.transparency, 'off');
|
||||
applyTransparency({ enabled: true, amount: 18 }, root);
|
||||
assert.equal(values.get('--rs-surface-opacity'), '82%');
|
||||
assert.equal(values.get('--rs-editor-surface-opacity'), '90%');
|
||||
assert.equal(root.dataset.transparency, 'on');
|
||||
});
|
||||
|
||||
test('Saved legacy light themes migrate once and preserve both original palettes', async () => {
|
||||
const { customThemes, CUSTOM_THEMES_KEY } = await import('../src/lib/theme/customThemes.ts');
|
||||
const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } };
|
||||
const stored = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
|
||||
const previous = globalThis.localStorage;
|
||||
try {
|
||||
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as Storage;
|
||||
assert.deepEqual(customThemes()[0].colors, legacy.light);
|
||||
assert.deepEqual(themeModes('custom:saved-light'), ['light']);
|
||||
assert.equal(normalizeAppearance({ theme: 'custom:saved-light', mode: 'dark' }).mode, 'light');
|
||||
assert.deepEqual(exportAppearanceTheme('custom:saved-light').colors.bg, '#fff');
|
||||
assert.equal(JSON.parse(stored.get(CUSTOM_THEMES_KEY)!)[0].schema, 2);
|
||||
assert.deepEqual(JSON.parse(stored.get(`${CUSTOM_THEMES_KEY}.legacy`)!)[0], legacy);
|
||||
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
|
||||
} finally { globalThis.localStorage = previous; }
|
||||
});
|
||||
|
||||
test('Legacy migration storage failure leaves the original palette available', async () => {
|
||||
const { customThemes, CUSTOM_THEMES_KEY } = await import('../src/lib/theme/customThemes.ts');
|
||||
const legacy = { schema: 1, id: 'quota-light', name: 'Quota light', light: { ...palette, bg: '#fefefe' }, dark: palette };
|
||||
const raw = JSON.stringify([legacy]);
|
||||
const previous = globalThis.localStorage;
|
||||
let original = raw;
|
||||
try {
|
||||
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? original : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
|
||||
assert.deepEqual(customThemes('light')[0].colors, legacy.light);
|
||||
assert.equal(original, raw);
|
||||
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
|
||||
} finally { globalThis.localStorage = previous; }
|
||||
});
|
||||
@@ -1,138 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,23 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { SearchQuery } from "@codemirror/search";
|
||||
import { documentMatches, replacementText } from "../src/lib/editor/findTarget.ts";
|
||||
|
||||
test("document search uses Writer word matching and normalized CRLF positions", () => {
|
||||
const query = new SearchQuery({ search: "Alpha", wholeWord: true, caseSensitive: true });
|
||||
const { state, matches } = documentMatches("Alpha alphabet\r\nalpha Alpha", query);
|
||||
assert.deepEqual(matches.map(({ from, to }) => ({ from, to })), [{ from: 0, to: 5 }, { from: 21, to: 26 }]);
|
||||
assert.equal(state.doc.lineAt(matches[1].from).number, 2);
|
||||
assert.equal(state.doc.lineAt(matches[1].from).from, 15);
|
||||
});
|
||||
|
||||
test("replacement keeps regex context, capture groups, dollars, and line breaks", () => {
|
||||
const query = new SearchQuery({ search: "(?<=G)(amma)", regexp: true, replace: "$1-$12-$&-$$\\n" });
|
||||
assert.equal(replacementText("Gamma", 1, query), "amma-amma2-amma-$\n");
|
||||
assert.equal(replacementText("Alpha", 0, new SearchQuery({ search: "Alpha", replace: "$1\\t" })), "$1\t");
|
||||
});
|
||||
|
||||
test("empty and invalid queries do not produce matches", () => {
|
||||
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "" })).matches, []);
|
||||
assert.deepEqual(documentMatches("Alpha", new SearchQuery({ search: "[", regexp: true })).matches, []);
|
||||
});
|
||||
@@ -1,57 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "../src/lib/workspace/documentPanes.ts";
|
||||
import { paneBounds } from "../src/lib/workspace/splitLayout.ts";
|
||||
import { registerSelection, selectedEditorText } from "../src/lib/editor/selection.ts";
|
||||
|
||||
test("opening a link to the right keeps its source and focuses an existing pane for duplicate targets", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b", "c"], "a");
|
||||
const primary = state.active;
|
||||
state = readDocumentPane(state, primary, true);
|
||||
state = splitDocumentPane(state, primary, "b", "right");
|
||||
assert.deepEqual(state.panes.map(pane => pane.documentId), ["a", "b"]);
|
||||
assert.equal(state.active, "right");
|
||||
assert.deepEqual(paneBounds(state.layout).right, { left: 50, top: 0, width: 50, height: 100 });
|
||||
state = splitDocumentPane(state, "right", "a", "unused");
|
||||
assert.equal(state.active, primary);
|
||||
assert.equal(state.panes.length, 2);
|
||||
assert.equal(state.panes[0].reading, true);
|
||||
state = splitDocumentPane(state, "right", "c", "third");
|
||||
assert.equal(paneBounds(state.layout).third.left, 75);
|
||||
});
|
||||
|
||||
test("closing a split preserves the remaining pane and a later tab selection can restore its hidden document", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
|
||||
state = splitDocumentPane(state, state.active, "b", "right");
|
||||
state = closeDocumentPane(state, "right");
|
||||
assert.equal(state.panes[0].documentId, "a");
|
||||
assert.equal(state.layout, state.active);
|
||||
state = syncDocumentPanes(state, ["a", "b"], "b");
|
||||
assert.equal(state.panes[0].documentId, "b");
|
||||
});
|
||||
|
||||
test("tab replacement stays in its focused pane, and closing another tab collapses only its empty pane", () => {
|
||||
let state = syncDocumentPanes(initialDocumentPanes(), ["a", "b"], "a");
|
||||
state = splitDocumentPane(state, state.active, "b", "right");
|
||||
state = syncDocumentPanes(state, ["a", "c"], "c");
|
||||
assert.deepEqual(state.panes.map(pane => pane.documentId), ["a", "c"]);
|
||||
assert.equal(state.active, "right");
|
||||
const unchanged = syncDocumentPanes(state, ["a", "c"], "c");
|
||||
assert.equal(unchanged, state);
|
||||
state = syncDocumentPanes(state, ["c"], "c");
|
||||
assert.equal(state.panes.length, 1);
|
||||
assert.equal(state.layout, "right");
|
||||
assert.equal(selectPane(state, "missing"), state);
|
||||
});
|
||||
|
||||
test("selection readers remain available in both panes and disposal cannot clear a replacement reader", () => {
|
||||
const first = registerSelection("a", () => "first selection");
|
||||
const second = registerSelection("b", () => "second selection");
|
||||
assert.equal(selectedEditorText("a"), "first selection");
|
||||
assert.equal(selectedEditorText("b"), "second selection");
|
||||
const replacement = registerSelection("a", () => "new selection");
|
||||
first(); second();
|
||||
assert.equal(selectedEditorText("a"), "new selection");
|
||||
assert.equal(selectedEditorText("b"), "");
|
||||
replacement();
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { documentSessionKey, parseDocumentSession, restoreDocumentSession } from "../src/lib/workspace/documentSession.ts";
|
||||
|
||||
test("document sessions isolate workspaces and discard unsafe or duplicate paths", () => {
|
||||
assert.notEqual(documentSessionKey("C:\\one"), documentSessionKey("C:\\two"));
|
||||
assert.equal(parseDocumentSession("invalid"), null);
|
||||
assert.equal(parseDocumentSession('{"version":2,"documents":[]}'), null);
|
||||
assert.deepEqual(parseDocumentSession(JSON.stringify({ version: 1, activePath: "b.md", documents: [
|
||||
{ path: "b.md", pinned: true, contents: "unsaved" }, { path: "a.md" }, { path: "b.md" },
|
||||
{ path: "../outside.md" }, { path: "C:\\outside.md" }, { path: "empty:test" }, null,
|
||||
] })), { version: 1, activePath: "b.md", documents: [{ path: "b.md", pinned: true }, { path: "a.md", pinned: false }] });
|
||||
});
|
||||
|
||||
test("restoration keeps order and active tab when a missing file fails", async () => {
|
||||
const opened: string[] = [];
|
||||
const session = parseDocumentSession(JSON.stringify({ version: 1, activePath: "c.md",
|
||||
documents: ["b.md", "missing.md", "c.md", "a.md"].map(path => ({ path })) }))!;
|
||||
const active = await restoreDocumentSession(session, async item => {
|
||||
if (item.path === "missing.md") throw new Error("Not found");
|
||||
opened.push(item.path);
|
||||
});
|
||||
assert.deepEqual(opened, ["b.md", "c.md", "a.md"]);
|
||||
assert.equal(active, "c.md");
|
||||
assert.equal(await restoreDocumentSession({ ...session, activePath: "missing.md" }, async item => {
|
||||
if (item.path === "missing.md") throw new Error("Not found");
|
||||
}), "b.md");
|
||||
assert.equal(await restoreDocumentSession(session, async () => { throw new Error("Unavailable"); }), null);
|
||||
});
|
||||
@@ -1,160 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,429 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { Documents } from "../src/lib/workspace/documents.ts";
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>(done => resolve = done);
|
||||
return { promise, resolve };
|
||||
}
|
||||
const entry = (path: string) => ({ rel_path: path, name: path, kind: "file" as const });
|
||||
function setup() {
|
||||
const disk = new Map([["note.md", "original"], ["script.py", "print('hello')"]]);
|
||||
const io = {
|
||||
read: async (path: string) => { if (!disk.has(path)) throw new Error("missing"); return disk.get(path)!; },
|
||||
write: async (path: string, contents: string, expected: string) => {
|
||||
if (disk.get(path) !== expected) throw new Error("conflict");
|
||||
disk.set(path, contents);
|
||||
},
|
||||
image: async () => "data:image/png;base64,",
|
||||
kind: () => "text" as const,
|
||||
chrome: () => "Writing" as const,
|
||||
};
|
||||
const docs = new Documents(io, () => {});
|
||||
return { docs, disk, io };
|
||||
}
|
||||
|
||||
test("imported tabs retain unsaved text and preserve pinned empty tabs", async () => {
|
||||
const { docs } = setup();
|
||||
docs.newTab();
|
||||
const empty = docs.active!;
|
||||
docs.togglePin(empty.relPath);
|
||||
const source = setup().docs;
|
||||
await source.open(entry("note.md"));
|
||||
source.edit(source.active!.id, "unsaved source text");
|
||||
source.togglePin("note.md");
|
||||
assert.equal(docs.importTab(source.active!), true);
|
||||
assert.equal(docs.active!.contents, "unsaved source text");
|
||||
assert.equal(docs.active!.saved, "original");
|
||||
assert.equal(docs.active!.pinned, true);
|
||||
assert.notEqual(docs.active!.id, source.active!.id);
|
||||
assert.ok(docs.buffers.some(tab => tab.id === empty.id));
|
||||
assert.equal(docs.importTab({ ...source.active!, contents: "different" }), false);
|
||||
assert.equal(docs.active!.contents, "unsaved source text");
|
||||
});
|
||||
|
||||
test("background loading for a split preserves the selected document and its unsaved edits", async () => {
|
||||
const { docs } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const first = docs.active!;
|
||||
docs.edit(first.id, "unsaved text");
|
||||
await docs.open(entry("script.py"), "background");
|
||||
assert.equal(docs.active, first);
|
||||
assert.equal(first.contents, "unsaved text");
|
||||
assert.equal(docs.buffers.length, 2);
|
||||
await assert.rejects(docs.open(entry("missing.md"), "background"));
|
||||
assert.equal(docs.active, first);
|
||||
docs.select("script.py");
|
||||
assert.equal(docs.active?.relPath, "script.py");
|
||||
});
|
||||
|
||||
test("tab moves preserve selection, dirty buffers, and in-flight saves", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "my edits");
|
||||
docs.setChrome("Ide");
|
||||
await docs.open(entry("script.py"));
|
||||
docs.newTab();
|
||||
const blank = docs.active!;
|
||||
const gate = deferred<void>();
|
||||
const write = io.write;
|
||||
io.write = async (...args) => { await gate.promise; await write(...args); };
|
||||
const pending = docs.save(note.id);
|
||||
await Promise.resolve();
|
||||
docs.move(note.relPath, 2);
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", blank.relPath, "note.md"]);
|
||||
assert.equal(docs.active, blank);
|
||||
assert.equal(docs.buffers[2], note);
|
||||
assert.equal(note.contents, "my edits");
|
||||
assert.equal(note.saved, "original");
|
||||
assert.equal(note.chromeOverride, "Ide");
|
||||
docs.move(blank.relPath, 0);
|
||||
assert.equal(docs.active, blank);
|
||||
gate.resolve();
|
||||
await pending;
|
||||
assert.equal(disk.get("note.md"), "my edits");
|
||||
docs.close(blank.relPath);
|
||||
assert.equal(docs.activePath, "script.py");
|
||||
});
|
||||
|
||||
test("tab moves ignore stale paths and invalid indices and clamp to the tab strip", async () => {
|
||||
const { docs } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
await docs.open(entry("script.py"));
|
||||
docs.move("missing.md", 0);
|
||||
docs.move("script.py", NaN);
|
||||
docs.move("script.py", 0.5);
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
|
||||
docs.move("script.py", -1);
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["script.py", "note.md"]);
|
||||
docs.move("script.py", 99);
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
|
||||
docs.dispose();
|
||||
docs.move("script.py", 0);
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", "script.py"]);
|
||||
});
|
||||
|
||||
test("empty tabs are independent, preserve dirty documents, and never access disk", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "keep my edits");
|
||||
docs.newTab();
|
||||
const first = docs.active!;
|
||||
docs.newTab();
|
||||
const second = docs.active!;
|
||||
assert.equal(first.kind, "empty");
|
||||
assert.equal(second.kind, "empty");
|
||||
assert.notEqual(first.relPath, second.relPath);
|
||||
assert.equal(note.contents, "keep my edits");
|
||||
docs.select(first.relPath);
|
||||
docs.close(first.relPath);
|
||||
assert.equal(docs.active, second);
|
||||
docs.close(note.relPath);
|
||||
io.read = io.image = async () => { assert.fail("empty tabs must not read disk"); };
|
||||
io.write = async () => { assert.fail("empty tabs must not write disk"); };
|
||||
docs.edit(second.id, "ignored");
|
||||
await docs.refresh();
|
||||
await docs.save(second.id);
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
assert.equal(docs.dirty, false);
|
||||
assert.equal(second.diskError, undefined);
|
||||
docs.close(second.relPath);
|
||||
assert.equal(docs.activePath, null);
|
||||
});
|
||||
|
||||
test("opening a file fills the active empty tab in place and failed reads preserve it", async () => {
|
||||
const { docs } = setup();
|
||||
docs.newTab();
|
||||
const first = docs.active!;
|
||||
docs.newTab();
|
||||
const second = docs.active!;
|
||||
docs.select(first.relPath);
|
||||
await assert.rejects(docs.open(entry("missing.md")), /missing/);
|
||||
assert.equal(docs.active, first);
|
||||
await docs.open(entry("note.md"));
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["note.md", second.relPath]);
|
||||
docs.select(second.relPath);
|
||||
await docs.open(entry("note.md"));
|
||||
assert.equal(docs.buffers.length, 2);
|
||||
assert.equal(docs.activePath, "note.md");
|
||||
});
|
||||
|
||||
test("a new empty tab stays selected when an earlier file read finishes", async () => {
|
||||
const { docs, io } = setup();
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("note.md"));
|
||||
docs.newTab();
|
||||
const blank = docs.active!;
|
||||
gate.resolve("note");
|
||||
await pending;
|
||||
assert.equal(docs.active, blank);
|
||||
assert.equal(docs.buffers.length, 2);
|
||||
});
|
||||
|
||||
test("clean buffers follow agent edits; dirty buffers retain both versions", async () => {
|
||||
const { docs, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
disk.set("note.md", "agent version");
|
||||
await docs.refresh();
|
||||
assert.equal(docs.active?.contents, "agent version");
|
||||
docs.edit(docs.active!.id, "my version");
|
||||
disk.set("note.md", "agent version 2");
|
||||
await docs.refresh();
|
||||
assert.equal(docs.active?.contents, "my version");
|
||||
assert.equal(docs.active?.diskContents, "agent version 2");
|
||||
await assert.rejects(docs.save(docs.active!.id), /Resolve/);
|
||||
docs.resolve(docs.active!.id, false);
|
||||
await docs.save(docs.active!.id);
|
||||
assert.equal(disk.get("note.md"), "my version");
|
||||
});
|
||||
|
||||
test("typing during a save remains unsaved", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<void>();
|
||||
const write = io.write;
|
||||
io.write = async (...args) => { await gate.promise; return write(...args); };
|
||||
docs.edit(docs.active!.id, "first edit");
|
||||
const pending = docs.save(docs.active!.id);
|
||||
await Promise.resolve();
|
||||
docs.edit(docs.active!.id, "second edit");
|
||||
gate.resolve();
|
||||
await pending;
|
||||
assert.equal(disk.get("note.md"), "first edit");
|
||||
assert.equal(docs.active!.saved, "first edit");
|
||||
assert.equal(docs.active!.contents, "second edit");
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("concurrent saves serialize and finish at the latest edit", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<void>();
|
||||
const write = io.write;
|
||||
io.write = async (...args) => { await gate.promise; return write(...args); };
|
||||
docs.edit(docs.active!.id, "first");
|
||||
const first = docs.save(docs.active!.id);
|
||||
await Promise.resolve();
|
||||
docs.edit(docs.active!.id, "latest");
|
||||
const second = docs.save(docs.active!.id);
|
||||
const third = docs.save(docs.active!.id);
|
||||
gate.resolve();
|
||||
await Promise.all([first, second, third]);
|
||||
assert.equal(disk.get("note.md"), "latest");
|
||||
assert.equal(docs.dirty, false);
|
||||
});
|
||||
|
||||
test("latest navigation wins even when earlier reads finish later", async () => {
|
||||
const { docs, io } = setup();
|
||||
const gate = deferred<string>();
|
||||
const read = io.read;
|
||||
io.read = path => path === "note.md" ? gate.promise : read(path);
|
||||
const first = docs.open(entry("note.md"));
|
||||
await docs.open(entry("script.py"));
|
||||
gate.resolve("note");
|
||||
await first;
|
||||
assert.equal(docs.activePath, "script.py");
|
||||
});
|
||||
|
||||
test("duplicate opens share one document and do not lose edits", async () => {
|
||||
const { docs } = setup();
|
||||
await Promise.all([docs.open(entry("note.md")), docs.open(entry("note.md"))]);
|
||||
assert.equal(docs.buffers.length, 1);
|
||||
docs.edit(docs.active!.id, "unsaved");
|
||||
await docs.open(entry("script.py"));
|
||||
await docs.open(entry("note.md"));
|
||||
assert.equal(docs.active!.contents, "unsaved");
|
||||
});
|
||||
|
||||
test("current-tab navigation replaces the selected tab in place; new-tab navigation keeps it", async () => {
|
||||
const { docs, disk } = setup();
|
||||
disk.set("third.md", "third");
|
||||
await docs.open(entry("note.md"));
|
||||
await docs.open(entry("script.py"), "new");
|
||||
docs.select("note.md");
|
||||
await docs.open(entry("third.md"), "current");
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
|
||||
assert.equal(docs.activePath, "third.md");
|
||||
await docs.open(entry("script.py"), "current");
|
||||
assert.deepEqual(docs.buffers.map(b => b.relPath), ["third.md", "script.py"]);
|
||||
assert.equal(docs.activePath, "script.py");
|
||||
});
|
||||
|
||||
test("current-tab navigation preserves edits made while the next file is loading", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("script.py"), "current");
|
||||
docs.edit(note.id, "keep these edits");
|
||||
gate.resolve("script");
|
||||
await pending;
|
||||
assert.equal(docs.buffers.length, 2);
|
||||
assert.equal(note.contents, "keep these edits");
|
||||
assert.equal(docs.activePath, "script.py");
|
||||
});
|
||||
|
||||
test("failed current-tab navigation keeps the active document", async () => {
|
||||
const { docs } = setup();
|
||||
await docs.open(entry("note.md"), "current");
|
||||
await assert.rejects(docs.open(entry("missing.md"), "current"), /missing/);
|
||||
assert.equal(docs.buffers.length, 1);
|
||||
assert.equal(docs.activePath, "note.md");
|
||||
});
|
||||
|
||||
test("a late current-tab read cannot replace a more recently selected tab", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("script.py"), "current");
|
||||
docs.select("note.md");
|
||||
gate.resolve("script");
|
||||
await pending;
|
||||
assert.equal(docs.activePath, "note.md");
|
||||
assert.equal(docs.buffers[0].relPath, "note.md");
|
||||
});
|
||||
|
||||
test("removed files retain text and block accidental recreation", async () => {
|
||||
const { docs, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
docs.edit(docs.active!.id, "precious text");
|
||||
disk.delete("note.md");
|
||||
await docs.refresh();
|
||||
assert.equal(docs.active!.contents, "precious text");
|
||||
assert.match(docs.active!.diskError!, /unavailable/);
|
||||
await assert.rejects(docs.save(docs.active!.id));
|
||||
});
|
||||
|
||||
test("disposing a workspace ignores late open results", async () => {
|
||||
const { docs, io } = setup();
|
||||
const gate = deferred<string>();
|
||||
io.read = () => gate.promise;
|
||||
const pending = docs.open(entry("note.md"));
|
||||
docs.dispose(); gate.resolve("late");
|
||||
await pending;
|
||||
assert.equal(docs.buffers.length, 0);
|
||||
});
|
||||
|
||||
test("renaming a folder preserves document identity and dirty state", async () => {
|
||||
const { docs } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const id = docs.active!.id;
|
||||
docs.edit(id, "edits"); docs.rename("note.md", "notes/moved.md");
|
||||
assert.equal(docs.activePath, "notes/moved.md");
|
||||
assert.equal(docs.active!.id, id);
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("autosave writes changed background tabs once and skips clean or reverted text", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
const writes: string[] = [];
|
||||
const write = io.write;
|
||||
io.write = async (...args) => { writes.push(args[0]); await write(...args); };
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "background edit");
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "temporary edit");
|
||||
docs.edit(docs.active!.id, docs.active!.saved);
|
||||
assert.deepEqual(await docs.autosave(), { saved: ["note.md"], failed: [] });
|
||||
assert.equal(disk.get("note.md"), "background edit");
|
||||
await docs.autosave();
|
||||
await docs.save(note.id);
|
||||
assert.deepEqual(writes, ["note.md"]);
|
||||
});
|
||||
|
||||
test("autosave skips in-flight saves and preserves edits for the next pass", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const gate = deferred<void>();
|
||||
const write = io.write;
|
||||
let writes = 0;
|
||||
io.write = async (...args) => { writes++; await gate.promise; await write(...args); };
|
||||
docs.edit(docs.active!.id, "first");
|
||||
const pending = docs.autosave();
|
||||
await Promise.resolve();
|
||||
docs.edit(docs.active!.id, "still typing");
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
gate.resolve();
|
||||
await pending;
|
||||
assert.equal(writes, 1);
|
||||
assert.equal(disk.get("note.md"), "first");
|
||||
assert.equal(docs.dirty, true);
|
||||
await docs.autosave();
|
||||
assert.equal(writes, 2);
|
||||
assert.equal(disk.get("note.md"), "still typing");
|
||||
});
|
||||
|
||||
test("autosave skips known conflicts and unavailable files", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "my note");
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "my script");
|
||||
disk.set("note.md", "external edit");
|
||||
disk.delete("script.py");
|
||||
await docs.refresh();
|
||||
io.write = async () => { assert.fail("blocked files must not be written"); };
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
assert.equal(note.contents, "my note");
|
||||
assert.equal(note.diskContents, "external edit");
|
||||
assert.equal(docs.active!.contents, "my script");
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("an autosave failure preserves edits, saves other files, and can be retried", async () => {
|
||||
const { docs, io, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
const note = docs.active!;
|
||||
docs.edit(note.id, "my note");
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "my script");
|
||||
const write = io.write;
|
||||
io.write = async (...args) => {
|
||||
if (args[0] === "note.md") throw new Error("disk full");
|
||||
await write(...args);
|
||||
};
|
||||
const result = await docs.autosave();
|
||||
assert.deepEqual(result.saved, ["script.py"]);
|
||||
assert.equal(result.failed[0].path, "note.md");
|
||||
assert.match(String(result.failed[0].error), /disk full/);
|
||||
assert.equal(note.saved, "original");
|
||||
assert.equal(note.contents, "my note");
|
||||
assert.equal(disk.get("script.py"), "my script");
|
||||
io.write = write;
|
||||
await docs.autosave();
|
||||
assert.equal(disk.get("note.md"), "my note");
|
||||
assert.equal(docs.dirty, false);
|
||||
});
|
||||
|
||||
test("autosave cannot overwrite an external edit even before the watcher refreshes", async () => {
|
||||
const { docs, disk } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
docs.edit(docs.active!.id, "my note");
|
||||
disk.set("note.md", "external edit");
|
||||
const result = await docs.autosave();
|
||||
assert.equal(result.failed.length, 1);
|
||||
assert.equal(disk.get("note.md"), "external edit");
|
||||
assert.equal(docs.active!.contents, "my note");
|
||||
assert.equal(docs.dirty, true);
|
||||
});
|
||||
|
||||
test("closed documents and disposed workspaces are not autosaved", async () => {
|
||||
const { docs, io } = setup();
|
||||
await docs.open(entry("note.md"));
|
||||
docs.edit(docs.active!.id, "discarded");
|
||||
docs.close("note.md");
|
||||
io.write = async () => { assert.fail("discarded edits must not be written"); };
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
await docs.open(entry("script.py"));
|
||||
docs.edit(docs.active!.id, "disposed");
|
||||
docs.dispose();
|
||||
assert.deepEqual(await docs.autosave(), { saved: [], failed: [] });
|
||||
});
|
||||
@@ -1,149 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,181 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,142 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,152 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,129 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,209 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,33 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { documentLinks, documentLinkAt } from "../src/lib/editor/documentLinks.ts";
|
||||
|
||||
test("document links keep complete source ranges and decode Markdown destinations", () => {
|
||||
const source = '[Local](<notes/two words.md> "Title") and [Web](https://example.com/a_(b)) and [[Another note|Alias]]';
|
||||
const links = documentLinks(source);
|
||||
assert.deepEqual(links.map(link => [link.kind, link.target]), [["md", "notes/two words.md"], ["md", "https://example.com/a_(b)"], ["wiki", "Another note"]]);
|
||||
for (const link of links) {
|
||||
assert.equal(documentLinkAt(source, link.from + 2)?.target, link.target);
|
||||
assert.equal(documentLinkAt(source, link.to - 1)?.target, link.target);
|
||||
}
|
||||
});
|
||||
|
||||
test("literal code and images cannot become document links", () => {
|
||||
const source = ' `https://example.com`\n\n```md\n[Hidden](hidden.md)\n[[Hidden]]\n```\n\n[Open](open.md)';
|
||||
assert.deepEqual(documentLinks(source).map(link => link.target), ["open.md"]);
|
||||
});
|
||||
|
||||
test("bare and angle links omit prose punctuation and preserve balanced parentheses", () => {
|
||||
const source = 'Go to https://example.com/a_(b). Next (<https://example.org>). Mail <mailto:[email protected]>.';
|
||||
assert.deepEqual(documentLinks(source).map(link => link.target), ["https://example.com/a_(b)", "https://example.org", "mailto:[email protected]"]);
|
||||
});
|
||||
|
||||
test("edit link selects only its destination, preserving labels, titles, brackets, and spacing", () => {
|
||||
const source = '[Local](<notes/two words.md> "Title") and [Web](https://example.com/a_\\(b\\)) and [[ Another note#Heading |Alias]] and <https://example.org>.';
|
||||
const links = documentLinks(source);
|
||||
assert.deepEqual(links.map(link => source.slice(link.targetFrom, link.targetTo)), ["notes/two words.md", "https://example.com/a_\\(b\\)", "Another note#Heading", "https://example.org"]);
|
||||
});
|
||||
|
||||
test("wiki image embeds do not expose document actions", () => {
|
||||
assert.deepEqual(documentLinks('![[image.png]] [[note|label]]').map(link => link.target), ["note"]);
|
||||
});
|
||||
@@ -1,182 +0,0 @@
|
||||
// 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(); }
|
||||
␍
|
||||
@@ -1,33 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import MarkdownIt from "markdown-it";
|
||||
import { footnotes, renderFootnotes } from "../src/lib/editor/footnotes.ts";
|
||||
|
||||
function render(source: string) {
|
||||
const markdown = new MarkdownIt({ html: false }).use(footnotes);
|
||||
const env = {};
|
||||
return markdown.render(source, env) + renderFootnotes(markdown, env);
|
||||
}
|
||||
|
||||
test("footnotes use first-reference order, repeated backlinks, and rich multiline definitions", () => {
|
||||
const html = render("First[^b], then[^a], again[^b].\n\n[^a]: Second definition\n[^b]: **Bold** text\n continued\n\n Second paragraph.\n");
|
||||
assert.match(html, /id="rs-fnref-1-1"/);
|
||||
assert.match(html, /id="rs-fnref-1-2"/);
|
||||
assert.match(html, /<strong>Bold<\/strong> text\ncontinued/);
|
||||
assert.match(html, /<p>Second paragraph\.<\/p>/);
|
||||
assert.ok(html.indexOf('<li id="rs-fn-1"') < html.indexOf('<li id="rs-fn-2"'));
|
||||
assert.match(html, /href="#rs-fnref-1-2"/);
|
||||
});
|
||||
|
||||
test("undefined, escaped, inline-code, fenced-code, and indented-code references stay literal", () => {
|
||||
const html = render("Missing[^missing]. Escaped\\[^n]. `[^n]`\n\n```md\n[^n]\n```\n\n [^n]\n\n[^n]: Unused\n");
|
||||
assert.doesNotMatch(html, /md-footnotes|md-footnote-ref/);
|
||||
assert.match(html, /Missing\[\^missing\]/);
|
||||
});
|
||||
|
||||
test("footnotes keep HTML escaped and support CRLF", () => {
|
||||
const html = render("Body[^x]\r\n\r\n[^x]: <script>alert(1)</script>\r\n");
|
||||
assert.match(html, /<script>/);
|
||||
assert.doesNotMatch(html, /<script>/);
|
||||
assert.match(html, /Footnote 1/);
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,181 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,155 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,138 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
||||
function fixture() {
|
||||
let writes = 0;
|
||||
const session = new ExternalSession("org.test.demo", {
|
||||
workspace: { list: async () => [], read: async () => "original", write: async () => { writes++; } },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {});
|
||||
return { session, writes: () => writes };
|
||||
}
|
||||
|
||||
test("native Markdown discovery remains optional and is revoked on disable", async () => {
|
||||
let api!: PluginApi;
|
||||
let scans = 0;
|
||||
const session = new ExternalSession("org.test.scan", {
|
||||
workspace: { list: async () => [], listMarkdown: async () => { scans++; return ["Notes/task.md"]; }, read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.deepEqual(await api.workspace.listMarkdown!(), ["Notes/task.md"]);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.listMarkdown!(), /disabled/);
|
||||
assert.equal(scans, 1);
|
||||
const old = fixture().session;
|
||||
await old.start({ activate(value) { assert.equal(value.workspace.listMarkdown, undefined); } });
|
||||
await old.stop();
|
||||
});
|
||||
test("external commands run and all host access stops before cleanup", async () => {
|
||||
const { session, writes } = fixture(); let api!: PluginApi; let ran = 0;
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.registerCommand({ id: "run", title: "Run", run: () => { ran++; } });
|
||||
api.registerView({ id: "view", title: "View", mount: () => {} });
|
||||
api.onDispose(() => { assert(api.signal.aborted); assert.throws(() => api.workspace.read("x"), /disabled/); });
|
||||
} });
|
||||
await session.run("run"); assert.equal(ran, 1);
|
||||
assert.throws(() => api.workspace.write("x", "new", undefined!), /original/);
|
||||
await api.workspace.write("x", "new", "original"); assert.equal(writes(), 1);
|
||||
await session.stop(); assert.equal(session.commands.size, 0); assert.equal(session.views.size, 0);
|
||||
await assert.rejects(session.run("run"), /disabled/);
|
||||
assert.throws(() => api.settings.read(), /disabled/);
|
||||
});
|
||||
test("async activation cleanup runs once even when disabled before activation finishes", async () => {
|
||||
const { session } = fixture(); let resolve!: () => void; let cleaned = 0;
|
||||
const gate = new Promise<void>(done => resolve = done);
|
||||
const start = session.start({ async activate() { await gate; return () => { cleaned++; }; } });
|
||||
await Promise.resolve();
|
||||
const stopped = session.stop(); resolve();
|
||||
await Promise.all([start, stopped]); await session.stop(); assert.equal(cleaned, 1);
|
||||
});
|
||||
test("failed cleanup does not skip other callbacks and blocks successful shutdown", async () => {
|
||||
const { session } = fixture(); const calls: number[] = [];
|
||||
await session.start({ activate(api) {
|
||||
api.onDispose(() => { calls.push(1); });
|
||||
api.onDispose(() => { calls.push(2); throw new Error("Cleanup failed"); });
|
||||
api.onDispose(() => { calls.push(3); });
|
||||
} });
|
||||
await assert.rejects(session.stop(), /Cleanup failed/); assert.deepEqual(calls, [3, 2, 1]);
|
||||
});
|
||||
test("duplicate contribution IDs fail and partial activation can be cleaned", async () => {
|
||||
const { session } = fixture(); let cleaned = false;
|
||||
await assert.rejects(session.start({ activate(api) {
|
||||
api.onDispose(() => { cleaned = true; });
|
||||
api.registerCommand({ id: "run", title: "Run", run() {} });
|
||||
api.registerCommand({ id: "run", title: "Again", run() {} });
|
||||
} }), /duplicate/);
|
||||
await session.stop(); assert(cleaned); assert.equal(session.commands.size, 0);
|
||||
});
|
||||
test("view disposal is idempotent and participates in plugin shutdown", async () => {
|
||||
const { session } = fixture(); let cleaned = 0; let cleared = 0;
|
||||
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => () => { cleaned++; } }); } });
|
||||
const cleanup = await session.mount("view", { replaceChildren() { cleared++; } } as unknown as HTMLElement);
|
||||
await session.stop(); await cleanup(); assert.equal(cleaned, 1); assert.equal(cleared, 1);
|
||||
});
|
||||
test("shutdown waits for view cleanup that already started when the view closed", async () => {
|
||||
const { session } = fixture(); let done!: () => void; let cleaned = false;
|
||||
const gate = new Promise<void>(resolve => done = resolve);
|
||||
await session.start({ activate(api) { api.registerView({ id: "view", title: "View", mount: () => async () => { await gate; cleaned = true; } }); } });
|
||||
const cleanup = await session.mount("view", { replaceChildren() {} } as unknown as HTMLElement);
|
||||
const closing = cleanup(); await Promise.resolve();
|
||||
let stopped = false; const stopping = session.stop().then(() => { stopped = true; });
|
||||
await Promise.resolve(); await Promise.resolve(); assert.equal(stopped, false);
|
||||
done(); await Promise.all([closing, stopping]); assert(cleaned);
|
||||
});
|
||||
test("cleanup returned by late activation still blocks shutdown when it fails", async () => {
|
||||
const { session } = fixture(); let done!: () => void;
|
||||
const gate = new Promise<void>(resolve => done = resolve);
|
||||
const starting = session.start({ async activate() { await gate; return () => { throw new Error("Late cleanup failed"); }; } });
|
||||
await Promise.resolve(); const stopping = session.stop(); done();
|
||||
await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/);
|
||||
});
|
||||
|
||||
test("batch workspace reads remain optional and stop when the plugin is disabled", async () => {
|
||||
let api!: PluginApi;
|
||||
let calls = 0;
|
||||
const rows = [{ path: "Card.md", source: "Card source" }, { path: "Missing.md", error: "File not found" }];
|
||||
const session = new ExternalSession("org.test.batch", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {},
|
||||
readMany: async paths => { calls++; assert.deepEqual(paths, ["Card.md", "Missing.md"]); return rows; } },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.deepEqual(await api.workspace.readMany!(["Card.md", "Missing.md"]), rows);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.readMany!(["Card.md"]), /disabled/);
|
||||
assert.equal(calls, 1);
|
||||
const old = fixture().session;
|
||||
await old.start({ activate(value) { assert.equal(value.workspace.readMany, undefined); } });
|
||||
await old.stop();
|
||||
});
|
||||
|
||||
test("view launch selects a default while explicit opens preserve their target", async () => {
|
||||
const opened: string[] = [];
|
||||
let api!: PluginApi;
|
||||
const session = new ExternalSession("org.test.launch", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, id => { opened.push(id); });
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.registerView({ id: "all", title: "All", launch: async () => { api.openView("board"); }, mount() {} });
|
||||
api.registerView({ id: "board", title: "Board", mount() {} });
|
||||
assert.throws(() => api.registerView({ id: "invalid", title: "Invalid", launch: true as never, mount() {} }), /launch handler/);
|
||||
} });
|
||||
await session.launch("all");
|
||||
api.openView("all");
|
||||
await session.launch("board");
|
||||
assert.deepEqual(opened, ["board", "all", "board"]);
|
||||
await assert.rejects(session.launch("missing"), /Unknown plugin view/);
|
||||
await session.stop();
|
||||
await assert.rejects(session.launch("all"), /disabled/);
|
||||
});
|
||||
@@ -1,167 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,28 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { documentHeadings, headingLinkLine, linkFragment } from "../src/lib/workspace/headingLinks.ts";
|
||||
|
||||
test("section links decode fragments without changing the file path", () => {
|
||||
assert.equal(linkFragment("notes/a%23b.md#Caf%C3%A9%20setup"), "Café setup");
|
||||
assert.equal(linkFragment("#literal%"), "literal%");
|
||||
assert.equal(linkFragment("a.md"), null);
|
||||
assert.equal(headingLinkLine("# Title", ""), 1);
|
||||
});
|
||||
|
||||
test("headings use rendered text, Unicode, and unique slugs", () => {
|
||||
const source = "# **Windows** setup!\n\n## Café `setup`\n\n## Windows setup!\n\n## Windows setup-1\n\n## Windows setup!\n";
|
||||
assert.deepEqual(documentHeadings(source).map(({ slug }) => slug),
|
||||
["windows-setup", "café-setup", "windows-setup-1", "windows-setup-1-1", "windows-setup-2"]);
|
||||
assert.equal(headingLinkLine(source, "windows-setup-2"), 9);
|
||||
assert.equal(headingLinkLine(source, "Café setup"), 3);
|
||||
assert.equal(headingLinkLine(source, "missing"), null);
|
||||
});
|
||||
|
||||
test("section lines exclude properties and code, and include Setext headings", () => {
|
||||
const source = "---\r\ntitle: Test\r\n---\r\n\r\n```md\r\n# Fake\r\n```\r\n\r\nInstall\r\n=======\r\n\r\n## Real ###\r\n";
|
||||
assert.deepEqual(documentHeadings(source), [
|
||||
{ text: "Install", slug: "install", line: 9 },
|
||||
{ text: "Real", slug: "real", line: 12 },
|
||||
]);
|
||||
assert.equal(headingLinkLine(source, "fake"), null);
|
||||
});
|
||||
@@ -1,15 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { fenceOpenText, headingMarkText } from "../src/lib/editor/headingMarks.ts";
|
||||
|
||||
test("heading marks match the heading level", () => {
|
||||
assert.equal(headingMarkText(1), "#");
|
||||
assert.equal(headingMarkText(3), "###");
|
||||
assert.equal(headingMarkText(6), "######");
|
||||
});
|
||||
|
||||
test("fence open marks include the language", () => {
|
||||
assert.equal(fenceOpenText(""), "```");
|
||||
assert.equal(fenceOpenText("js"), "```js");
|
||||
assert.equal(fenceOpenText(" pp "), "```pp");
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,100 +0,0 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { resolve, join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.connectOverCDP(process.env.NAVIGATION_NATIVE_CDP || 'http://127.0.0.1:9236');
|
||||
const context = browser.contexts()[0];
|
||||
const page = context.pages().find(page => new URL(page.url()).pathname === '/' && !new URL(page.url()).search);
|
||||
assert.ok(page, 'The isolated main window must be open.');
|
||||
page.setDefaultTimeout(20000);
|
||||
const output = resolve('output/host-navigation-pass3-native');
|
||||
const workspace = join(tmpdir(), 'runestone-pass3-native-workspace');
|
||||
const results = {};
|
||||
let detached;
|
||||
try {
|
||||
const identity = await page.evaluate(async () => (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
|
||||
assert.match(identity, /[\\/]com\.runestone\.pass3-test[\\/]?$/);
|
||||
results.identity = identity;
|
||||
await mkdir(output, { recursive: true });
|
||||
await mkdir(join(workspace, 'folder', 'nested'), { recursive: true });
|
||||
await mkdir(join(workspace, 'other'), { recursive: true });
|
||||
await writeFile(join(workspace, 'folder', 'nested', 'note.md'), '# Native note\n\nText for transfer.\n');
|
||||
await writeFile(join(workspace, 'other', 'keep.md'), '# Keep');
|
||||
await page.evaluate(async path => {
|
||||
await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('workspace_open', { path });
|
||||
localStorage.setItem('runestone.workbenchLayout', JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 260, rightWidth: 240, leftView: 'files' }));
|
||||
}, workspace);
|
||||
await page.reload();
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
|
||||
await row('folder/nested/note.md').click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Rename', exact: true }).click();
|
||||
await page.locator('.tree input').fill('renamed.md'); await page.locator('.tree input').press('Enter');
|
||||
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']) assert.equal(await row(path).getAttribute('aria-expanded'), 'true');
|
||||
results.renameUndoPreservesExpandedFolders = true;
|
||||
await row('folder/nested/note.md').click();
|
||||
await page.getByRole('tab', { name: /note.md/ }).waitFor();
|
||||
await page.getByText('Text for transfer.', { exact: true }).waitFor();
|
||||
const savedLayout = await page.evaluate(() => localStorage.getItem('runestone.workbenchLayout'));
|
||||
const pending = context.waitForEvent('page');
|
||||
await page.getByRole('tab', { name: /note.md/ }).click({ button: 'right' });
|
||||
await page.getByRole('menuitem', { name: 'Open in new window', exact: true }).click();
|
||||
detached = await pending;
|
||||
await detached.getByRole('tab', { name: /note.md/ }).waitFor();
|
||||
await detached.evaluate(async () => (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().minimize());
|
||||
await detached.getByText('Text for transfer.', { exact: true }).waitFor();
|
||||
assert.ok(detached.url().includes('tabTransfer='));
|
||||
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
|
||||
await page.getByRole('tab', { name: /note.md/ }).waitFor({ state: 'detached' });
|
||||
const sourceClosed = await page.getByRole('tab', { name: /note.md/ }).count() === 0;
|
||||
await detached.getByRole('button', { name: 'Show outline', exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), savedLayout);
|
||||
await detached.getByRole('button', { name: 'Hide outline', exact: true }).click();
|
||||
results.nativeTransfer = { sourceClosed, columnsHidden: true, savedLayoutPreserved: true };
|
||||
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.screenshot({ path: join(output, `detached-${mode}.png`) });
|
||||
}
|
||||
results.imageJsonIpc = await page.evaluate(async () => {
|
||||
const { invoke } = await import('/node_modules/@tauri-apps/api/core.js');
|
||||
const bytes = 50 * 1024 * 1024;
|
||||
const pixel = Uint8Array.from(atob('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII='), char => char.charCodeAt(0));
|
||||
const blob = new Blob([pixel, new Uint8Array(bytes - pixel.length)], { type: 'image/png' });
|
||||
const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = reject; reader.readAsDataURL(blob); });
|
||||
const contents = JSON.stringify({ schema: 1, data });
|
||||
const start = performance.now();
|
||||
await invoke('workspace_write', { rel: '.runestone/pm/images/native-50mib.json', contents });
|
||||
const written = performance.now();
|
||||
const read = await invoke('workspace_read', { rel: '.runestone/pm/images/native-50mib.json' });
|
||||
return { bytes, jsonLength: contents.length, matches: read === contents, writeMs: Math.round(written - start), readMs: Math.round(performance.now() - written) };
|
||||
});
|
||||
assert.equal(results.imageJsonIpc.matches, true);
|
||||
await page.goto('http://127.0.0.1:5186/?settingsWindow=true');
|
||||
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
|
||||
const largeImage = Buffer.concat([pixel, Buffer.alloc(1_900_000 - pixel.length)]);
|
||||
await page.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'native-large.png', mimeType: 'image/png', buffer: largeImage });
|
||||
await page.waitForFunction(() => !!JSON.parse(localStorage.getItem('runestone.appearance'))?.newTabBackground?.imageId);
|
||||
await page.goto('http://127.0.0.1:5186/');
|
||||
await page.locator('.empty').waitFor();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
await page.reload(); await page.locator('.empty').waitFor();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
results.largeBackground = { bytes: largeImage.length, renderedAfterReload: true };
|
||||
await page.screenshot({ path: join(output, 'large-background.png') });
|
||||
await writeFile(join(output, 'results.json'), JSON.stringify(results, null, 2));
|
||||
console.log(JSON.stringify(results));
|
||||
} catch (error) {
|
||||
await writeFile(join(output, 'partial-results.json'), JSON.stringify(results, null, 2));
|
||||
console.error({ error: String(error), main: await page.locator('body').innerText().catch(() => ''), detached: detached && !detached.isClosed() ? await detached.locator('body').innerText().catch(() => '') : null });
|
||||
throw error;
|
||||
} finally {
|
||||
if (detached && !detached.isClosed()) await detached.evaluate(async () => (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().destroy()).catch(() => {});
|
||||
await browser.close();
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,165 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,17 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts";
|
||||
|
||||
test("Windows HTML clipboard fragment comments do not become table content", () => {
|
||||
const html = '<html><body><!--StartFragment--><table><tr><th>Ticker</th><th>Name</th></tr><tr><td>ADBE.US</td><td>Adobe</td></tr><tr><td>ADSK.US</td><td>Autodesk</td></tr></table><!--EndFragment--></body></html>';
|
||||
assert.equal(htmlToMarkdown(html), '| Ticker | Name |\n| --- | --- |\n| ADBE.US | Adobe |\n| ADSK.US | Autodesk |');
|
||||
});
|
||||
|
||||
test("comments inside cells preserve adjacent text and formatting", () => {
|
||||
const html = '<table><tr><th>Notes</th></tr><tr><td>First<!-- multi-line\n <b>comment</b> --> part<br><strong>Second</strong></td></tr></table>';
|
||||
assert.equal(htmlToMarkdown(html), '| Notes |\n| --- |\n| First part<br>**Second** |');
|
||||
});
|
||||
|
||||
test("escaped comment text remains user content", () => {
|
||||
assert.equal(htmlToMarkdown('<p><!--Example--></p>'), '<!--Example-->');
|
||||
});
|
||||
@@ -1,75 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { catalogs, messageRows } from '../src/lib/i18n/messages.ts';
|
||||
import { get } from 'svelte/store';
|
||||
import { LANGUAGE_KEY, locale, normalizeLocale, setLocale, t, translate, syncLocale } from '../src/lib/i18n/index.ts';
|
||||
test('Every catalog entry has all translations and preserves its placeholders', () => {
|
||||
const seen = new Set<string>();
|
||||
for (const [english, ...translations] of messageRows) {
|
||||
assert(!seen.has(english), `Duplicate message: ${english}`); seen.add(english);
|
||||
const placeholders = (value: string) => [...value.matchAll(/\{(\w+)\}/g)].map(match => match[1]).sort();
|
||||
for (const value of translations) {
|
||||
assert(value.trim(), `Empty translation: ${english}`);
|
||||
assert.deepEqual(placeholders(value), placeholders(english), english);
|
||||
}
|
||||
}
|
||||
assert.equal(Object.keys(catalogs.fr).length, messageRows.length);
|
||||
});
|
||||
test('Locale parsing rejects unsupported values and interpolation preserves user text', () => {
|
||||
assert.equal(normalizeLocale('ja'), 'ja');
|
||||
assert.equal(normalizeLocale('zh-CN'), 'zh-CN');
|
||||
for (const value of [null, undefined, 'constructor', 'de', [], {}]) assert.equal(normalizeLocale(value), 'en');
|
||||
assert.equal(translate('fr', 'Missing source text'), 'Missing source text');
|
||||
assert.equal(translate('ja', 'Close {name}', { name: '<script>例.md</script>' }), '<script>例.md</script>を閉じる');
|
||||
});
|
||||
test('Language saves before reactive changes and syncs across windows', () => {
|
||||
const stored = new Map<string, string>();
|
||||
const events = new Map<string, Function>();
|
||||
const priorStorage = globalThis.localStorage, priorWindow = globalThis.window, priorDocument = globalThis.document;
|
||||
try {
|
||||
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as Storage;
|
||||
globalThis.window = { addEventListener: (key: string, handler: Function) => events.set(key, handler), removeEventListener: (key: string) => events.delete(key) } as unknown as Window & typeof globalThis;
|
||||
globalThis.document = { documentElement: { lang: '' } } as unknown as Document;
|
||||
const stop = syncLocale();
|
||||
setLocale('fr');
|
||||
assert.equal(stored.get(LANGUAGE_KEY), 'fr');
|
||||
assert.equal(get(t)('Settings'), 'Paramètres');
|
||||
assert.equal(document.documentElement.lang, 'fr');
|
||||
stored.set(LANGUAGE_KEY, 'zh-CN'); events.get('storage')!({ key: LANGUAGE_KEY });
|
||||
assert.equal(get(locale), 'zh-CN'); assert.equal(get(t)('Settings'), '设置');
|
||||
globalThis.localStorage.setItem = () => { throw new Error('Storage unavailable'); };
|
||||
assert.throws(() => setLocale('ja'));
|
||||
assert.equal(get(locale), 'zh-CN');
|
||||
stop(); assert.equal(events.size, 0);
|
||||
} finally { globalThis.localStorage = priorStorage; globalThis.window = priorWindow; globalThis.document = priorDocument; locale.set('en'); }
|
||||
});
|
||||
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import ts from 'typescript';
|
||||
function sourceFiles(dir: string): string[] {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? sourceFiles(path.join(dir, entry.name)) : /\.(ts|svelte)$/.test(entry.name) ? [path.join(dir, entry.name)] : []);
|
||||
}
|
||||
test('Every static host translation call has all three catalog entries', () => {
|
||||
const missing: string[] = [];
|
||||
for (const file of sourceFiles('src/lib')) {
|
||||
const source = readFileSync(file, 'utf8');
|
||||
for (const match of source.matchAll(/(?:\$t|\btr)\(\s*((?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'))/g)) {
|
||||
const parsed = ts.createSourceFile('literal.ts', match[1], ts.ScriptTarget.Latest, true);
|
||||
const statement = parsed.statements[0];
|
||||
const value = ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression) ? statement.expression.text : '';
|
||||
if (value && !Object.hasOwn(catalogs.fr, value)) missing.push(`${file}: ${value}`);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
test('Keyboard identifiers remain untranslated in event handlers', () => {
|
||||
const failures: string[] = [];
|
||||
for (const file of sourceFiles('src/lib')) {
|
||||
const source = readFileSync(file, 'utf8');
|
||||
for (const line of source.split(/\r?\n/)) {
|
||||
if (/event\.(?:key|code)\s*[!=]==?\s*(?:tr|\$t)\(/.test(line) || /(?:tr|\$t)\([^\n]+\]\.(?:includes|indexOf)\(event\.(?:key|code)/.test(line)) failures.push(`${file}: ${line.trim()}`);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(failures, []);
|
||||
});
|
||||
@@ -1,209 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,250 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,55 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { attachmentRel, hasFileDrag, imageFiles, imageInsertion, workspaceImageLink } from "../src/lib/workspace/media.ts";
|
||||
import { imageSource, editImageSource, imageSourceRanges } from "../src/lib/editor/imageSource.ts";
|
||||
import { imageDrops, trackImageDrop } from "../src/lib/editor/imageDrop.ts";
|
||||
|
||||
test("same-name image imports receive distinct safe attachment paths", () => {
|
||||
const paths = new Set(Array.from({ length: 100 }, () => attachmentRel("photo (1).PNG")));
|
||||
assert.equal(paths.size, 100);
|
||||
assert.ok([...paths].every(path => /^attachments\/[\w.-]+\.PNG$/.test(path)));
|
||||
});
|
||||
|
||||
test("protected file drags and files without MIME metadata are recognized", () => {
|
||||
assert.equal(hasFileDrag({ types: ["Files"], files: [] } as unknown as DataTransfer), true);
|
||||
assert.equal(hasFileDrag({ types: ["text/plain"] } as unknown as DataTransfer), false);
|
||||
const files = [{ name: "PHOTO.PNG", type: "" }, { name: "note.md", type: "text/plain" }];
|
||||
assert.deepEqual(imageFiles({ files } as unknown as DataTransfer), [files[0]]);
|
||||
});
|
||||
|
||||
test("image batches form independent Markdown blocks without extra blank lines", () => {
|
||||
assert.equal(imageInsertion("beforeafter", 6, 6, ["", ""]), "\n\n\n\n\n\n");
|
||||
assert.equal(imageInsertion("before\n\nafter", 8, 8, [""]), "\n\n");
|
||||
assert.equal(imageInsertion("before\r\n\r\nafter", 10, 10, [""]), "\n\n");
|
||||
});
|
||||
|
||||
test("pending image drops follow intervening edits instead of the current caret", () => {
|
||||
let state = EditorState.create({ doc: "before\nafter", extensions: [imageDrops] });
|
||||
const id = Symbol();
|
||||
state = state.update({ effects: trackImageDrop.of({ id, from: 7, to: 7 }) }).state;
|
||||
state = state.update({ changes: { from: 0, insert: "new\n" }, selection: { anchor: 0 } }).state;
|
||||
assert.deepEqual(state.field(imageDrops).get(id), { from: 11, to: 11 });
|
||||
});
|
||||
|
||||
test("navigator image links are relative and encode Markdown and URL punctuation", () => {
|
||||
assert.equal(workspaceImageLink("notes/drafts/note.md", "images/a (#1).png"), "");
|
||||
assert.equal(workspaceImageLink("notes/note.md", "notes/photo.png"), "");
|
||||
assert.equal(workspaceImageLink("note.md", "日本語/photo%.png"), "");
|
||||
});
|
||||
|
||||
test("image source is explicitly activated, tracks edits, and hides on leaving", () => {
|
||||
let state = EditorState.create({ doc: "\n\nText", extensions: [imageSource] });
|
||||
state = state.update({ selection: { anchor: 0, head: 10 } }).state;
|
||||
assert.equal(state.field(imageSource), null);
|
||||
state = state.update({ effects: editImageSource.of({ from: 0, to: 10 }) }).state;
|
||||
state = state.update({ changes: { from: 2, insert: "Alt" } }).state;
|
||||
assert.deepEqual(state.field(imageSource), { from: 0, to: 13 });
|
||||
state = state.update({ selection: { anchor: state.doc.length } }).state;
|
||||
assert.equal(state.field(imageSource), null);
|
||||
});
|
||||
|
||||
test("image ranges distinguish embeds from code and retain reference and wiki syntax", () => {
|
||||
const source = "``\n\nText  and ![[a b.png|Photo]]\n\n![ref][photo]\n\n[photo]: x.png\n\n```\n\n```";
|
||||
assert.deepEqual(imageSourceRanges(source).map(range => source.slice(range.from, range.to)), ["", "![[a b.png|Photo]]", "![ref][photo]"]);
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { noteFormats } from "../src/lib/editor/noteFormats.ts";
|
||||
import { renderMarkdownHtml } from "../src/lib/workspace/noteHtml.ts";
|
||||
|
||||
const parser = markdown({ base: markdownLanguage, extensions: [noteFormats] }).language.parser;
|
||||
const render = (source: string) => renderMarkdownHtml(source, new Map());
|
||||
function mathNodes(source: string) {
|
||||
const nodes: string[] = [];
|
||||
parser.parse(source).iterate({ enter(node) {
|
||||
if (node.name === "NoteMath") nodes.push(source.slice(node.from, node.to));
|
||||
} });
|
||||
return nodes;
|
||||
}
|
||||
|
||||
test("dollar amounts stay literal in writing, reading, and table cells", () => {
|
||||
for (const source of [
|
||||
"$10", "$10 and $20", "$1,234.56 plus $78.90", "$10-$20", "$0.25-$.50",
|
||||
"US$10 / CA$20", "$ 10 and $ 20", "$-10 and $-20", "($10) and ($20)",
|
||||
"$10\n$20", "$10\r\n$20", "$10 **income**, $20 **cost**",
|
||||
]) {
|
||||
assert.deepEqual(mathNodes(source), [], source);
|
||||
const html = render(source);
|
||||
assert.doesNotMatch(html, /md-inline-math/, source);
|
||||
assert.equal((html.match(/\$/g) || []).length, (source.match(/\$/g) || []).length, source);
|
||||
assert.doesNotMatch(render(`| Amounts |\n| --- |\n| ${source.replace(/\r?\n/g, "<br>")} |`), /md-inline-math/, source);
|
||||
}
|
||||
});
|
||||
|
||||
test("inline math still works next to dollar amounts", () => {
|
||||
for (const expression of ["$x^2$", "$2 + 2$", "$x + y$", String.raw`$\frac{1}{2}$`, String.raw`$x + \$5$`]) {
|
||||
const source = `$10 and $20, then ${expression}, then $30 and $40.`;
|
||||
assert.deepEqual(mathNodes(source), [expression], source);
|
||||
assert.equal((render(source).match(/md-inline-math/g) || []).length, 1, source);
|
||||
assert.match(render(source), /\$10 and \$20/);
|
||||
assert.match(render(source), /\$30 and \$40/);
|
||||
}
|
||||
});
|
||||
|
||||
test("escaped, incomplete, spaced, multiline, and double delimiters do not create inline math", () => {
|
||||
for (const source of [String.raw`\$x\$`, "$x", "$ x$", "$x $", "$x\ny$", "$$x$$", "$$\nx\n$$", "`$x$`", "```\n$x$\n```", "$x$2"]) {
|
||||
assert.deepEqual(mathNodes(source), [], source);
|
||||
assert.doesNotMatch(render(source), /md-inline-math/, source);
|
||||
}
|
||||
});
|
||||
|
||||
test("highlight and comment formats keep their existing behavior", () => {
|
||||
const source = "==**highlight**== %%comment%%";
|
||||
const tree = parser.parse(source).toString();
|
||||
assert.match(tree, /NoteHighlight/);
|
||||
assert.match(tree, /StrongEmphasis/);
|
||||
assert.match(tree, /NoteComment/);
|
||||
assert.match(render(source), /<mark><strong>highlight<\/strong><\/mark>/);
|
||||
assert.match(render(source), /md-inline-comment/);
|
||||
});
|
||||
@@ -1,77 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtemp, readFile, writeFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { releaseVersion, nextHotfix, compareReleases } from './releaseVersion.mjs';
|
||||
|
||||
const ordering = ['0.1.22z', '0.1.23', '0.1.23a', '0.1.23b', '0.1.23c', '0.1.23z', '0.1.23aa', '0.1.23ab', '0.1.23zz', '0.1.23aaa', '0.1.24'];
|
||||
|
||||
test('hotfix versions retain their release identity and advance in letter order', () => {
|
||||
assert.deepEqual(releaseVersion('0.1.23a'), { version: '0.1.23a', base: '0.1.23', suffix: 'a', revision: 1, toolchain: '0.1.23+1', windows: '0.1.23.1' });
|
||||
for (const [before, after] of [['0.1.23', '0.1.23a'], ['0.1.23a', '0.1.23b'], ['0.1.23b', '0.1.23c'], ['0.1.23z', '0.1.23aa'], ['0.1.23aa', '0.1.23ab'], ['0.1.23zz', '0.1.23aaa']]) assert.equal(nextHotfix(before), after);
|
||||
for (const version of ['0.1.23A', '0.1.23a1', '0.1.23-a', '0.1.23+1', '0.1', '0.1.23aaaaa', '0.1.65536']) assert.throws(() => releaseVersion(version));
|
||||
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) assert.equal(compareReleases(ordering[i], ordering[j]), Math.sign(i - j));
|
||||
});
|
||||
|
||||
const makensis = path.join(process.env.LOCALAPPDATA ?? '', 'tauri/NSIS/makensis.exe');
|
||||
const nsisSkip = process.platform !== 'win32' ? 'Windows only' : existsSync(makensis) ? false : 'the NSIS compiler is missing; run pnpm build:installer once to download it';
|
||||
|
||||
test('the native NSIS comparator blocks older hotfixes and permits reinstall', { skip: nsisSkip }, async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), 'runestone-installer-version-'));
|
||||
try {
|
||||
const checks: string[] = [];
|
||||
checks.push('StrCpy $0 "keep0"\nStrCpy $1 "keep1"\nPush "0.1.23a"\nPush "0.1.23"\nCall RuneStoneCompareVersions\nPop $2\nStrCmp $0 "keep0" saved0\nSetErrorLevel 1\nQuit\nsaved0:\nStrCmp $1 "keep1" saved1\nSetErrorLevel 1\nQuit\nsaved1:');
|
||||
let index = 0;
|
||||
for (let i = 0; i < ordering.length; i++) for (let j = 0; j < ordering.length; j++) {
|
||||
checks.push(`Push "${ordering[i]}"\nPush "${ordering[j]}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 ${Math.sign(i - j)} check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
|
||||
}
|
||||
for (const version of ['0.1.23A', '0.1.23a1', '0.1.a', '0.1.23-rc', '0.1.23aaaaa', '4294967296.0.0']) {
|
||||
checks.push(`Push "0.1.23a"\nPush "${version}"\nCall RuneStoneCompareVersions\nPop $0\nStrCmp $0 -1 check_${index}\nSetErrorLevel 1\nQuit\ncheck_${index++}:`);
|
||||
}
|
||||
const executable = path.join(root, 'compare.exe');
|
||||
const source = `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone version check"\nOutFile "${executable}"\n!include LogicLib.nsh\n!include WordFunc.nsh\n!include "${path.resolve('src-tauri/windows/versionCompare.nsh')}"\nSection\n${checks.join('\n')}\nSetErrorLevel 0\nSectionEnd\n`;
|
||||
const script = path.join(root, 'compare.nsi');
|
||||
await writeFile(script, source);
|
||||
const compiler = makensis;
|
||||
const built = spawnSync(compiler, ['/V2', script], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(built.status, 0, built.stdout + built.stderr);
|
||||
const checked = spawnSync(executable, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(checked.status, 0, checked.stdout + checked.stderr);
|
||||
const patched = spawnSync('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.resolve('scripts/setWindowsVersion.ps1'), '-Path', executable, '-Version', '0.1.23a', '-NumericVersion', '0.1.23.1'], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(patched.status, 0, patched.stdout + patched.stderr);
|
||||
assert.match(patched.stdout, /0\.1\.23a/);
|
||||
// Git can check the template out with CRLF line endings on Windows.
|
||||
const template = (await readFile('src-tauri/windows/installer.nsi', 'utf8')).replaceAll('\r\n', '\n');
|
||||
assert.ok(template.includes('Call RuneStoneCompareVersions'));
|
||||
assert.ok(!template.includes('nsis_tauri_utils::SemverCompare'));
|
||||
assert.match(template, /SetErrorLevel 2\n\s+Quit/);
|
||||
const guard = / !if "\$\{ALLOWDOWNGRADES\}" == "false"\n \$\{If\} \$R0 = -1[\s\S]+? !endif/.exec(template)?.[0];
|
||||
assert.ok(guard, 'The downgrade guard must precede reinstall and update actions.');
|
||||
const blockExe = path.join(root, 'block.exe');
|
||||
const blockScript = path.join(root, 'block.nsi');
|
||||
await writeFile(blockScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone downgrade check"\nOutFile "${blockExe}"\n!include LogicLib.nsh\n!define ALLOWDOWNGRADES "false"\nLangString dontUninstallDowngrade 1033 "Older versions cannot replace this installation."\nSection\nStrCpy $R0 -1\n${guard}\nSetErrorLevel 1\nSectionEnd\n`);
|
||||
const blockBuilt = spawnSync(compiler, ['/V2', blockScript], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(blockBuilt.status, 0, blockBuilt.stdout + blockBuilt.stderr);
|
||||
for (const flags of [['/S'], ['/S', '/P'], ['/S', '/UPDATE']]) {
|
||||
const blocked = spawnSync(blockExe, flags, { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(blocked.status, 2, 'The installer must block a downgrade with ' + flags.join(' '));
|
||||
}
|
||||
assert.match(template, /\$\{ElseIf\} \$R0 = 1 ; Upgrading\n\s+\$\{If\} \$R1 = 1\n\s+Goto reinst_done/);
|
||||
assert.ok(template.includes('"RuneStoneReleaseVersion" "${VERSION}"'));
|
||||
assert.ok(template.includes('"DisplayVersion" "${TOOLCHAINVERSION}"'));
|
||||
const legacyExe = path.join(root, 'legacy.exe');
|
||||
const legacyScript = path.join(root, 'legacy.nsi');
|
||||
const pluginPath = path.join(process.env.LOCALAPPDATA!, 'tauri/NSIS/Plugins/x86-unicode/additional');
|
||||
await writeFile(legacyScript, `Unicode true\nSilentInstall silent\nRequestExecutionLevel user\nName "RuneStone legacy version check"\nOutFile "${legacyExe}"\n!addplugindir "${pluginPath}"\nSection\nnsis_tauri_utils::SemverCompare "0.1.23" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_ok\nSetErrorLevel 1\nQuit\nlegacy_ok:\nnsis_tauri_utils::SemverCompare "0.1.22" "0.1.23+1"\nPop $0\nStrCmp $0 -1 legacy_older_ok\nSetErrorLevel 1\nQuit\nlegacy_older_ok:\nnsis_tauri_utils::SemverCompare "0.1.24" "0.1.23+1"\nPop $0\nStrCmp $0 1 legacy_newer_ok\nSetErrorLevel 1\nQuit\nlegacy_newer_ok:\nSetErrorLevel 0\nSectionEnd\n`);
|
||||
const legacyBuilt = spawnSync(compiler, ['/V2', legacyScript], { encoding: 'utf8', windowsHide: true });
|
||||
assert.equal(legacyBuilt.status, 0, legacyBuilt.stdout + legacyBuilt.stderr);
|
||||
const legacyChecked = spawnSync(legacyExe, ['/S'], { encoding: 'utf8', windowsHide: true, timeout: 30000 });
|
||||
assert.equal(legacyChecked.status, 0, 'Older installers must detect the encoded hotfix as newer.');
|
||||
} finally {
|
||||
assert.equal(path.isAbsolute(root) && root.startsWith(path.join(tmpdir(), 'runestone-installer-version-')), true);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,44 +0,0 @@
|
||||
import {createRequire} from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
const {chromium}=createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser=await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9224');
|
||||
const context=browser.contexts()[0];
|
||||
const page=context.pages().find(page => new URL(page.url()).pathname === '/' && !new URL(page.url()).search);
|
||||
assert.ok(page, 'The isolated main window must be open.');
|
||||
let transferred, settings;
|
||||
try {
|
||||
const identity=await page.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
|
||||
assert.match(identity, /[\\/]com\.runestone\.spelling-test[\\/]?$/);
|
||||
const pending=context.waitForEvent('page');
|
||||
const token=await page.evaluate(async()=>{
|
||||
const {invoke}=await import('/node_modules/@tauri-apps/api/core.js');
|
||||
const root=await invoke('workspace_last_path');
|
||||
const token=crypto.randomUUID(), id=crypto.randomUUID();
|
||||
localStorage.setItem('runestone.tab-transfer.'+token,JSON.stringify({root,created:Date.now(),reading:false,buffer:{id,relPath:'empty:'+id,name:'New tab',kind:'empty',imageUrl:null,contents:'',saved:'',chrome:'Writing',chromeOverride:null}}));
|
||||
await invoke('workspace_open_window',{path:root,transfer:token});
|
||||
return token;
|
||||
});
|
||||
transferred=await pending;
|
||||
await transferred.locator('.empty').waitFor();
|
||||
assert.ok(transferred.url().includes('?tabTransfer='+token));
|
||||
assert.ok(!transferred.url().includes('index.html'));
|
||||
assert.equal(await transferred.getByText('404',{exact:true}).count(),0);
|
||||
await page.waitForFunction(token=>localStorage.getItem('runestone.tab-transfer.'+token+'.accepted') === 'true',token);
|
||||
console.log('PASS: native empty-tab transfer loads the splash screen and acknowledges its saved tab state.');
|
||||
await transferred.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().close()); transferred=undefined;
|
||||
settings=context.pages().find(page => page.url().includes('settingsWindow=true'));
|
||||
const next=settings ? Promise.resolve(settings) : context.waitForEvent('page');
|
||||
await page.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/core.js')).invoke('settings_open_window'));
|
||||
settings=await next;
|
||||
await settings.waitForURL(/settingsWindow=true/);
|
||||
await settings.waitForLoadState('domcontentloaded');
|
||||
const error=await settings.evaluate(async()=>{
|
||||
try { await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('theme_export',{contents:'{',defaultName:'test.json'}); }
|
||||
catch(error) { return String(error); }
|
||||
});
|
||||
assert.equal(error,'The theme contains invalid JSON.');
|
||||
console.log('PASS: the native settings window can call theme export; invalid JSON stops before the save dialog.');
|
||||
} finally {
|
||||
for(const target of [transferred,settings]) if(target&&!target.isClosed()) await target.evaluate(async()=> (await import('/node_modules/@tauri-apps/api/window.js')).getCurrentWindow().close()).catch(()=>{});
|
||||
await browser.close();
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,152 +0,0 @@
|
||||
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(); }
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { languageFor } from "../src/lib/editor/languageFor.ts";
|
||||
|
||||
test("markdown files use the markdown language", () => {
|
||||
assert.equal(languageFor("notes/inbox.md"), "markdown");
|
||||
assert.equal(languageFor("README.markdown"), "markdown");
|
||||
});
|
||||
|
||||
test("python and scripts use their languages", () => {
|
||||
assert.equal(languageFor("src/hello.py"), "python");
|
||||
assert.equal(languageFor("tools/setup.sh"), "shell");
|
||||
});
|
||||
|
||||
test("unknown extensions are plaintext", () => {
|
||||
assert.equal(languageFor("Makefile"), "plaintext");
|
||||
assert.equal(languageFor("notes/data.bin"), "plaintext");
|
||||
});
|
||||
@@ -1,31 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { externalLinkText, workspaceLinkText } from "../src/lib/editor/linkCommands.ts";
|
||||
import { linkCandidates } from "../src/lib/workspace/markdownLinks.ts";
|
||||
|
||||
test("external links prepare editable syntax with the cursor in the missing field", () => {
|
||||
const empty = externalLinkText("", { from: 0, to: 0 });
|
||||
assert.equal(empty.insert, "[]()");
|
||||
assert.equal(empty.anchor, 1);
|
||||
assert.equal(empty.head, 1);
|
||||
const selected = externalLinkText("before [label] after", { from: 7, to: 14 });
|
||||
assert.equal(selected.insert, "[\\[label\\]]()");
|
||||
assert.equal(selected.anchor - selected.from, selected.insert.length - 1);
|
||||
assert.equal(selected.anchor, selected.head);
|
||||
});
|
||||
|
||||
test("workspace links retain the selected label and the exact workspace path", () => {
|
||||
assert.equal(workspaceLinkText("", { from: 0, to: 0 }, "notes/Same name.md").insert, "[[/notes/Same%20name.md]]");
|
||||
const edit = workspaceLinkText("before visible\nlabel after", { from: 7, to: 20 }, "nested/target.md");
|
||||
assert.equal(edit.insert, "[[/nested/target.md|visible label]]");
|
||||
assert.equal(edit.anchor, 7);
|
||||
assert.equal(edit.head, 7 + edit.insert.length);
|
||||
});
|
||||
|
||||
test("workspace link paths preserve spaces, brackets, hashes and literal percent signs", () => {
|
||||
const path = "notes/Nested/[A] #50%.md";
|
||||
const edit = workspaceLinkText("", { from: 0, to: 0 }, path);
|
||||
const target = edit.insert.slice(2, -2);
|
||||
assert.equal(target, "/notes/Nested/%5BA%5D%20%2350%25.md");
|
||||
assert.deepEqual(linkCandidates("notes/current.md", target, "wiki"), [path]);
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { CHARACTER_THEMES, SYNTAX_ROLES } from '../src/lib/theme/characterThemes.ts';
|
||||
|
||||
const rgb = (hex: string) => hex.match(/[0-9a-f]{2}/gi)!.map(channel => parseInt(channel, 16));
|
||||
const luminance = (hex: string) => rgb(hex).map(channel => channel / 255)
|
||||
.map(channel => channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4)
|
||||
.reduce((sum, channel, index) => sum + channel * [.2126, .7152, .0722][index], 0);
|
||||
const contrast = (a: string, b: string) => (Math.max(luminance(a), luminance(b)) + .05) / (Math.min(luminance(a), luminance(b)) + .05);
|
||||
const mix = (a: string, b: string, ratio: number) => '#' + rgb(a)
|
||||
.map((channel, index) => Math.round(channel * ratio + rgb(b)[index] * (1 - ratio)).toString(16).padStart(2, '0')).join('');
|
||||
|
||||
test('Silver Serpent text and syntax remain readable on opaque and image surfaces', () => {
|
||||
const { surfaces, syntax, secondary } = CHARACTER_THEMES['silver-serpent'];
|
||||
const [bg, elevated, active, , dim, text, strong, accent, selection] = surfaces;
|
||||
const panelOnWhite = mix(elevated, '#ffffff', .82);
|
||||
const editorOnWhite = mix(bg, '#ffffff', .9);
|
||||
const backgrounds = {
|
||||
bg, elevated, active, selection,
|
||||
panelOnWhite,
|
||||
editorOnWhite,
|
||||
menuHoverOnWhite: mix(active, panelOnWhite, .82),
|
||||
controlHoverOnWhite: mix(active, '#ffffff', .92),
|
||||
codeBlockOnWhite: mix(elevated, editorOnWhite, .82),
|
||||
};
|
||||
const foregrounds = { dim, text, strong, accent, secondary,
|
||||
...Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, syntax[index]])) };
|
||||
for (const [backgroundName, background] of Object.entries(backgrounds)) {
|
||||
for (const [foregroundName, foreground] of Object.entries(foregrounds)) {
|
||||
assert(contrast(foreground, background) >= 4.5, `${foregroundName} on ${backgroundName}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Silver Serpent selection has a readable perimeter and a separate fill', () => {
|
||||
const [bg, elevated, , , , , , accent, selection] = CHARACTER_THEMES['silver-serpent'].surfaces;
|
||||
assert(contrast(accent, selection) >= 3, 'selection perimeter');
|
||||
assert(contrast(selection, bg) >= 1.5, 'selection against the editor');
|
||||
assert(contrast(selection, elevated) >= 1.5, 'selection against a panel');
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { markdownBlocks, markdownFences } from "../src/lib/workspace/markdownBlocks.ts";
|
||||
|
||||
test("fenced block with a language is one fence", () => {
|
||||
assert.deepEqual(markdownBlocks("hi\n```js\nconst x = 1\n```\nbye"), [
|
||||
{ type: "text", line: "hi" },
|
||||
{ type: "fence", lang: "js", body: "const x = 1" },
|
||||
{ type: "text", line: "bye" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("fenced block without a language keeps an empty lang", () => {
|
||||
assert.deepEqual(markdownBlocks("```\nHUGE\n```"), [
|
||||
{ type: "fence", lang: "", body: "HUGE" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("inline backticks stay on a text line", () => {
|
||||
assert.deepEqual(markdownBlocks("say `HUGE` now"), [
|
||||
{ type: "text", line: "say `HUGE` now" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("a fence opened and closed on one line is a fence", () => {
|
||||
assert.deepEqual(markdownBlocks("```this was a triumph```"), [
|
||||
{ type: "fence", lang: "", body: "this was a triumph" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("closed fence body is the copy payload", () => {
|
||||
assert.deepEqual(markdownFences("```js\nconst x = 1\n```"), [
|
||||
{ lang: "js", body: "const x = 1", openLine: 1, closeLine: 3 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("one-line fence body excludes ticks", () => {
|
||||
assert.deepEqual(markdownFences("```this was a triumph```"), [
|
||||
{ lang: "", body: "this was a triumph", openLine: 1, closeLine: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("unclosed fence is not MdFence", () => {
|
||||
assert.deepEqual(markdownFences("```js\nconst x = 1\n"), []);
|
||||
});
|
||||
|
||||
test("markdownBlocks fence body matches markdownFences", () => {
|
||||
const src = "hi\n```js\nconst x = 1\n```\nbye";
|
||||
const block = markdownBlocks(src).find((row) => row.type === "fence");
|
||||
const fence = markdownFences(src)[0];
|
||||
assert.equal(block && block.type === "fence" ? block.body : null, "const x = 1");
|
||||
assert.equal(fence.body, "const x = 1");
|
||||
assert.equal(fence.lang, "js");
|
||||
assert.equal(fence.openLine, 2);
|
||||
assert.equal(fence.closeLine, 4);
|
||||
});
|
||||
@@ -1,60 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { formatText, paragraphText, insertBlock, type MarkdownEdit, type InlineFormat } from "../src/lib/editor/markdownCommands.ts";
|
||||
|
||||
const apply = (source: string, edit: MarkdownEdit) => source.slice(0, edit.from) + edit.insert + source.slice(edit.to);
|
||||
|
||||
test("inline formatting toggles without losing surrounding prose or the selected text", () => {
|
||||
for (const format of ["bold", "italic", "strike", "highlight", "code", "math", "comment"] as InlineFormat[]) {
|
||||
const source = "before words after", selection = { from: 7, to: 12 };
|
||||
const edit = formatText(source, selection, format), changed = apply(source, edit);
|
||||
assert.equal(changed.slice(edit.anchor, edit.head), "words");
|
||||
assert.equal(apply(changed, formatText(changed, { from: edit.anchor, to: edit.head }, format)), source, format);
|
||||
assert.equal(apply(changed, formatText(changed, { from: edit.from, to: edit.from + edit.insert.length }, format)), source, format);
|
||||
}
|
||||
assert.equal(apply("word ", formatText("word ", { from: 0, to: 5 }, "bold")), "**word** ");
|
||||
assert.equal(apply("**bold**", formatText("**bold**", { from: 0, to: 8 }, "italic")), "***bold***");
|
||||
const empty = formatText("", { from: 0, to: 0 }, "bold");
|
||||
assert.equal(empty.insert, "****"); assert.equal(empty.anchor, 2); assert.equal(empty.head, 2);
|
||||
});
|
||||
|
||||
test("code delimiters survive backticks and clear formatting preserves literal punctuation and newlines", () => {
|
||||
const source = "a ` b", edit = formatText(source, { from: 0, to: source.length }, "code");
|
||||
assert.equal(edit.insert, "``a ` b``");
|
||||
assert.equal(apply(edit.insert, formatText(edit.insert, { from: edit.anchor, to: edit.head }, "code")), source);
|
||||
assert.equal(apply(edit.insert, formatText(edit.insert, { from: 0, to: edit.insert.length }, "code")), source);
|
||||
const rich = "**bold**\r\n==mark== and \\*literal\\*";
|
||||
assert.equal(formatText(rich, { from: 0, to: rich.length }, "clear").insert, "bold\r\nmark and \\*literal\\*");
|
||||
assert.equal(apply("***bold***", formatText("***bold***", { from: 3, to: 7 }, "clear")), "bold");
|
||||
});
|
||||
|
||||
test("paragraph commands cover selected lines, omit an unselected next line, and preserve indentation and CRLF", () => {
|
||||
const source = "before\r\n - [x] first\r\n 2. second\r\nafter";
|
||||
const selected = { from: source.indexOf("first"), to: source.indexOf("after") };
|
||||
assert.equal(apply(source, paragraphText(source, selected, 3)), "before\r\n ### first\r\n ### second\r\nafter");
|
||||
assert.equal(apply(source, paragraphText(source, selected, "body")), "before\r\n first\r\n second\r\nafter");
|
||||
assert.equal(paragraphText("one\ntwo\n\nthree", { from: 0, to: 14 }, "number").insert, "1. one\n2. two\n\n1. three");
|
||||
assert.equal(paragraphText("", { from: 0, to: 0 }, "task").insert, "- [ ] ");
|
||||
assert.equal(apply("one\ntwo", paragraphText("one\ntwo", { from: 4, to: 4 }, "quote")), "one\n> two");
|
||||
});
|
||||
|
||||
test("block inserts retain adjacent text, escape code fences, and select editable placeholders", () => {
|
||||
const source = "left right", selection = { from: 5, to: 10 };
|
||||
for (const kind of ["table", "rule"] as const) {
|
||||
const result = apply(source, insertBlock(source, selection, kind));
|
||||
assert.ok(result.startsWith(source + "\n\n"));
|
||||
}
|
||||
const code = insertBlock("```", { from: 0, to: 3 }, "code");
|
||||
assert.equal(code.insert, "````\n```\n````\n\n");
|
||||
const table = insertBlock("", { from: 0, to: 0 }, "table");
|
||||
assert.equal(table.insert.slice(table.anchor, table.head), "Column 1");
|
||||
assert.equal(insertBlock("a\r\nb", { from: 3, to: 4 }, "callout").insert, "\r\n> [!note]\r\n> b\r\n\r\n");
|
||||
});
|
||||
|
||||
test("footnotes get unique references, retain the document tail, and select the definition", () => {
|
||||
const source = "One[^1] and words.\n\n[^1]: existing\n";
|
||||
const from = source.indexOf("words"), edit = insertBlock(source, { from, to: from + 5 }, "footnote");
|
||||
const changed = apply(source, edit);
|
||||
assert.equal(changed, "One[^1] and [^2].\n\n[^1]: existing\n\n[^2]: words\n");
|
||||
assert.equal(changed.slice(edit.anchor, edit.head), "words");
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { findMarkdownLinks, wikiCandidates } from "../src/lib/workspace/markdownLinks.ts";
|
||||
|
||||
test("markdown links skip image embeds", () => {
|
||||
const links = findMarkdownLinks("See [alpha](notes/a.md) and ");
|
||||
assert.deepEqual(links, [
|
||||
{ kind: "md", from: 4, to: 23, label: "alpha", target: "notes/a.md" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("wikilinks skip image embeds", () => {
|
||||
const links = findMarkdownLinks("Go [[projects/alpha|Alpha]] and ![[screenshot.png]]");
|
||||
assert.deepEqual(links, [
|
||||
{
|
||||
kind: "wiki",
|
||||
from: 3,
|
||||
to: 27,
|
||||
label: "Alpha",
|
||||
target: "projects/alpha",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("wikiCandidates add .md for a bare name", () => {
|
||||
assert.deepEqual(wikiCandidates("alpha"), ["alpha.md", "notes/alpha.md", "alpha"]);
|
||||
});
|
||||
|
||||
|
||||
import { linkCandidates } from "../src/lib/workspace/markdownLinks.ts";
|
||||
|
||||
test("links resolve relative to notes, including parent paths and encoded spaces", () => {
|
||||
assert.deepEqual(linkCandidates("notes/project/inbox.md", "../other%20note.md", "md"), ["notes/other note.md"]);
|
||||
assert.deepEqual(linkCandidates("notes/inbox.md", "ideas", "wiki"), ["notes/ideas.md", "notes/ideas", "ideas.md", "ideas"]);
|
||||
assert.deepEqual(linkCandidates("notes/inbox.md", "../../secret", "md"), []);
|
||||
assert.deepEqual(linkCandidates("notes/inbox.md", "javascript:alert(1)", "md"), []);
|
||||
});
|
||||
@@ -1,207 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,112 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,120 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "../src/lib/editor/markdownTable.ts";
|
||||
import { tableCellMarkdown, extractedCellMarkdown } from "../src/lib/editor/tableCellMarkdown.ts";
|
||||
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||
|
||||
const table = "| Ticker | Notes |\n| :--- | ---: |\n| IBKR.US | First<br>Second |";
|
||||
|
||||
test("prose directly after a table stays outside the table and its edit range", () => {
|
||||
for (const eol of ["\n", "\r\n"]) {
|
||||
const body = table.replaceAll("\n", eol);
|
||||
const tail = `${eol}Plain text${eol}More text with an escaped \\| pipe${eol}# Heading`;
|
||||
const source = body + tail;
|
||||
assert.equal(parseMarkdownTable(source)?.end, body.length);
|
||||
assert.equal(parseMarkdownTable(source)?.rows.length, 3);
|
||||
assert.equal(appendTableRow(source), body + `${eol}| | |` + tail);
|
||||
assert.equal(appendTableColumn(source), appendTableColumn(body) + tail);
|
||||
assert.equal(replaceTableCell(source, 3, 0, "changed"), source);
|
||||
const html = renderMarkdownHtml(source, new Map());
|
||||
assert.equal((html.match(/<tr>/g) || []).length, 2);
|
||||
assert.match(html, /<\/table>[\s\S]*<p>Plain text/);
|
||||
const sections = renderMarkdownSections(source, new Map());
|
||||
assert.equal(sections[0].end, body.length + eol.length);
|
||||
assert.equal(source.slice(sections[1].start).startsWith("Plain text"), true);
|
||||
}
|
||||
});
|
||||
|
||||
test("table boundaries distinguish escaped pipes from delimiters and work in nested blocks", () => {
|
||||
const body = "| A | B |\n| --- | --- |\nOne | Two\n| short |\n| escaped \\| pipe | value |\n| even \\\\| delimiter |";
|
||||
assert.equal(parseMarkdownTable(body + "\nProse \\| literal")?.rows.length, 6);
|
||||
assert.equal((renderMarkdownHtml(body + "\nProse \\| literal", new Map()).match(/<tr>/g) || []).length, 5);
|
||||
assert.match(renderMarkdownHtml("> | A |\n> | --- |\n> | B |\n> Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
|
||||
assert.match(renderMarkdownHtml("- Item\n\n | A |\n | --- |\n | B |\n Paragraph", new Map()), /<\/table>[\s\S]*<p>Paragraph<\/p>/);
|
||||
});
|
||||
|
||||
test("extracted cell text keeps formatting and literal code while converting actual line breaks", () => {
|
||||
assert.equal(extractedCellMarkdown([
|
||||
{ type: "text", text: "Title", marks: [{ type: "bold" }] },
|
||||
{ type: "hardBreak" },
|
||||
{ type: "text", text: "<br>", marks: [{ type: "code" }] },
|
||||
]), "**Title**\n`<br>`");
|
||||
});
|
||||
|
||||
test("table column insertion retains alignment and existing cell contents", () => {
|
||||
assert.equal(appendTableColumn(table), "| Ticker | Notes | |\n| :--- | ---: | --- |\n| IBKR.US | First<br>Second | |");
|
||||
});
|
||||
|
||||
test("table row insertion keeps existing source byte-for-byte", () => {
|
||||
assert.equal(appendTableRow(table + "\n\n"), table + "\n| | |\n\n");
|
||||
});
|
||||
|
||||
test("table edits preserve CRLF and optional outer pipes", () => {
|
||||
const source = "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n";
|
||||
assert.equal(appendTableRow(source), "Name | Link\r\n--- | :---:\r\nOne | [note](note.md)\r\n| | |\r\n");
|
||||
assert.equal(appendTableColumn(source), "| Name | Link | |\r\n| --- | :---: | --- |\r\n| One | [note](note.md) | |\r\n");
|
||||
});
|
||||
|
||||
test("escaped pipes in text, wiki aliases, and inline code stay inside cells", () => {
|
||||
const source = "| One | Two |\n| --- | --- |\n| [[note\\|Alias]] | `a\\|b` and text\\|value |";
|
||||
const parsed = parseMarkdownTable(source)!;
|
||||
assert.equal(parsed.rows[2].cells.length, 2);
|
||||
const changed = appendTableColumn(source);
|
||||
assert.ok(changed.includes("| [[note\\|Alias]] | `a\\|b` and text\\|value | |"));
|
||||
for (const row of parsed.rows) for (const cell of row.cells) assert.equal(source.slice(cell.from, cell.to), cell.text);
|
||||
});
|
||||
|
||||
test("adding columns pads short rows without losing extra source cells", () => {
|
||||
const source = "| A | B |\n| --- | --- |\n| short |\n| a | b | extra |";
|
||||
assert.equal(appendTableColumn(source), "| A | B | |\n| --- | --- | --- |\n| short | | |\n| a | b | | extra |");
|
||||
});
|
||||
|
||||
test("table controls handle header-only and single-column tables", () => {
|
||||
assert.equal(appendTableRow("| Header |\n| --- |"), "| Header |\n| --- |\n| |");
|
||||
assert.equal(parseMarkdownTable(appendTableColumn("| Header |\n| --- |"))?.columns, 2);
|
||||
});
|
||||
|
||||
test("invalid tables are unchanged", () => {
|
||||
for (const source of ["Just text", "| A | B |\n| --- |", "| A |\n| not a delimiter |"] ) {
|
||||
assert.equal(parseMarkdownTable(source), null);
|
||||
assert.equal(appendTableColumn(source), source);
|
||||
assert.equal(appendTableRow(source), source);
|
||||
}
|
||||
});
|
||||
|
||||
test("editing one cell preserves padding, alignment, other cells and CRLF", () => {
|
||||
const source = " | Name | Notes |\r\n | :--- | ---: |\r\n | One | first<br />~~old~~ |\r\n\r\nTail";
|
||||
assert.equal(replaceTableCell(source, 2, 1, "next<br>line\\|pipe"), source.replace("first<br />~~old~~", "next<br>line\\|pipe"));
|
||||
assert.equal(replaceTableCell(source, 0, 0, "Title"), source.replace("Name", "Title"));
|
||||
assert.equal(replaceTableCell(source, 1, 0, "bad"), source);
|
||||
assert.equal(replaceTableCell(source, 2, 1, "break\nrow"), source);
|
||||
});
|
||||
|
||||
test("editing an empty or omitted cell does not overwrite its neighbor", () => {
|
||||
assert.equal(replaceTableCell("| A | B |\n| --- | --- |\n| short |", 2, 1, "new"), "| A | B |\n| --- | --- |\n| short | new |");
|
||||
const source = "| A | B |\n| --- | --- |\n| | value |";
|
||||
assert.equal(replaceTableCell(source, 2, 0, "new"), source.replace("| | value", "| new| value"));
|
||||
});
|
||||
|
||||
test("rich cell serialization retains breaks, formatting, links and literal punctuation", () => {
|
||||
const text = tableCellMarkdown({ type: "doc", content: [{ type: "paragraph", content: [
|
||||
{ type: "text", text: "old", marks: [{ type: "strike" }] },
|
||||
{ type: "hardBreak" },
|
||||
{ type: "text", text: "bold", marks: [{ type: "bold" }] },
|
||||
{ type: "text", text: " | *literal* <br> & value" },
|
||||
{ type: "hardBreak" },
|
||||
{ type: "text", text: "a|`b", marks: [{ type: "code" }] },
|
||||
{ type: "text", text: "note", marks: [{ type: "link", attrs: { href: "note.md", "data-kind": "wiki" } }] },
|
||||
{ type: "text", text: "web", marks: [{ type: "link", attrs: { href: "https://example.com/a(b)" } }] },
|
||||
] }, { type: "paragraph", content: [{ type: "text", text: "Pasted paragraph" }] }] });
|
||||
const source = `| A |\n| --- |\n| ${text} |`;
|
||||
assert.equal(parseMarkdownTable(source)?.rows[2].cells.length, 1);
|
||||
const html = renderMarkdownHtml(source, new Map());
|
||||
assert.ok(html.includes("<s>old</s>"));
|
||||
assert.ok(html.includes("<strong>bold</strong>"));
|
||||
assert.ok(html.includes("| *literal* <br> & value"));
|
||||
assert.ok(html.includes("<code>a|`b</code>"));
|
||||
assert.ok(html.includes('href="note.md" data-kind="wiki"'));
|
||||
assert.ok(html.includes('href="https://example.com/a(b)"'));
|
||||
assert.equal((html.match(/<br>/g) || []).length, 3);
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
findMarkdownImages,
|
||||
isImagePath,
|
||||
isRemoteImage,
|
||||
resolveImageRel,
|
||||
} from "../src/lib/workspace/media.ts";
|
||||
|
||||
test("image paths are detected by extension", () => {
|
||||
assert.equal(isImagePath("screenshot.png"), true);
|
||||
assert.equal(isImagePath("notes/photo.JPEG"), true);
|
||||
assert.equal(isImagePath("notes/inbox.md"), false);
|
||||
});
|
||||
|
||||
test("markdown image syntax is parsed", () => {
|
||||
const found = findMarkdownImages("See  and ![[screenshot.png|Hero]]");
|
||||
assert.equal(found.length, 2);
|
||||
assert.equal(found[0].src, "../shot.png");
|
||||
assert.equal(found[0].kind, "md");
|
||||
assert.equal(found[1].src, "screenshot.png");
|
||||
assert.equal(found[1].alt, "Hero");
|
||||
assert.equal(found[1].kind, "wiki");
|
||||
});
|
||||
|
||||
test("image paths resolve from the note folder", () => {
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "pic.png"), "notes/pic.png");
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "../screenshot.png"), "screenshot.png");
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "screenshot.png"), "notes/screenshot.png");
|
||||
assert.equal(resolveImageRel("notes/inbox.md", "/assets/pic.png"), "assets/pic.png");
|
||||
});
|
||||
|
||||
test("remote images stay as URLs", () => {
|
||||
assert.equal(isRemoteImage("https://example.com/a.png"), true);
|
||||
assert.equal(isRemoteImage("screenshot.png"), false);
|
||||
});
|
||||
@@ -1,334 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,71 +0,0 @@
|
||||
// Use only an isolated com.runestone.spelling-test debug window.
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir, writeFile } 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.connectOverCDP(process.env.SPELLING_CDP_URL || 'http://127.0.0.1:9237');
|
||||
const page = browser.contexts()[0].pages()[0];
|
||||
page.setDefaultTimeout(15000);
|
||||
const captures = [];
|
||||
try {
|
||||
await page.waitForFunction(() => !!window.__TAURI_INTERNALS__);
|
||||
await page.getByRole('button', { name: 'Settings (Ctrl+,)', exact: true }).waitFor();
|
||||
const identity = await page.evaluate(async () => (await import('/node_modules/@tauri-apps/api/path.js')).appDataDir());
|
||||
assert.match(identity, /[\\/]com\.runestone\.spelling-test[\\/]?$/);
|
||||
await page.evaluate(async () => {
|
||||
const { listen } = await import('/node_modules/@tauri-apps/api/event.js');
|
||||
window.nativeMenuPayload = null;
|
||||
await listen('spelling-menu', ({ payload }) => window.nativeMenuPayload = payload);
|
||||
await (await import('/node_modules/@tauri-apps/api/core.js')).invoke('spelling_menu_install');
|
||||
});
|
||||
await mkdir('output/todo-menus', { recursive: true });
|
||||
const menu = page.getByRole('menu', { name: 'Spelling actions', exact: true });
|
||||
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);
|
||||
for (const kind of ['input', 'textarea', 'dialog']) {
|
||||
await page.evaluate(kind => {
|
||||
document.getElementById('native-menu-field')?.remove(); document.getElementById('native-menu-dialog')?.remove();
|
||||
const field = document.createElement(kind === 'input' ? 'input' : 'textarea');
|
||||
field.id = 'native-menu-field'; field.spellcheck = true; field.value = 'I recieved a letter.';
|
||||
field.style.cssText = 'position:fixed;left:100px;top:100px;width:500px;height:100px;font:16px/24px Arial;padding:10px;z-index:100';
|
||||
if (kind === 'dialog') { const dialog = document.createElement('dialog'); dialog.id = 'native-menu-dialog'; dialog.append(field); document.body.append(dialog); dialog.showModal(); }
|
||||
else document.body.append(field);
|
||||
field.focus();
|
||||
}, kind);
|
||||
const field = page.locator('#native-menu-field');
|
||||
await field.press('End');
|
||||
await field.pressSequentially(' TEST');
|
||||
await field.click({ button: 'right', position: { x: 300, y: kind === 'input' ? 50 : 22 } });
|
||||
await menu.waitFor();
|
||||
const payload = await page.evaluate(() => window.nativeMenuPayload);
|
||||
captures.push({ mode, kind, value: await field.inputValue(), payload });
|
||||
await writeFile('output/todo-menus/native-filtered-items.json', JSON.stringify(captures, null, 2));
|
||||
const flatten = items => items.flatMap(item => [item, ...flatten(item.children)]);
|
||||
const entries = flatten(payload.items);
|
||||
assert.ok(entries.every(item => item.kind === 3 || !['share', 'writingDirection', 'voiceTyping', 'other'].includes(item.name)));
|
||||
assert.ok(entries.some(item => item.name === 'undo' && item.enabled), mode + ' ' + kind + ' keeps native Undo enabled');
|
||||
assert.ok(entries.some(item => item.name === 'emoji'));
|
||||
assert.ok(entries.some(item => item.name === 'copy'));
|
||||
assert.equal(await menu.getByRole('menuitem', { name: /More tools|Writing direction|Voice typing|Share/ }).count(), 0);
|
||||
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
|
||||
if (kind === 'textarea') await page.screenshot({ path: `output/todo-menus/native-${mode}.png` });
|
||||
await menu.getByRole('menuitem', { name: 'Undo Ctrl+Z', exact: true }).click();
|
||||
await page.waitForFunction(() => document.getElementById('native-menu-field').value === 'I recieved a letter.').catch(async error => { console.error('Undo result', await field.inputValue()); throw error; });
|
||||
await field.click({ button: 'right', position: { x: 48, y: kind === 'input' ? 50 : 22 } });
|
||||
await menu.getByRole('menuitem', { name: 'received', exact: true }).click();
|
||||
assert.equal(await field.inputValue(), 'I received a letter.');
|
||||
await field.press('Control+z');
|
||||
assert.equal(await field.inputValue(), 'I recieved a letter.');
|
||||
await field.click({ button: 'right', position: { x: 48, y: kind === 'input' ? 50 : 22 } });
|
||||
await menu.waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await field.evaluate(node => document.activeElement === node), true);
|
||||
}
|
||||
}
|
||||
await writeFile('output/todo-menus/native-filtered-items.json', JSON.stringify(captures, null, 2));
|
||||
console.log('PASS: real WebView2 menus omit unsupported commands, retain editing and spelling, execute native Undo, correct spelling with undo, and restore focus in fields and dialogs in both themes.');
|
||||
} finally {
|
||||
await page.evaluate(() => { document.getElementById('native-menu-field')?.remove(); document.getElementById('native-menu-dialog')?.remove(); }).catch(() => {});
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { htmlToMarkdown } from "../src/lib/workspace/htmlToMarkdown.ts";
|
||||
|
||||
test("headings and inline marks become markdown", () => {
|
||||
const html =
|
||||
"<h1>Heading 1</h1><h2>Heading 2</h2><p>hello <strong>bold</strong> and <code>code</code></p>";
|
||||
assert.equal(htmlToMarkdown(html), "# Heading 1\n## Heading 2\nhello **bold** and `code`");
|
||||
});
|
||||
|
||||
test("fences keep language and body", () => {
|
||||
const html = '<pre class="md-code" data-lang="js"><code class="language-js">const x = 1</code></pre>';
|
||||
assert.equal(htmlToMarkdown(html), "```js\nconst x = 1\n```");
|
||||
});
|
||||
|
||||
test("wiki and markdown links become markdown", () => {
|
||||
const html =
|
||||
'<p>see <a class="wiki" href="projects/alpha" data-kind="wiki">projects/alpha</a> and <a href="notes/a.md" data-kind="md">label</a></p>';
|
||||
assert.equal(htmlToMarkdown(html), "see [[projects/alpha]] and [label](notes/a.md)");
|
||||
});
|
||||
|
||||
test("wiki image uses data-md-kind", () => {
|
||||
const html =
|
||||
'<p><img src="data:image/png;base64,xx" alt="screenshot.png" data-md-src="screenshot.png" data-md-kind="wiki" /></p>';
|
||||
assert.equal(htmlToMarkdown(html), "![[screenshot.png]]");
|
||||
});
|
||||
|
||||
test("strike super and sub become markdown", () => {
|
||||
const html = "<p><s>old</s> x<sup>2</sup> a<sub>n</sub></p>";
|
||||
assert.equal(htmlToMarkdown(html), "~~old~~ x^2^ a~n~");
|
||||
});
|
||||
|
||||
test("gfm table becomes markdown", () => {
|
||||
const html =
|
||||
"<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>";
|
||||
assert.equal(htmlToMarkdown(html), "| A | B |\n| --- | --- |\n| 1 | 2 |");
|
||||
});
|
||||
|
||||
test("checked task item becomes a checkbox line", () => {
|
||||
const html =
|
||||
'<ul data-type="taskList"><li data-type="taskItem" data-checked="true"><p>done</p></li></ul>';
|
||||
assert.equal(htmlToMarkdown(html), "- [x] done");
|
||||
});
|
||||
|
||||
test("unchecked task item becomes an empty checkbox", () => {
|
||||
const html =
|
||||
'<ul data-type="taskList"><li data-type="taskItem" data-checked="false"><p>todo</p></li></ul>';
|
||||
assert.equal(htmlToMarkdown(html), "- [ ] todo");
|
||||
});
|
||||
|
||||
test("italic highlight math and comment become markdown", () => {
|
||||
const html =
|
||||
'<p><em>hi</em> <mark>glow</mark> <span data-math="1">x^2</span> <span data-comment="1">note</span></p>';
|
||||
assert.equal(htmlToMarkdown(html), "*hi* ==glow== $x^2$ %%note%%");
|
||||
});
|
||||
|
||||
test("blockquote and numbered list become markdown", () => {
|
||||
const html = "<blockquote><p>said</p></blockquote><ol><li>one</li><li>two</li></ol>";
|
||||
assert.equal(htmlToMarkdown(html), "> said\n1. one\n2. two");
|
||||
});
|
||||
@@ -1,164 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { WorkspaceNoteIndex, type NoteIndexIO } from "../src/lib/workspace/noteIndex.ts";
|
||||
|
||||
function workspace(files: Map<string, string>): NoteIndexIO {
|
||||
return {
|
||||
async list(folder) {
|
||||
const prefix = folder ? `${folder}/` : "";
|
||||
const entries = new Map<string, { rel_path: string; kind: "file" | "folder" }>();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix)) continue;
|
||||
const suffix = path.slice(prefix.length), separator = suffix.indexOf("/");
|
||||
const rel_path = separator < 0 ? path : prefix + suffix.slice(0, separator);
|
||||
entries.set(rel_path, { rel_path, kind: separator < 0 ? "file" : "folder" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
},
|
||||
async read(path) {
|
||||
if (!files.has(path)) throw new Error("File missing");
|
||||
return files.get(path)!;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("wiki names resolve anywhere and duplicate names require a path", async () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
await index.rebuild(workspace(new Map([
|
||||
["deep/source.md", "[[Elsewhere]]\n[[Root]]"], ["unrelated/nested/Elsewhere.md", ""], ["Root.md", ""],
|
||||
])));
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "resolved", path: "unrelated/nested/Elsewhere.md" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Root#Heading", "wiki"), { status: "resolved", path: "Root.md" });
|
||||
index.update("deep/Elsewhere.md", "");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Elsewhere", "wiki"), { status: "ambiguous", candidates: ["deep/Elsewhere.md", "unrelated/nested/Elsewhere.md"] });
|
||||
assert.equal(index.backlinks("deep/Elsewhere.md").length, 0);
|
||||
assert.deepEqual(index.resolve("deep/source.md", "./Elsewhere", "wiki"), { status: "resolved", path: "deep/Elsewhere.md" });
|
||||
index.update("documents/Other.mdown", "[[Root]]");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Other", "wiki"), { status: "resolved", path: "documents/Other.mdown" });
|
||||
assert.equal(index.backlinks("Root.md").length, 2);
|
||||
index.update("documents/Version 1.2.md", "");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Version 1.2", "wiki"), { status: "resolved", path: "documents/Version 1.2.md" });
|
||||
});
|
||||
|
||||
test("explicit relative links do not fall back and cannot escape the workspace", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
for (const path of ["source.md", "deep/source.md", "Target.md", "deep/folder/Target.md", "folder/Target.md", "deep/Name with spaces.md"]) index.update(path, "");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "./Target", "wiki"), { status: "missing" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "./Target.md", "md"), { status: "missing" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "../Target", "wiki"), { status: "resolved", path: "Target.md" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "/Target", "wiki"), { status: "resolved", path: "Target.md" });
|
||||
assert.equal(index.resolve("deep/source.md", "folder/Target", "wiki").status, "ambiguous");
|
||||
assert.deepEqual(index.resolve("deep/source.md", "Name%20with%20spaces.md#part", "md"), { status: "resolved", path: "deep/Name with spaces.md" });
|
||||
assert.deepEqual(index.resolve("deep/source.md", "..\\Target.md", "md"), { status: "resolved", path: "Target.md" });
|
||||
assert.equal(index.resolve("deep/source.md", "../../Target", "wiki").status, "missing");
|
||||
assert.equal(index.resolve("source.md", "../Target", "wiki").status, "missing");
|
||||
assert.equal(index.resolve("source.md", "https://example.test", "md").status, "external");
|
||||
assert.equal(index.resolve("source.md", "//example.test/Target", "md").status, "external");
|
||||
});
|
||||
|
||||
test("backlinks index wiki aliases, inline and reference Markdown links with source lines", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
index.update("Target.md", "");
|
||||
index.update("source.md", [
|
||||
"[[Target|Alias]]", "[Target](Target.md#Section)", "[Named][id]", "[id][]", "[id]", "", "[id]: Target.md", "",
|
||||
"`[[Target]]`", "", "![[Target]]", "\\[[Target]]", "<!-- [[Target]] -->", "```md", "[[Target]]", "```",
|
||||
].join("\n"));
|
||||
assert.deepEqual(index.backlinks("Target.md").map(link => [link.sourcePath, link.line, link.kind]), [
|
||||
["source.md", 1, "wiki"], ["source.md", 2, "md"], ["source.md", 3, "md"], ["source.md", 4, "md"], ["source.md", 5, "md"],
|
||||
]);
|
||||
index.update("Target.md", "[Local section](#Heading)");
|
||||
assert.equal(index.backlinks("Target.md").length, 5);
|
||||
});
|
||||
|
||||
test("backlinks follow edits, create, file and folder moves, rename, and deletion", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
index.update("folder/source.md", "[[Target]]\n[Target](../Target.md)");
|
||||
assert.deepEqual(index.backlinks("Target.md"), []);
|
||||
index.update("Target.md", "");
|
||||
assert.equal(index.backlinks("Target.md").length, 2);
|
||||
index.update("folder/source.md", "[[Target]]");
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
index.rename("folder", "other/deep");
|
||||
assert.equal(index.backlinks("Target.md")[0].sourcePath, "other/deep/source.md");
|
||||
index.rename("Target.md", "notes/Target.md");
|
||||
assert.equal(index.backlinks("notes/Target.md").length, 1);
|
||||
index.rename("notes/Target.md", "notes/Renamed.md");
|
||||
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
|
||||
index.update("other/deep/source.md", "[[Renamed]]");
|
||||
assert.equal(index.backlinks("notes/Renamed.md").length, 1);
|
||||
index.remove("other");
|
||||
assert.equal(index.backlinks("notes/Renamed.md").length, 0);
|
||||
index.remove("notes/Renamed.md");
|
||||
assert.equal(index.resolve("", "Renamed", "wiki").status, "missing");
|
||||
});
|
||||
|
||||
test("moving a relative-link source changes its target without rewriting Markdown", () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
index.update("Target.md", "");
|
||||
index.update("folder/Target.md", "");
|
||||
index.update("source.md", "[Target](./Target.md)");
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
index.rename("source.md", "folder/source.md");
|
||||
assert.equal(index.backlinks("Target.md").length, 0);
|
||||
assert.equal(index.backlinks("folder/Target.md").length, 1);
|
||||
});
|
||||
|
||||
test("rebuild replaces deleted paths and uses live drafts", async () => {
|
||||
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
|
||||
const index = new WorkspaceNoteIndex();
|
||||
await index.rebuild(workspace(files));
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
files.delete("source.md");
|
||||
files.set("elsewhere/source.md", "Old content");
|
||||
const result = await index.rebuild(workspace(files), new Map([["elsewhere/source.md", "[[Target]]"]]));
|
||||
assert.equal(result.committed, true);
|
||||
assert.equal(result.indexed, 2);
|
||||
assert.deepEqual(result.errors, []);
|
||||
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["elsewhere/source.md"]);
|
||||
index.clear();
|
||||
assert.equal(index.size, 0);
|
||||
await index.rebuild(workspace(files));
|
||||
assert.equal(index.size, 2);
|
||||
});
|
||||
|
||||
test("updates during a rebuild survive its disk snapshot", async () => {
|
||||
const files = new Map([["Target.md", ""], ["source.md", "[[Target]]"]]);
|
||||
const io = workspace(files);
|
||||
let release!: () => void;
|
||||
const barrier = new Promise<void>(resolve => release = resolve);
|
||||
const index = new WorkspaceNoteIndex();
|
||||
const rebuild = index.rebuild({ ...io, read: async path => { await barrier; return io.read(path); } });
|
||||
await Promise.resolve();
|
||||
index.update("source.md", "No link");
|
||||
index.update("new.md", "[[Target]]");
|
||||
index.rename("new.md", "moved.md");
|
||||
release();
|
||||
await rebuild;
|
||||
assert.deepEqual(index.backlinks("Target.md").map(link => link.sourcePath), ["moved.md"]);
|
||||
});
|
||||
|
||||
test("workspace clear and a newer rebuild reject stale async results", async () => {
|
||||
let release!: () => void;
|
||||
const barrier = new Promise<void>(resolve => release = resolve);
|
||||
const index = new WorkspaceNoteIndex();
|
||||
const slow = index.rebuild({ list: async () => { await barrier; return [{ rel_path: "old.md", kind: "file" }]; }, read: async () => "" });
|
||||
index.clear();
|
||||
await index.rebuild(workspace(new Map([["new.md", ""]])));
|
||||
release();
|
||||
assert.equal((await slow).committed, false);
|
||||
assert.equal(index.resolve("", "old", "wiki").status, "missing");
|
||||
assert.deepEqual(index.resolve("", "new", "wiki"), { status: "resolved", path: "new.md" });
|
||||
});
|
||||
|
||||
test("read and list failures report incomplete coverage and remain rebuildable", async () => {
|
||||
const index = new WorkspaceNoteIndex();
|
||||
const io = workspace(new Map([["Target.md", ""], ["source.md", "[[Target]]"], ["blocked/note.md", ""]]));
|
||||
const result = await index.rebuild({
|
||||
list: async folder => { if (folder === "blocked") throw new Error("Folder unavailable"); return io.list(folder); },
|
||||
read: async path => { if (path === "source.md") throw new Error("File unavailable"); return io.read(path); },
|
||||
});
|
||||
assert.deepEqual(result.errors.map(error => [error.path, error.operation]), [["blocked", "list"], ["source.md", "read"]]);
|
||||
assert.equal(index.backlinks("Target.md").length, 0);
|
||||
await index.rebuild(io);
|
||||
assert.equal(index.backlinks("Target.md").length, 1);
|
||||
});
|
||||
@@ -1,166 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,159 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,77 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,145 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,129 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,81 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { pluginAccess } from "../src/lib/plugins/access.ts";
|
||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi, PluginCommand, PluginView } from "../src/lib/plugins/sdk.ts";
|
||||
|
||||
const view = (id: string, extra: Partial<PluginView> = {}): PluginView => ({ id, title: id, mount() {}, ...extra });
|
||||
const command = (id: string, extra: Partial<PluginCommand> = {}): PluginCommand => ({ id, title: id, run() {}, ...extra });
|
||||
|
||||
test("plugin access separates settings, launchers, and commands without reading titles", () => {
|
||||
const tools = pluginAccess("org.example.test", [command("open", { category: "open" }), command("configure")], [view("preferences", { settings: true }), view("tasks"), view("instance", { launcher: false })]);
|
||||
assert.deepEqual(tools.map(({ id, surface }) => [id, surface]), [["open", "open"], ["configure", "commands"], ["preferences", "settings"], ["tasks", "open"]]);
|
||||
});
|
||||
|
||||
test("installed RuneStone packages retain access before their next package update", () => {
|
||||
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings")])[0].surface, "settings");
|
||||
assert.deepEqual(pluginAccess("runestone.browser", [command("new-tab")], [view("tab-123")]).map(({ id, surface }) => [id, surface]), [["new-tab", "open"]]);
|
||||
assert.equal(pluginAccess("org.example.test", [], [view("settings")])[0].surface, "open");
|
||||
assert.equal(pluginAccess("runestone.local-autocomplete", [], [view("settings", { settings: false })])[0].surface, "open");
|
||||
assert.equal(pluginAccess("runestone.browser", [command("new-tab", { category: "action" })], [])[0].surface, "commands");
|
||||
});
|
||||
|
||||
test("command launchers retain the plugin action icon", () => {
|
||||
const tools = pluginAccess("runestone.git", [command("graph", { category: "open", icon: "git" })], []);
|
||||
assert.equal(tools[0].icon, "git");
|
||||
assert.equal(tools[0].surface, "open");
|
||||
});
|
||||
|
||||
test("settings listeners are removable and revoked before plugin cleanup", async () => {
|
||||
let api!: PluginApi, notify!: () => void;
|
||||
let received = 0, disposed = 0;
|
||||
const session = new ExternalSession("org.example.settings", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
settings: { read: async () => null, write: async () => {}, subscribe(listener) { notify = listener; return () => { disposed++; }; } },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
const off = api.settings.subscribe!(() => { received++; });
|
||||
notify(); assert.equal(received, 1);
|
||||
await off(); await off(); assert.equal(disposed, 1);
|
||||
api.settings.subscribe!(() => { received++; });
|
||||
await session.stop(); notify();
|
||||
assert.equal(received, 1); assert.equal(disposed, 2);
|
||||
assert.throws(() => api.settings.subscribe!(() => {}), /disabled/);
|
||||
});
|
||||
|
||||
test("invalid access metadata fails registration", async () => {
|
||||
for (const activate of [
|
||||
(api: PluginApi) => api.registerCommand(command("invalid", { category: "unknown" as "open" })),
|
||||
(api: PluginApi) => api.registerView(view("invalid", { settings: "yes" as unknown as boolean })),
|
||||
(api: PluginApi) => api.registerView(view("invalid", { launcher: "yes" as unknown as boolean })),
|
||||
]) {
|
||||
const session = new ExternalSession("org.example.invalid", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
|
||||
}, () => {}, () => {});
|
||||
await assert.rejects(session.start({ activate }), /category|boolean/);
|
||||
await session.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("settings windows permit model checks and cancellation", () => {
|
||||
const capability = JSON.parse(readFileSync(new URL("../src-tauri/capabilities/settings.json", import.meta.url), "utf8"));
|
||||
for (const permission of ["allow-completion-request", "allow-completion-cancel", "allow-plugins-data"]) assert(capability.permissions.includes(permission));
|
||||
});
|
||||
|
||||
test("view mount context distinguishes Settings from editor and dialog views", async () => {
|
||||
const surfaces: string[] = [];
|
||||
const session = new ExternalSession("org.example.context", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() }, settings: { read: async () => null, write: async () => {} },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(api) { api.registerView(view("settings", { mount(_element, context) { surfaces.push(context!.surface); } })); } });
|
||||
const target = { replaceChildren() {} } as unknown as HTMLElement;
|
||||
const disposeView = await session.mount("settings", target);
|
||||
await disposeView();
|
||||
const disposeSettings = await session.mount("settings", target, undefined, "settings");
|
||||
await disposeSettings(); await session.stop();
|
||||
assert.deepEqual(surfaces, ["view", "settings"]);
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,96 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||
import type { PluginApi, PluginDocumentType } from "../src/lib/plugins/sdk.ts";
|
||||
|
||||
const services = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
};
|
||||
const type: PluginDocumentType = {
|
||||
id: "board", title: "Board", icon: "kanban", extensions: ["md"],
|
||||
identify: (_path, source) => source === "board" ? { id: "stable" } : null,
|
||||
create: { label: "New board", defaultName: "Untitled board", extension: "md", contents: () => "board" },
|
||||
mount: () => {},
|
||||
};
|
||||
|
||||
test("document renames pass the stable identity and stop after shutdown", async () => {
|
||||
let api!: PluginApi;
|
||||
const calls: unknown[] = [];
|
||||
const session = new ExternalSession("fixture", services, () => {}, () => {}, undefined, undefined,
|
||||
async (document, name) => { calls.push({ document, name }); return "Renamed.md"; });
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.equal(await api.renameDocument!({ id: "stable", path: "Board.md" }, "Renamed"), "Renamed.md");
|
||||
assert.deepEqual(calls, [{ document: { id: "stable", path: "Board.md" }, name: "Renamed" }]);
|
||||
await session.stop();
|
||||
assert.throws(() => api.renameDocument!({ id: "stable", path: "Board.md" }, "Other"), /disabled/);
|
||||
assert.equal(calls.length, 1);
|
||||
});
|
||||
|
||||
test("binary document registration preserves bytes and revokes reads on shutdown", async () => {
|
||||
let api!: PluginApi;
|
||||
const bytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0xff, 0x00]);
|
||||
const paths: string[] = [];
|
||||
const session = new ExternalSession("fixture", {
|
||||
...services, workspace: { ...services.workspace, readBytes: async path => { paths.push(path); return bytes; } },
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
api.registerDocumentType({ ...type, id: "pdf", extensions: ["pdf"], content: "binary", create: undefined });
|
||||
} });
|
||||
assert.equal(session.documentTypes.get("pdf")?.content, "binary");
|
||||
assert.deepEqual(await api.workspace.readBytes!("report.pdf"), bytes);
|
||||
assert.deepEqual(paths, ["report.pdf"]);
|
||||
assert.throws(() => api.registerDocumentType({ ...type, content: "invalid" as "binary" }), /content type/);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.readBytes!("report.pdf"), /disabled/);
|
||||
});
|
||||
|
||||
test("document types have independent registrations and reject invalid creation actions", async () => {
|
||||
let api!: PluginApi;
|
||||
const session = new ExternalSession("fixture", services, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; api.registerDocumentType(type); } });
|
||||
assert.equal(session.documentTypes.get("board")?.identify("Board.md", "board")?.id, "stable");
|
||||
assert.equal(session.documentTypes.get("board")?.identify("Note.md", "plain"), null);
|
||||
assert.throws(() => api.registerDocumentType(type), /duplicate/);
|
||||
assert.throws(() => api.registerDocumentType({ ...type, id: "other", create: { ...type.create!, extension: "exe" } }), /Invalid document creation/);
|
||||
await session.stop();
|
||||
assert.equal(session.documentTypes.size, 0);
|
||||
assert.throws(() => api.registerDocumentType(type), /disabled/);
|
||||
});
|
||||
|
||||
test("two document mounts retain independent context and clean up once", async () => {
|
||||
const mounted: string[] = [], cleaned: string[] = [];
|
||||
const session = new ExternalSession("fixture", services, () => {}, () => {});
|
||||
await session.start({ activate(api) {
|
||||
api.registerDocumentType({ ...type, mount(_node, context) { mounted.push(context.path); return () => { cleaned.push(context.id); }; } });
|
||||
} });
|
||||
const element = () => ({ replaceChildren() {} }) as unknown as HTMLElement;
|
||||
const first = await session.mount("board", element(), { id: "first", path: "One.md" });
|
||||
await session.mount("board", element(), { id: "second", path: "Two.md" });
|
||||
assert.deepEqual(mounted, ["One.md", "Two.md"]);
|
||||
await first(); await first();
|
||||
assert.deepEqual(cleaned, ["first"]);
|
||||
await session.stop();
|
||||
assert.deepEqual(cleaned, ["first", "second"]);
|
||||
});
|
||||
|
||||
test("document opening and workspace subscriptions stop with their plugin", async () => {
|
||||
let api!: PluginApi;
|
||||
let listener: (() => void) | undefined;
|
||||
let notifications = 0, removed = 0;
|
||||
const opened: string[] = [];
|
||||
const session = new ExternalSession("fixture", {
|
||||
...services,
|
||||
workspace: { ...services.workspace, subscribe(callback) { listener = callback; return () => { removed++; }; } },
|
||||
}, () => {}, () => {}, undefined, async path => { opened.push(path); });
|
||||
await session.start({ activate(value) { api = value; api.workspace.subscribe!(() => { notifications++; }); } });
|
||||
await api.openDocument("Board.md"); listener!();
|
||||
assert.deepEqual(opened, ["Board.md"]);
|
||||
assert.equal(notifications, 1);
|
||||
await session.stop(); listener!();
|
||||
assert.equal(notifications, 1);
|
||||
assert.equal(removed, 1);
|
||||
assert.throws(() => api.openDocument("Board.md"), /disabled/);
|
||||
});
|
||||
@@ -1,176 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,59 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||
import { ContributionRegistry } from "../src/lib/plugins/registry.ts";
|
||||
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
||||
|
||||
test("Git and file access stop before plugin cleanup", async () => {
|
||||
const calls: unknown[] = [];
|
||||
let api!: PluginApi;
|
||||
const registry = new ContributionRegistry();
|
||||
const session = new ExternalSession("test.git", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
|
||||
openFile: async path => { calls.push(path); },
|
||||
git: {
|
||||
status: async () => ({ available: true, repository: true, branch: "main", changes: [] }),
|
||||
diff: async (path, staged) => { calls.push([path, staged]); return "diff"; },
|
||||
stage: async paths => { calls.push(paths); }, unstage: async paths => { calls.push(paths); },
|
||||
commit: async message => { calls.push(message); }, blame: async () => null,
|
||||
push: async () => { calls.push('push'); }, pull: async () => { calls.push('pull'); }, graph: async () => ({ commits: [] }),
|
||||
},
|
||||
}, () => {}, () => {}, registry);
|
||||
await session.start({ activate(value) { api = value; api.contribute("git", { blame: (path, line) => api.git!.blame(path, line) }); } });
|
||||
await api.openFile!("notes.md");
|
||||
assert.equal(await api.git!.diff("notes.md", true), "diff");
|
||||
await api.git!.stage(["notes.md"]);
|
||||
assert.deepEqual(calls, ["notes.md", ["notes.md", true], ["notes.md"]]);
|
||||
await api.git!.push();
|
||||
await api.git!.pull();
|
||||
assert.deepEqual(await api.git!.graph(), { commits: [] });
|
||||
assert.deepEqual(calls.slice(-2), ['push', 'pull']);
|
||||
await session.stop();
|
||||
assert.equal(registry.get("git"), undefined);
|
||||
assert.throws(() => api.openFile!("notes.md"), /disabled/);
|
||||
for (const action of [() => api.git!.push(), () => api.git!.pull(), () => api.git!.graph()]) assert.throws(action, /disabled/);
|
||||
for (const action of [() => api.git!.status(), () => api.git!.diff("a", false), () => api.git!.stage(["a"]), () => api.git!.unstage(["a"]), () => api.git!.commit("a"), () => api.git!.blame("a", 1)]) assert.throws(action, /disabled/);
|
||||
});
|
||||
|
||||
test("view replacement rejects unknown destinations and stops after disposal", async () => {
|
||||
let api!: PluginApi;
|
||||
const calls: unknown[] = [];
|
||||
const session = new ExternalSession("test.boards", {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} }, assets: { read: async () => new Uint8Array() },
|
||||
}, () => {}, () => {}, new ContributionRegistry(), undefined, undefined, undefined,
|
||||
(current, next) => calls.push([current, next]), (document, next) => calls.push([document, next]));
|
||||
await session.start({ activate(value) {
|
||||
api = value;
|
||||
for (const id of ["a", "b"]) api.registerView({ id, title: id, placement: "editor", mount() {} });
|
||||
api.registerView({ id: "sidebar", title: "Sidebar", placement: "sidebar", navigation: true, icon: "git", mount() {} });
|
||||
} });
|
||||
api.replaceView!("a", "b");
|
||||
api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "b");
|
||||
assert.deepEqual(calls, [["a", "b"], [{ id: "legacy", path: "Board.md" }, "b"]]);
|
||||
assert.throws(() => api.replaceView!("missing", "b"), /Unknown/);
|
||||
assert.throws(() => api.replaceDocumentWithView!({ id: "legacy", path: "Board.md" }, "missing"), /Unknown/);
|
||||
await session.stop();
|
||||
assert.throws(() => api.replaceView!("a", "b"), /disabled/);
|
||||
});
|
||||
@@ -1,238 +0,0 @@
|
||||
// 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(); }
|
||||
+2
-40
@@ -1,40 +1,2 @@
|
||||
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);
|
||||
}
|
||||
// RuneStone_Terminal imports this path for its smoke test. The helper lives in the shared smoke harness.
|
||||
export * from "../tests/smoke/_harness/pluginMocks.mjs";
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, mkdir, readFile, writeFile, rm, realpath } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
// @ts-ignore The build tool is a JavaScript module.
|
||||
import { packagePlugin } from "./packagePlugin.mjs";
|
||||
|
||||
test("plugin packaging rejects invalid release inputs before writing an archive", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "runestone-packaging-"));
|
||||
const source = join(root, "plugin"), output = join(root, "releases");
|
||||
await mkdir(source);
|
||||
const manifest = {
|
||||
schemaVersion: 1, apiVersion: 1, id: "org.test.demo", name: "Demo", author: "Test",
|
||||
description: "Test plugin", version: "1.0.0", entry: "main.js", access: "full-app",
|
||||
};
|
||||
const save = async (changes = {}) => writeFile(join(source, "plugin.json"), JSON.stringify({ ...manifest, ...changes }));
|
||||
try {
|
||||
await assert.rejects(packagePlugin(source, output), /plugin.json at its root/);
|
||||
await save();
|
||||
await assert.rejects(packagePlugin(source, output), /entry module is missing/);
|
||||
await writeFile(join(source, "main.js"), "export function activate() {}");
|
||||
for (const [changes, message] of [
|
||||
[{ id: "../escape" }, /ID is invalid/],
|
||||
[{ version: "1.0" }, /version such as/],
|
||||
[{ version: "1.0.0A" }, /version such as/],
|
||||
[{ version: "1.0.0a1" }, /version such as/],
|
||||
[{ version: "1.0.0-beta" }, /version such as/],
|
||||
[{ version: "1.0.0+build" }, /version such as/],
|
||||
[{ entry: "../main.js" }, /compiled JavaScript/],
|
||||
[{ apiVersion: 99 }, /Unsupported/],
|
||||
[{ author: "" }, /valid author/],
|
||||
] as const) {
|
||||
await save(changes);
|
||||
await assert.rejects(packagePlugin(source, output), message);
|
||||
}
|
||||
await save();
|
||||
await assert.rejects(packagePlugin(source, source), /outside the plugin folder/);
|
||||
await writeFile(join(source, "invalid file.txt"), "test");
|
||||
await assert.rejects(packagePlugin(source, output), /Invalid package path/);
|
||||
await rm(join(source, "invalid file.txt"));
|
||||
await writeFile(join(root, "package.json"), JSON.stringify({ name: "test-plugin" }));
|
||||
const path = await packagePlugin(source);
|
||||
assert.equal(path, join(await realpath(output), "org.test.demo-1.0.0.zip"));
|
||||
const first = await readFile(path);
|
||||
await packagePlugin(source, output);
|
||||
assert.deepEqual(await readFile(path), first);
|
||||
await writeFile(join(source, "main.js"), "export function activate() { return 1; }");
|
||||
await assert.rejects(packagePlugin(source), /different contents/);
|
||||
assert.deepEqual(await readFile(path), first);
|
||||
await writeFile(join(source, "main.js"), "export function activate() {}");
|
||||
for (const version of ["0.2.28a", "0.2.28b", "0.2.28aa"]) {
|
||||
await save({ version });
|
||||
const hotfix = await packagePlugin(source, output);
|
||||
assert.equal(hotfix, join(await realpath(output), `org.test.demo-${version}.zip`));
|
||||
assert.ok((await readFile(hotfix)).length > 0);
|
||||
assert.deepEqual(await readFile(path), first);
|
||||
}
|
||||
} finally {
|
||||
// mkdtemp returns this test's unique directory under the operating system temp folder.
|
||||
assert.equal(root.startsWith(join(tmpdir(), "runestone-packaging-")), true);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -1,357 +0,0 @@
|
||||
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();
|
||||
}
|
||||
@@ -1,202 +0,0 @@
|
||||
import { mockFeaturePlugins } from "./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(); }
|
||||
@@ -1,89 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { ContributionRegistry, pluginHost } from "../src/lib/plugins/registry.ts";
|
||||
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
|
||||
import { existsSync } from "node:fs";
|
||||
// The Table Formulas package comes from a sibling repository. Run `pnpm build:plugins` to build it.
|
||||
const tableFormulasEntry = new URL("../plugin-packages/table-formulas/main.js", import.meta.url);
|
||||
const tableFormulas = existsSync(tableFormulasEntry) ? await import(tableFormulasEntry.href) : undefined;
|
||||
const activate = tableFormulas?.activate;
|
||||
const needsTableFormulas = { skip: tableFormulas ? false : "the Table Formulas package is not built; run pnpm build:plugins" };
|
||||
import { renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
|
||||
|
||||
const services = {
|
||||
workspace: { list: async () => [], read: async () => "", write: async () => {} },
|
||||
settings: { read: async () => null, write: async () => {} },
|
||||
assets: { read: async () => new Uint8Array() },
|
||||
};
|
||||
|
||||
test("optional workspace creation and reads stop when the plugin is disabled", async () => {
|
||||
const files = new Map<string, string>();
|
||||
let api!: PluginApi;
|
||||
const session = new ExternalSession("workspace-test", {
|
||||
...services,
|
||||
workspace: {
|
||||
...services.workspace,
|
||||
readOptional: async path => files.get(path) ?? null,
|
||||
create: async (path, contents) => { if (files.has(path)) throw new Error("exists"); files.set(path, contents); },
|
||||
},
|
||||
}, () => {}, () => {});
|
||||
await session.start({ activate(value) { api = value; } });
|
||||
assert.equal(await api.workspace.readOptional!("board.json"), null);
|
||||
await api.workspace.create!("board.json", "{}");
|
||||
assert.equal(await api.workspace.readOptional!("board.json"), "{}");
|
||||
await assert.rejects(api.workspace.create!("board.json", "replacement"), /exists/);
|
||||
await session.stop();
|
||||
assert.throws(() => api.workspace.create!("other.json", "{}"), /disabled/);
|
||||
assert.throws(() => api.workspace.readOptional!("board.json"), /disabled/);
|
||||
assert.equal(files.size, 1);
|
||||
});
|
||||
test("core starts without optional features and formula packages preserve source when stopped", needsTableFormulas, async () => {
|
||||
assert.equal(pluginHost.get("terminal"), undefined);
|
||||
assert.equal(pluginHost.get("tableFormulas"), undefined);
|
||||
const source = "| A | B |\n| --- | --- |\n| 2 | =A2*3 |\n";
|
||||
assert.doesNotMatch(renderMarkdownHtml(source, new Map()), /md-table-formula/);
|
||||
const session = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
|
||||
await session.start({ activate });
|
||||
const enabled = renderMarkdownHtml(source, new Map());
|
||||
assert.match(enabled, />6<\/span>/);
|
||||
await session.stop();
|
||||
for (const html of [renderMarkdownHtml(source, new Map()), ...renderMarkdownSections(source, new Map()).map(section => section.html)]) {
|
||||
assert.doesNotMatch(html, /md-table-formula/);
|
||||
assert.match(html, /=A2\*3/);
|
||||
assert.match(html, /<table>/);
|
||||
}
|
||||
const next = new ExternalSession("runestone.table-formulas", services, () => {}, () => {});
|
||||
await next.start({ activate });
|
||||
assert.equal(renderMarkdownHtml(source, new Map()), enabled);
|
||||
await next.stop();
|
||||
});
|
||||
|
||||
test("package contribution conflicts preserve the first owner and revoke access before cleanup", needsTableFormulas, async () => {
|
||||
const registry = new ContributionRegistry();
|
||||
const first = new ExternalSession("first", services, () => {}, () => {}, registry);
|
||||
const second = new ExternalSession("second", services, () => {}, () => {}, registry);
|
||||
let api!: PluginApi;
|
||||
await first.start({ activate(value) { api = value; activate(api); } });
|
||||
const contribution = registry.get("tableFormulas");
|
||||
await assert.rejects(second.start({ activate }), /already registered/);
|
||||
await second.stop();
|
||||
assert.equal(registry.get("tableFormulas"), contribution);
|
||||
api.onDispose(() => {
|
||||
assert.equal(registry.get("tableFormulas"), undefined);
|
||||
assert.throws(() => api.contribute("tableFormulas", contribution!), /disabled/);
|
||||
});
|
||||
await first.stop();
|
||||
});
|
||||
|
||||
test("partial activation and failed cleanup cannot retain feature contributions", needsTableFormulas, async () => {
|
||||
const registry = new ContributionRegistry();
|
||||
const session = new ExternalSession("failed", services, () => {}, () => {}, registry);
|
||||
await assert.rejects(session.start({ activate(api) {
|
||||
activate(api);
|
||||
api.onDispose(() => { throw new Error("Cleanup failed"); });
|
||||
throw new Error("Activation failed");
|
||||
} }), /Activation failed/);
|
||||
await assert.rejects(session.stop(), /Cleanup failed/);
|
||||
assert.equal(registry.get("tableFormulas"), undefined);
|
||||
});
|
||||
@@ -1,121 +0,0 @@
|
||||
// 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();
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { markdownImages, renderMarkdownHtml, renderMarkdownSections } from "../src/lib/workspace/noteHtml.ts";
|
||||
|
||||
const render = (text: string) => renderMarkdownHtml(text, new Map());
|
||||
|
||||
test("writing sections retain exact source ranges and document-wide references", () => {
|
||||
const source = '\uFEFF---\r\ntitle: Draft\r\n---\r\n\r\n# Heading\r\n\r\n- Parent\r\n - Child\r\n\r\nA [reference][ref].\r\n\r\n[ref]: https://example.com\r\n';
|
||||
const sections = renderMarkdownSections(source, new Map());
|
||||
assert.equal(sections.map(section => source.slice(section.start, section.end)).join(""), source);
|
||||
assert.equal(sections.length, 4);
|
||||
assert.match(sections[2].html, /<ul>[\s\S]*<ul>/);
|
||||
assert.match(sections[3].html, /href="https:\/\/example.com"/);
|
||||
const paragraph = sections[3];
|
||||
const edited = source.slice(0, paragraph.start) + 'Changed paragraph.\r\n' + source.slice(paragraph.end);
|
||||
assert.equal(edited.slice(0, paragraph.start), source.slice(0, paragraph.start));
|
||||
});
|
||||
|
||||
test("writing exposes empty and reference-only documents for editing", () => {
|
||||
for (const source of ["", "\n\n", "[ref]: https://example.com\n"]) {
|
||||
assert.deepEqual(renderMarkdownSections(source, new Map()), [{ start: 0, end: source.length, html: "" }]);
|
||||
}
|
||||
});
|
||||
|
||||
test("Mermaid fences render diagram containers with escaped, copyable source", () => {
|
||||
const html = render('```mermaid\nflowchart LR\n A["<script>bad</script>"] --> B\n```');
|
||||
assert.match(html, /class="md-mermaid"/);
|
||||
assert.match(html, /aria-label="Mermaid diagram"/);
|
||||
assert.match(html, /<summary>Diagram source<\/summary>/);
|
||||
assert.match(html, /<script>bad<\/script>/);
|
||||
assert.doesNotMatch(html, /<script>/);
|
||||
assert.doesNotMatch(render('```js\nconst x = 1;\n```'), /md-mermaid/);
|
||||
});
|
||||
|
||||
test("reader joins soft-wrapped lines and preserves paragraph boundaries", () => {
|
||||
assert.equal(render("First line\ncontinues here.\n\nSecond paragraph."), "<p>First line\ncontinues here.</p>\n<p>Second paragraph.</p>\n");
|
||||
assert.match(render("Hard break \nnext line"), /Hard break<br>\nnext line/);
|
||||
});
|
||||
|
||||
test("reader preserves nested lists, ordered starts and multi-paragraph items", () => {
|
||||
const html = render("7. Parent\n - Nested **item**\n - Other\n8. Next\n\n Another paragraph.\n");
|
||||
assert.match(html, /<ol start="7">/);
|
||||
assert.match(html, /<li>\n<p>Parent<\/p>\n<ul>\n<li>Nested <strong>item<\/strong><\/li>/);
|
||||
assert.match(html, /<p>Next<\/p>\n<p>Another paragraph\.<\/p>/);
|
||||
});
|
||||
|
||||
test("reader renders aligned tables and read-only nested tasks", () => {
|
||||
const html = render("| Left | Right |\n| :--- | ---: |\n| **a** | 2 |\n\n- [x] Done\n - [ ] Nested\n");
|
||||
assert.match(html, /class="md-table-scroll"><table>/);
|
||||
assert.match(html, /<th style="text-align:right">Right<\/th>/);
|
||||
assert.equal((html.match(/type="checkbox" disabled/g) || []).length, 2);
|
||||
assert.equal((html.match(/ checked>/g) || []).length, 1);
|
||||
assert.doesNotMatch(html, /\[x\]|\[ \]/);
|
||||
});
|
||||
|
||||
test("reader keeps code literal and escapes embedded HTML", () => {
|
||||
const html = render('```js\nconst text = "[[note]] **bold** <script>alert(1)</script>";\n```\n\n`[[literal]]`\n\n<img src=x onerror=alert(1)>');
|
||||
assert.match(html, /aria-label="Copy code"/);
|
||||
assert.match(html, /\[\[note\]\] \*\*bold\*\* <script>/);
|
||||
assert.match(html, /<code>\[\[literal\]\]<\/code>/);
|
||||
assert.doesNotMatch(html, /<script>|<img|class="wiki"|<strong>/);
|
||||
});
|
||||
|
||||
test("table cell line breaks render without enabling arbitrary HTML", () => {
|
||||
const html = render('| Notes |\n| --- |\n| First<br>Second<BR />Third<br/>Fourth |');
|
||||
assert.match(html, /First<br>\nSecond<br>\nThird<br>\nFourth/);
|
||||
assert.doesNotMatch(html, /<br/i);
|
||||
assert.match(render('`<br>`'), /<code><br><\/code>/);
|
||||
assert.doesNotMatch(render('<br onclick="alert(1)">'), /<br /);
|
||||
});
|
||||
|
||||
test("frontmatter is collapsed separately from document headings", () => {
|
||||
const html = render("\uFEFF---\r\ntitle: Notes\r\ntags: [work]\r\n---\r\n# Document\n");
|
||||
assert.match(html, /^<details class="md-properties"><summary>Properties<\/summary><pre>title: Notes/);
|
||||
assert.match(html, /<h1>Document<\/h1>/);
|
||||
assert.doesNotMatch(html, /<h2>|<hr>|details[^>]*open/);
|
||||
assert.match(render("---\n\nOrdinary rule"), /^<hr>/);
|
||||
});
|
||||
|
||||
test("wiki links, aliases and reference images retain their targets", () => {
|
||||
const source = 'See [[notes/one|First note]] and [second](second.md).\n\n![A **diagram**][diagram]\n\n![[assets/screenshot.png|Screenshot]]\n\n[diagram]: assets/my%20diagram.png "Diagram"\n';
|
||||
const urls = new Map([['assets/my%20diagram.png', 'data:image/png;base64,AA=='], ['assets/screenshot.png', 'data:image/png;base64,BB==']]);
|
||||
const html = renderMarkdownHtml(source, urls);
|
||||
assert.match(html, /href="notes\/one" data-kind="wiki" class="wiki">First note/);
|
||||
assert.match(html, /href="second.md" data-kind="md"/);
|
||||
assert.match(html, /alt="A diagram"/);
|
||||
assert.match(html, /data-md-kind="wiki"/);
|
||||
assert.deepEqual(markdownImages(source + '\n`![[ignored.png]]`\n\n```\n\n```'), ['assets/my%20diagram.png', 'assets/screenshot.png']);
|
||||
});
|
||||
|
||||
test("reader rejects executable links and image URL injection", () => {
|
||||
const html = render('[bad](javascript:alert%281%29) [[javascript:alert(1)]] ');
|
||||
assert.doesNotMatch(html, /<a |<img /);
|
||||
const image = renderMarkdownHtml('![[safe.png]]', new Map([['safe.png', 'javascript:alert(1)']]));
|
||||
assert.match(image, /Image unavailable/);
|
||||
});
|
||||
|
||||
test("note callouts separate their title from the Markdown body", () => {
|
||||
const html = render('> [!tip] Keep context close\n> Use **notes** beside code.\n>\n> A second paragraph.');
|
||||
assert.match(html, /class="md-callout" data-callout="tip"/);
|
||||
assert.match(html, /class="md-callout-title">Keep context close<\/strong>Use <strong>notes<\/strong>/);
|
||||
assert.match(html, /<p>A second paragraph\.<\/p>/);
|
||||
});
|
||||
@@ -1,76 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { planRename, planTitleRename, planMarkdownTitleRename, planDocumentTitleRename } from "../src/lib/workspace/renamePath.ts";
|
||||
|
||||
test("rename in a folder keeps the parent", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", "b.md"), {
|
||||
action: "rename",
|
||||
to: "notes/b.md",
|
||||
});
|
||||
});
|
||||
|
||||
test("same name is a no-op", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", "a.md"), { action: "noop" });
|
||||
});
|
||||
|
||||
test("path separators are rejected", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", "foo/bar"), {
|
||||
action: "error",
|
||||
message: "Name cannot contain a path separator",
|
||||
});
|
||||
assert.deepEqual(planRename("notes/a.md", "foo\\bar"), {
|
||||
action: "error",
|
||||
message: "Name cannot contain a path separator",
|
||||
});
|
||||
});
|
||||
|
||||
test("empty name is rejected", () => {
|
||||
assert.deepEqual(planRename("notes/a.md", " "), {
|
||||
action: "error",
|
||||
message: "Name is empty",
|
||||
});
|
||||
});
|
||||
|
||||
test("root file rename stays at the root", () => {
|
||||
assert.deepEqual(planRename("inbox.md", "todo.md"), {
|
||||
action: "rename",
|
||||
to: "todo.md",
|
||||
});
|
||||
});
|
||||
|
||||
test("title rename keeps the existing extension", () => {
|
||||
assert.deepEqual(planTitleRename("notes/inbox.md", "hello"), {
|
||||
action: "rename",
|
||||
to: "notes/hello.md",
|
||||
});
|
||||
assert.deepEqual(planTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
|
||||
});
|
||||
|
||||
test("title rename keeps a typed extension", () => {
|
||||
assert.deepEqual(planTitleRename("notes/inbox.md", "hello.txt"), {
|
||||
action: "rename",
|
||||
to: "notes/hello.txt",
|
||||
});
|
||||
});
|
||||
|
||||
test("writing titles preserve Markdown extensions and allow dots in names", () => {
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "Release 1.2"), { action: "rename", to: "notes/Release 1.2.md" });
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.MD", " Renamed.md "), { action: "rename", to: "notes/Renamed.MD" });
|
||||
assert.deepEqual(planMarkdownTitleRename("inbox.markdown", "Renamed"), { action: "rename", to: "Renamed.markdown" });
|
||||
assert.deepEqual(planMarkdownTitleRename("inbox.mdown", "Renamed"), { action: "rename", to: "Renamed.mdown" });
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md", "inbox"), { action: "noop" });
|
||||
assert.deepEqual(planMarkdownTitleRename("notes/inbox.md.md", "inbox.md"), { action: "noop" });
|
||||
for (const name of ["", " ", ".md", "../escape", "folder/note", "folder\\note"]) {
|
||||
assert.equal(planMarkdownTitleRename("notes/inbox.md", name).action, "error", name);
|
||||
}
|
||||
});
|
||||
|
||||
test("document names retain their format and cannot hide or move the file", () => {
|
||||
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Renamed"), { action: "rename", to: "Projects/Renamed.md" });
|
||||
assert.deepEqual(planDocumentTitleRename("Projects/Board.md", "Release 1.2"), { action: "rename", to: "Projects/Release 1.2.md" });
|
||||
assert.deepEqual(planDocumentTitleRename("Projects/Board.MD", "Renamed.md"), { action: "rename", to: "Projects/Renamed.MD" });
|
||||
assert.deepEqual(planDocumentTitleRename("Report.pdf", "Next.pdf"), { action: "rename", to: "Next.pdf" });
|
||||
assert.deepEqual(planDocumentTitleRename("Board.md", "Board"), { action: "noop" });
|
||||
for (const name of ["", " ", ".md", ".hidden", "../escape", "folder/name", "folder\\name", "a:b", "a?b"])
|
||||
assert.equal(planDocumentTitleRename("Board.md", name).action, "error", name);
|
||||
});
|
||||
@@ -1,132 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,158 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,175 +0,0 @@
|
||||
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(); }
|
||||
|
||||
@@ -1,175 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,32 +0,0 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings } from "../src/lib/workspace/settings.ts";
|
||||
|
||||
test("missing or damaged preferences keep safe defaults", () => {
|
||||
for (const raw of [null, "{broken", "null", "[]", "42", '"text"']) {
|
||||
assert.deepEqual(parseSettings(raw), DEFAULT_SETTINGS);
|
||||
}
|
||||
for (const autosaveSeconds of [0, -1, 301, 1.5, "10", null]) {
|
||||
assert.deepEqual(parseSettings(JSON.stringify({ autosaveEnabled: false, autosaveSeconds, showInternalFolder: false })), { autosaveEnabled: false, autosaveSeconds: 5, showInternalFolder: false });
|
||||
}
|
||||
assert.deepEqual(parseSettings('{"autosaveEnabled":"false","autosaveSeconds":10}'), { autosaveEnabled: true, autosaveSeconds: 10, showInternalFolder: false });
|
||||
});
|
||||
|
||||
test("preferences persist and load at both interval limits", () => {
|
||||
const store = new Map<string, string>();
|
||||
for (const autosaveSeconds of [1, 23, 300]) {
|
||||
const settings = { autosaveEnabled: false, autosaveSeconds, showInternalFolder: false };
|
||||
saveSettings({ setItem: (key, value) => { store.set(key, value); } }, settings);
|
||||
assert.deepEqual(parseSettings(store.get(SETTINGS_KEY)!), settings);
|
||||
}
|
||||
});
|
||||
|
||||
test("invalid changes never reach storage and storage failures reach the caller", () => {
|
||||
let writes = 0;
|
||||
const storage = { setItem: () => { writes++; } };
|
||||
for (const autosaveSeconds of [NaN, Infinity, 0, 301, 2.5]) {
|
||||
assert.throws(() => saveSettings(storage, { autosaveEnabled: true, autosaveSeconds, showInternalFolder: false }));
|
||||
}
|
||||
assert.equal(writes, 0);
|
||||
assert.throws(() => saveSettings({ setItem: () => { throw new Error("Storage unavailable"); } }, { ...DEFAULT_SETTINGS }), /Storage unavailable/);
|
||||
});
|
||||
@@ -1,109 +0,0 @@
|
||||
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(); }
|
||||
@@ -1,96 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,92 +0,0 @@
|
||||
// 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(); }
|
||||
@@ -1,96 +0,0 @@
|
||||
// Use a debug app with TAURI_CONFIG identifier com.runestone.spelling-test,
|
||||
// a hidden window, and a separate WEBVIEW2_USER_DATA_FOLDER outside Vite's watch paths.
|
||||
// Set WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS=--remote-debugging-port=9224 before launch.
|
||||
// The normal app identifier is rejected before this test writes any workspace files.
|
||||
import { createRequire } from "node:module";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.connectOverCDP(process.env.SPELLING_CDP_URL || "http://127.0.0.1:9224");
|
||||
const page = browser.contexts()[0].pages()[0];
|
||||
page.setDefaultTimeout(15000);
|
||||
try {
|
||||
await page.goto(process.env.SPELLING_APP_URL || "http://localhost:1420");
|
||||
const data = await page.evaluate(async () => {
|
||||
const { appDataDir } = await import("/node_modules/@tauri-apps/api/path.js");
|
||||
return appDataDir();
|
||||
});
|
||||
assert.match(data, /[\\/]com\.runestone\.spelling-test[\\/]?$/, "Use the isolated spelling-test app identifier");
|
||||
const workspace = resolve(process.env.SPELLING_WORKSPACE || ".audit/spelling-workspace");
|
||||
await mkdir(workspace, { recursive: true });
|
||||
await writeFile(resolve(workspace, "Spelling.md"), "# Spelling\n\nI recieved a letter.\n");
|
||||
await page.evaluate(async path => {
|
||||
const { invoke } = await import("/node_modules/@tauri-apps/api/core.js");
|
||||
await invoke("workspace_open", { path });
|
||||
}, workspace);
|
||||
await page.reload();
|
||||
await page.locator('[data-tree-rel="Spelling.md"]').click();
|
||||
const editor = page.locator(".cm-content");
|
||||
await editor.waitFor();
|
||||
const line = page.getByText("I recieved a letter.", { exact: true });
|
||||
const rect = await line.boundingBox();
|
||||
await line.click();
|
||||
const before = await editor.innerText();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.type(" TEST");
|
||||
const typed = await editor.innerText();
|
||||
assert.notEqual(typed, before);
|
||||
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
|
||||
const menu = page.getByRole("menu", { name: "Spelling actions", exact: true });
|
||||
await menu.waitFor();
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: ".audit/spelling-native.png" });
|
||||
const undo = menu.getByRole("menuitem", { name: "Undo Ctrl+Z", exact: true });
|
||||
assert.equal(await undo.isEnabled(), true, "The native Undo command is enabled after typing");
|
||||
await undo.click();
|
||||
await page.waitForFunction(previous => document.querySelector(".cm-content")?.innerText !== previous, typed);
|
||||
const remaining = (await editor.innerText()).match(/^I recieved a letter\.(.*)$/m)?.[1];
|
||||
assert.ok(remaining !== undefined && remaining.length < " TEST".length && " TEST".startsWith(remaining), "Native Undo reduces the appended text and preserves the original paragraph");
|
||||
// WebView2 and CodeMirror can group typing differently. Restore the fixture through editor history.
|
||||
for (let attempt = 0; attempt < 8 && await editor.innerText() !== before; attempt++) {
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
}
|
||||
assert.equal(await editor.innerText(), before, "Bounded keyboard Undo restores the exact original editor text");
|
||||
console.log("PASS: real WebView2 Undo reduces the typed text, and bounded editor Undo restores the fixture.");
|
||||
|
||||
await page.mouse.click(rect.x + 42, rect.y + rect.height / 2, { button: "right" });
|
||||
await menu.waitFor();
|
||||
const suggestion = menu.getByRole("menuitem", { name: "received", exact: true });
|
||||
if (await suggestion.count()) {
|
||||
await suggestion.click();
|
||||
await page.waitForFunction(() => document.querySelector(".cm-content")?.innerText.includes("I received a letter."));
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.waitForFunction(() => document.querySelector(".cm-content")?.innerText.includes("I recieved a letter."));
|
||||
console.log("PASS: native spelling correction and editor undo.");
|
||||
} else {
|
||||
await page.keyboard.press("Escape");
|
||||
assert.notEqual(process.env.REQUIRE_NATIVE_SUGGESTIONS, "1", "The test WebView2 profile supplied no spelling suggestions");
|
||||
console.log("SKIP: native spelling correction. This WebView2 profile supplied no suggestions. Desktop acceptance is still required.");
|
||||
}
|
||||
for (const kind of ["input", "textarea", "dialog"]) {
|
||||
await page.evaluate(kind => {
|
||||
const field = document.createElement(kind === "input" ? "input" : "textarea");
|
||||
field.id = "native-spelling-field"; field.spellcheck = true;
|
||||
field.value = "I recieved a letter.";
|
||||
field.style.cssText = "position:fixed;left:250px;top:200px;width:500px;height:100px;font:16px/24px Arial;padding:10px;z-index:100";
|
||||
if (kind === "dialog") { const dialog = document.createElement("dialog"); dialog.id = "native-spelling-dialog"; dialog.append(field); document.body.append(dialog); dialog.showModal(); }
|
||||
else document.body.append(field);
|
||||
field.focus();
|
||||
}, kind);
|
||||
const field = page.locator("#native-spelling-field"), box = await field.boundingBox();
|
||||
await page.mouse.click(box.x + 48, box.y + (kind === "input" ? box.height / 2 : 22), { button: "right" });
|
||||
await menu.getByRole("menuitem", { name: "received", exact: true }).click();
|
||||
assert.equal(await field.inputValue(), "I received a letter.", kind + " corrects the clicked word");
|
||||
await page.keyboard.press("Control+z");
|
||||
assert.equal(await field.inputValue(), "I recieved a letter.", kind + " retains undo");
|
||||
await page.evaluate(() => { document.getElementById("native-spelling-field")?.remove(); document.getElementById("native-spelling-dialog")?.remove(); });
|
||||
}
|
||||
console.log("PASS: native spelling corrections and undo in inputs, card textareas, and top-layer dialogs.");
|
||||
} finally {
|
||||
await page.keyboard.press("Escape").catch(() => {});
|
||||
await browser.close();
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { splitPane, removePane, paneBounds, containsPane } from "../src/lib/workspace/splitLayout.ts";
|
||||
|
||||
test("nested splits preserve the source and divide the requested pane", () => {
|
||||
const right = splitPane("a", "a", "b", "right");
|
||||
const nested = splitPane(right, "b", "c", "down");
|
||||
assert.deepEqual(paneBounds(nested), {
|
||||
a: { left: 0, top: 0, width: 50, height: 100 },
|
||||
b: { left: 50, top: 0, width: 50, height: 50 },
|
||||
c: { left: 50, top: 50, width: 50, height: 50 },
|
||||
});
|
||||
assert.equal(containsPane(nested, "c"), true);
|
||||
const closed = removePane(nested, "b")!;
|
||||
assert.deepEqual(paneBounds(closed).c, { left: 50, top: 0, width: 50, height: 100 });
|
||||
assert.equal(removePane(closed, "a"), "c");
|
||||
assert.equal(removePane("c", "c"), null);
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user