Update the browser, editor, settings, and installer
This commit is contained in:
@@ -81,10 +81,16 @@ try {
|
||||
return expected ? JSON.stringify(colors) === JSON.stringify(expected) : Object.values(colors).every(Boolean) && new Set(Object.values(colors)).size === 3;
|
||||
}, expected);
|
||||
}
|
||||
const themeName = theme => ({ default: 'RuneStone', claude: 'Claude', sakura: 'Sakura' })[theme];
|
||||
const picker = (page, name) => page.locator('.picker').filter({ has: page.locator('svg') }).and(page.getByRole('button', { name, exact: true }));
|
||||
async function choose(page, name, value) {
|
||||
await picker(page, name).click();
|
||||
await page.getByRole('menuitemradio', { name: name === 'Color theme' ? themeName(value) : value === 'light' ? 'Light' : 'Dark', exact: true }).click();
|
||||
}
|
||||
async function openAppearance(page) {
|
||||
await page.goto(`${origin}/?settingsWindow=true`);
|
||||
await page.getByRole("button", { name: "Appearance", exact: true }).click();
|
||||
await page.getByRole("combobox", { name: "Color theme", exact: true }).waitFor();
|
||||
await picker(page, "Color theme").waitFor();
|
||||
}
|
||||
await openCode(0);
|
||||
await openAppearance(settings);
|
||||
@@ -94,8 +100,8 @@ try {
|
||||
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 secondSettings.getByRole("combobox", { name: "Color theme", exact: true }).inputValue(), theme);
|
||||
assert.equal(await secondSettings.getByRole("combobox", { name: "Appearance", exact: true }).inputValue(), mode);
|
||||
assert.equal((await picker(secondSettings, "Color theme").textContent()).trim(), themeName(theme));
|
||||
assert.equal((await picker(secondSettings, "Appearance").textContent()).trim(), mode === "light" ? "Light" : "Dark");
|
||||
await main.waitForFunction(() => {
|
||||
const root = document.documentElement;
|
||||
const probe = document.createElement("i");
|
||||
@@ -114,8 +120,8 @@ try {
|
||||
for (const theme of ["default", "claude", "sakura"]) {
|
||||
for (const mode of theme === "sakura" ? ["light"] : ["light", "dark"]) {
|
||||
const before = await editorIds();
|
||||
await settings.getByRole("combobox", { name: "Color theme", exact: true }).selectOption(theme);
|
||||
if (theme !== "sakura") await settings.getByRole("combobox", { name: "Appearance", exact: true }).selectOption(mode);
|
||||
await choose(settings, 'Color theme', theme);
|
||||
if (theme !== "sakura") await choose(settings, 'Appearance', 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++);
|
||||
@@ -147,9 +153,11 @@ try {
|
||||
}
|
||||
}
|
||||
assert.equal(backgrounds.size, 5, "All supported combinations have distinct backgrounds");
|
||||
assert.deepEqual(await settings.getByRole('combobox', { name: 'Color theme', exact: true }).locator('option').evaluateAll(options => options.map(option => option.value)), ['default', 'claude', 'sakura']);
|
||||
assert.equal(await settings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true);
|
||||
assert.equal(await secondSettings.getByRole('combobox', { name: 'Appearance', exact: true }).isDisabled(), true);
|
||||
await picker(settings, 'Color theme').click();
|
||||
assert.deepEqual(await settings.getByRole('menuitemradio').allTextContents(), ['RuneStone', 'Claude', 'Sakura']);
|
||||
await settings.keyboard.press('Escape');
|
||||
assert.equal(await picker(settings, 'Appearance').isDisabled(), true);
|
||||
assert.equal(await picker(secondSettings, 'Appearance').isDisabled(), true);
|
||||
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()]));
|
||||
@@ -169,15 +177,15 @@ try {
|
||||
}
|
||||
for (const [theme, mode] of [['default', 'dark'], ['claude', 'light'], ['claude', 'dark'], ['sakura', 'light']]) {
|
||||
await settings.setViewportSize({ width: 1100, height: 780 });
|
||||
await settings.getByRole('combobox', { name: 'Color theme', exact: true }).selectOption(theme);
|
||||
if (theme !== 'sakura') await settings.getByRole('combobox', { name: 'Appearance', exact: true }).selectOption(mode);
|
||||
await choose(settings, 'Color theme', theme);
|
||||
if (theme !== 'sakura') await choose(settings, 'Appearance', 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', 'Appearance']) {
|
||||
const control = settings.getByRole('combobox', { name, exact: true });
|
||||
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`);
|
||||
|
||||
@@ -19,3 +19,12 @@ test('Malformed storage returns a valid default appearance', () => {
|
||||
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' });
|
||||
});
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\host-todo-test';
|
||||
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
|
||||
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
|
||||
window.__HOST_TEST__ = state;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push({ command, args });
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_list') {
|
||||
const prefix = args.rel ? args.rel + '/' : '';
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
|
||||
const tail = path.slice(prefix.length), name = tail.split('/')[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_write') {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === 'workspace_rename') {
|
||||
if (files.has(args.to)) throw new Error('Destination exists');
|
||||
if (!files.has(args.from)) throw new Error('Missing file');
|
||||
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
|
||||
}
|
||||
if (command === 'workspace_delete') { files.delete(args.rel); return; }
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:dialog|message') return 'Ok';
|
||||
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage(), settings = await context.newPage();
|
||||
const errors = [];
|
||||
for (const page of [main, settings]) page.on('pageerror', error => errors.push(error.message));
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
|
||||
await mkdir('output/appearance-pass3', { recursive: true });
|
||||
async function background() { return main.locator('.empty').evaluate(node => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(node).backgroundImage)?.[1]); }
|
||||
async function decoded(page, url) {
|
||||
return page.evaluate(async url => { const image = new Image(); image.src = url; await image.decode(); return image.naturalWidth; }, url);
|
||||
}
|
||||
try {
|
||||
await main.goto(origin); await main.locator('.empty').waitFor();
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
const image = await main.evaluate(() => {
|
||||
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 700;
|
||||
const ctx = canvas.getContext('2d'), pixels = ctx.createImageData(700, 700);
|
||||
let seed = 23;
|
||||
for (let i = 0; i < pixels.data.length; i++) { seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; pixels.data[i] = i % 4 === 3 ? 255 : seed >>> 24; }
|
||||
ctx.putImageData(pixels, 0, 0); return canvas.toDataURL();
|
||||
});
|
||||
const bytes = Buffer.from(image.split(',')[1], 'base64');
|
||||
assert.ok(image.length > 2 ** 21 && bytes.length < 2_000_000, 'Fixture crosses the CSS limit but fits the upload limit');
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'large.png', mimeType: 'image/png', buffer: bytes });
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
let url = await background();
|
||||
assert.equal(await decoded(main, url), 700, 'The actual new-tab image decodes');
|
||||
await main.reload(); await main.locator('.empty').waitFor();
|
||||
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
|
||||
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
|
||||
const large = Buffer.concat([pixel, Buffer.alloc(50 * 1024 * 1024 - pixel.length)]);
|
||||
await writeFile('output/appearance-pass3/50MiB.png', large);
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/50MiB.png'));
|
||||
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.empty')).backgroundImage)?.[1] !== old, url);
|
||||
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
|
||||
assert.ok(await settings.evaluate(() => localStorage.getItem('runestone.appearance').length < 500), 'Image bytes stay outside localStorage');
|
||||
await main.reload(); await main.locator('.empty').waitFor();
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
|
||||
const acceptedId = await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId);
|
||||
await writeFile('output/appearance-pass3/too-large.png', Buffer.alloc(50 * 1024 * 1024 + 1));
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles(resolve('output/appearance-pass3/too-large.png'));
|
||||
await settings.getByRole('alert').filter({ hasText: '50 MiB' }).waitFor();
|
||||
assert.equal(await settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.imageId), acceptedId);
|
||||
assert.equal(await settings.locator('input[type=color]').count(), 0);
|
||||
await settings.getByLabel('Image overlay', { exact: true }).fill('55');
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('0.55'));
|
||||
await settings.getByLabel('Image overlay', { exact: true }).fill('-40');
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('255, 255, 255, 0.4'));
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await settings.locator('.picker').and(settings.getByRole('button', { name: 'Appearance', exact: true })).click();
|
||||
await settings.getByRole('menuitemradio', { name: mode === 'dark' ? 'Dark' : 'Light', exact: true }).click();
|
||||
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
|
||||
assert.equal(await background(), url, 'Theme changes reuse the current image URL');
|
||||
await main.screenshot({ path: `output/appearance-pass3/background-${mode}.png` });
|
||||
for (const name of ['Color theme', 'Appearance']) {
|
||||
await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).click();
|
||||
const menu = settings.getByRole('menu', { name, exact: true });
|
||||
assert.equal(await menu.evaluate(node => getComputedStyle(node).fontSize), '13px');
|
||||
assert.equal(await menu.locator(':scope > button').first().evaluate(node => getComputedStyle(node).minHeight), '30px');
|
||||
assert.equal(await menu.locator('[aria-checked="true"] svg').count(), 0);
|
||||
assert.equal(await menu.evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-menu-border)'; node.append(reference); const matches = getComputedStyle(node).borderColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true, 'Menu uses the shared border token');
|
||||
assert.equal(await menu.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)', 'Menus have no visible border');
|
||||
await settings.screenshot({ path: `output/appearance-pass3/${name.replaceAll(' ', '-')}-${mode}.png` });
|
||||
await settings.keyboard.press('Escape');
|
||||
assert.equal(await settings.locator('.picker').and(settings.getByRole('button', { name, exact: true })).evaluate(node => node === document.activeElement), true);
|
||||
}
|
||||
}
|
||||
await settings.setViewportSize({ width: 360, height: 480 });
|
||||
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
|
||||
const box = await settings.getByRole('menu', { name: 'Color theme', exact: true }).boundingBox();
|
||||
assert.ok(box.x >= 0 && box.x + box.width <= 360 && box.y + box.height <= 480);
|
||||
await settings.screenshot({ path: 'output/appearance-pass3/menu-narrow.png' });
|
||||
await settings.keyboard.press('Escape');
|
||||
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
|
||||
assert.equal(await main.evaluate(async url => { try { await fetch(url); return false; } catch { return true; } }, url), true, 'Removing an image releases its URL');
|
||||
assert.equal(await settings.evaluate(async id => (await import('/src/lib/theme/backgroundImages.ts')).readBackgroundImage(id).then(Boolean), acceptedId), false, 'Removal deletes stored image bytes');
|
||||
await settings.evaluate(async () => {
|
||||
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
external.pluginTools.update(items => [...items, ...Array.from({ length: 30 }, (_, index) => ({ owner: `test.plugin${index}`, id: 'settings', title: `Plugin settings ${index}`, kind: 'view', surface: 'settings' }))]);
|
||||
});
|
||||
for (const theme of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, theme);
|
||||
await settings.setViewportSize({ width: 360, height: 600 });
|
||||
assert.equal(await settings.getByRole('navigation', { name: 'Settings categories' }).getByRole('button').count() >= 34, true);
|
||||
assert.equal(await settings.locator('.content').evaluate(node => node.clientHeight > 240 && node.clientWidth > 300), true, 'Long navigation leaves room for settings');
|
||||
await settings.screenshot({ path: `output/appearance-pass3/long-plugin-list-${theme}-narrow.png` });
|
||||
await main.setViewportSize({ width: 600, height: 700 });
|
||||
await main.keyboard.press('F1');
|
||||
await main.getByRole('dialog', { name: 'Help and about' }).waitFor();
|
||||
assert.equal(await main.locator('.help-card details[open]').count(), 0);
|
||||
await main.locator('.help-card summary').first().focus(); await main.keyboard.press('Enter');
|
||||
assert.equal(await main.locator('.help-card details[open]').count(), 1);
|
||||
await main.keyboard.press('Enter');
|
||||
await main.screenshot({ path: `output/appearance-pass3/help-${theme}-narrow.png` });
|
||||
await main.getByRole('button', { name: 'Close help', exact: true }).click();
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: large image upload, decoding, cross-window sync, reload, theme reuse, removal, shared menu dimensions, keyboard dismissal, and narrow viewport.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,76 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command) => {
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const main = await context.newPage(), settings = await context.newPage();
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
|
||||
const screenshots = [];
|
||||
await mkdir('output/todo-background', { recursive: true });
|
||||
try {
|
||||
await main.goto(origin);
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'image.png', mimeType: 'image/png', buffer: png });
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
for (const [control, choice] of [['Image position', 'Top left'], ['Image size', 'Actual size']]) {
|
||||
const button = settings.getByRole('button', { name: control, exact: true });
|
||||
await button.click();
|
||||
await settings.getByRole('menuitemradio', { name: choice, exact: true }).click();
|
||||
assert.equal(await button.evaluate(node => node === document.activeElement), true);
|
||||
}
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('0% 0%'));
|
||||
const layout = () => main.locator('.empty').evaluate(node => {
|
||||
const style = getComputedStyle(node), box = node.getBoundingClientRect();
|
||||
return { position: style.backgroundPosition, size: style.backgroundSize, width: box.width, height: box.height };
|
||||
});
|
||||
const before = await layout();
|
||||
assert.equal(before.size, '100% 100%, auto');
|
||||
await main.locator('.empty').evaluate(node => {
|
||||
const content = document.createElement('div'); content.style.cssText = 'height:2000px;flex-shrink:0;width:100%'; node.append(content);
|
||||
});
|
||||
assert.deepEqual(await layout(), before, 'Overflowing content does not resize or reposition the image surface');
|
||||
await main.reload();
|
||||
await main.locator('.empty').waitFor();
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
assert.equal((await layout()).position, before.position);
|
||||
assert.equal((await layout()).size, before.size);
|
||||
await settings.getByRole('button', { name: 'Image position', exact: true }).click();
|
||||
await settings.keyboard.press('End');
|
||||
await settings.keyboard.press('Enter');
|
||||
await main.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundPosition.endsWith('100% 100%'));
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => {
|
||||
const appearance = await import('/src/lib/theme/appearance.ts');
|
||||
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
}, mode);
|
||||
await main.waitForFunction(mode => document.documentElement.dataset.theme === mode, mode);
|
||||
for (const width of [1100, 360]) {
|
||||
await settings.setViewportSize({ width, height: 700 });
|
||||
const file = `output/todo-background/settings-${mode}-${width}.png`;
|
||||
await settings.screenshot({ path: file }); screenshots.push(file);
|
||||
const pane = settings.locator('.content');
|
||||
assert.equal(await pane.evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
|
||||
}
|
||||
}
|
||||
await writeFile('output/todo-background-report.json', JSON.stringify({ card: 'ab7b1a06-fd5a-4b74-aaa1-da64eafdf71c', checks: ['Alignment and sizing choices persist across reload and windows', 'Overflow does not resize the background surface', 'Keyboard choice and focus return', 'Both themes and narrow settings'], screenshots, native: 'Desktop visual acceptance remains pending.' }, null, 2));
|
||||
console.log('PASS: background alignment, size, stable surface, persistence, keyboard, both themes, narrow settings.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -4,7 +4,7 @@ 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('../RuneStone_Browser');
|
||||
const runtime = path.resolve('browser-runtime');
|
||||
const require = createRequire(path.join(runtime, 'package.json'));
|
||||
const { chromium } = require('playwright');
|
||||
const electron = require('electron');
|
||||
@@ -45,7 +45,7 @@ const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_P
|
||||
const errors = [];
|
||||
try {
|
||||
await ready;
|
||||
page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
|
||||
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(() => {
|
||||
@@ -77,12 +77,53 @@ try {
|
||||
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();
|
||||
@@ -94,7 +135,7 @@ try {
|
||||
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(150);
|
||||
await page.waitForTimeout(350);
|
||||
const stopped = await evaluate('scrollY');
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await evaluate('scrollY'), stopped);
|
||||
@@ -131,8 +172,8 @@ try {
|
||||
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.json', JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, passed: ['Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer bursts coalesce', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
|
||||
console.log('PASS browser UI with real Electron pages, autoscroll cleanup, pointer coalescing and center new-tab action');
|
||||
await writeFile(`output/browser-interaction-${process.env.BROWSER_TEST_SCALE || 1}x.json`, JSON.stringify({ decodedFps, scrolled, pointerBurstCalls: motionCount, wheelBurstCalls, passed: ['Native text entry, clipboard, composition and context menus', 'Native middle-button scrolling on both axes', 'Escape, click, drag release and focus loss stop scrolling', 'Pointer and wheel bursts coalesce during animation', 'Both themes and narrow layout', 'Toolbar plus removed and center new-tab retained'] }, null, 2));
|
||||
console.log('PASS browser UI with real Electron typing, clipboard, composition, page menus, autoscroll, pointer coalescing and center new-tab action');
|
||||
} finally {
|
||||
await browser.close();
|
||||
await rpc('shutdown').catch(() => {}); child.kill();
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import assert from 'node:assert/strict';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1100, height: 850 } });
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const snapshot = {
|
||||
profiles: [{ id: 'user', name: 'Personal' }, { id: 'work', name: 'Work' }], tabs: [], bookmarks: [],
|
||||
settings: { search: 'duckduckgo', adblock: true, linkDestination: 'internal', personalRules: '', homepage: '', filterLists: [] },
|
||||
};
|
||||
window.browserMenuTest = { snapshot, calls: [] };
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'settings-main' }, currentWebview: { label: 'settings-main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
if (command === 'plugin:event|listen') return args.handler;
|
||||
if (command === 'plugin:event|unlisten') return;
|
||||
if (command === 'browser_connect') return 'menu-session';
|
||||
if (command === 'browser_stop' || command === 'plugins_release') return;
|
||||
if (command === 'plugins_snapshot') return { root: 'test', plugins: [] };
|
||||
if (command.startsWith('plugin:window|')) return false;
|
||||
if (command !== 'browser_request') throw Error('Unhandled IPC: ' + command);
|
||||
const details = args.args || {};
|
||||
window.browserMenuTest.calls.push({ command: args.command, ...details });
|
||||
if (args.command === 'webData') return { profileId: details.profileId, cookies: [], history: [] };
|
||||
if (args.command === 'settings') Object.assign(snapshot.settings, details);
|
||||
return structuredClone(snapshot);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const menu = name => page.getByRole('menu', { name, exact: true });
|
||||
const trigger = name => page.getByRole('button', { name, exact: true });
|
||||
try {
|
||||
await mkdir('output/todo-menus', { recursive: true });
|
||||
await page.goto((process.env.SMOKE_URL || 'http://127.0.0.1:1420') + '/?settingsWindow=true');
|
||||
await trigger('Browser').click();
|
||||
await trigger('Search engine').waitFor();
|
||||
for (const mode of ['dark', 'light']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await trigger('Search engine').focus();
|
||||
await page.keyboard.press('Enter');
|
||||
const engines = menu('Search engine');
|
||||
await engines.waitFor();
|
||||
assert.equal(await engines.getByRole('menuitemradio', { name: 'DuckDuckGo' }).getAttribute('aria-checked'), 'true');
|
||||
assert.equal(await engines.evaluate(node => getComputedStyle(node).borderColor), 'rgba(0, 0, 0, 0)');
|
||||
await page.screenshot({ path: `output/todo-menus/search-${mode}.png` });
|
||||
await page.keyboard.press('End');
|
||||
await page.keyboard.press('Space');
|
||||
assert.equal(await trigger('Search engine').innerText(), 'Bing');
|
||||
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
|
||||
await trigger('Search engine').click();
|
||||
await page.keyboard.press('Home');
|
||||
await page.keyboard.press('Enter');
|
||||
await trigger('Profile').focus();
|
||||
await page.keyboard.press('Space');
|
||||
await menu('Profile').waitFor();
|
||||
await page.screenshot({ path: `output/todo-menus/profile-${mode}.png` });
|
||||
await page.keyboard.press('ArrowDown');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.waitForFunction(() => document.querySelector('button[aria-label="Profile"]')?.textContent === 'Work');
|
||||
await page.waitForFunction(() => window.browserMenuTest.calls.some(call => call.command === 'webData' && call.profileId === 'work'));
|
||||
await trigger('Profile').click();
|
||||
await page.keyboard.press('Home');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.setViewportSize({ width: 520, height: 700 });
|
||||
await trigger('Search engine').click();
|
||||
const bounds = await engines.boundingBox();
|
||||
assert.ok(bounds.x >= 8 && bounds.x + bounds.width <= 512);
|
||||
await page.screenshot({ path: `output/todo-menus/narrow-${mode}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await trigger('Search engine').evaluate(node => node === document.activeElement), true);
|
||||
await page.setViewportSize({ width: 1100, height: 850 });
|
||||
}
|
||||
await trigger('Search engine').click();
|
||||
await menu('Search engine').getByRole('menuitemradio', { name: 'Google', exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.browserMenuTest.calls.filter(call => call.command === 'settings').length), 0, 'A choice does not submit the form');
|
||||
await trigger('Save browser settings').click();
|
||||
await page.waitForFunction(() => window.browserMenuTest.snapshot.settings.search === 'google');
|
||||
await page.evaluate(async () => { const { state } = await import('/src/lib/browser/client.ts'); const snapshot = window.browserMenuTest.snapshot; snapshot.profiles.push(...Array.from({ length: 60 }, (_, i) => ({ id: 'p' + i, name: 'Profile ' + i }))); state.set(structuredClone(snapshot)); });
|
||||
await page.setViewportSize({ width: 520, height: 700 });
|
||||
await trigger('Profile').click();
|
||||
const profiles = menu('Profile');
|
||||
assert.equal(await profiles.evaluate(node => node.scrollHeight > node.clientHeight), true, 'Long profile lists scroll');
|
||||
await page.keyboard.press('End');
|
||||
assert.equal(await profiles.getByRole('menuitemradio', { name: 'Profile 59', exact: true }).evaluate(node => node === document.activeElement), true);
|
||||
await page.screenshot({ path: 'output/todo-menus/profile-long-narrow.png' });
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await trigger('Profile').evaluate(node => node === document.activeElement), true);
|
||||
await trigger('Profile').click();
|
||||
await trigger('Profile').evaluate(node => {
|
||||
let parent = node.parentElement;
|
||||
while (parent && parent.scrollHeight <= parent.clientHeight) parent = parent.parentElement;
|
||||
if (!parent) throw Error('Settings need a scroll area');
|
||||
parent.scrollTop -= 40;
|
||||
});
|
||||
await profiles.waitFor({ state: 'detached' });
|
||||
await trigger('Search engine').click();
|
||||
await trigger('General').click();
|
||||
assert.equal(await page.locator('.rs-menu').count(), 0, 'Leaving Browser closes the menu');
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('PASS: browser choices, persistence, keyboard selection and dismissal, long profiles, both themes, narrow layout, and cleanup.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -69,7 +69,11 @@ await page.addInitScript(() => {
|
||||
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('combobox', { name: 'Profile', 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('combobox', { name: 'Web data type', exact: true });
|
||||
const filter = section.getByRole('searchbox', { name: 'Filter web data', exact: true });
|
||||
const refresh = section.getByRole('button', { name: 'Refresh', exact: true });
|
||||
@@ -114,7 +118,7 @@ try {
|
||||
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 profile.selectOption('work');
|
||||
await selectProfile('work');
|
||||
await settle();
|
||||
assert.equal(await filter.inputValue(), '', 'Profile changes clear the prior filter');
|
||||
await section.getByText('Work guide', { exact: true }).waitFor();
|
||||
@@ -126,7 +130,7 @@ try {
|
||||
await refresh.click();
|
||||
await pending('webData:work');
|
||||
assert.equal(await workCookie().isDisabled(), true);
|
||||
await profile.selectOption('user');
|
||||
await selectProfile('user');
|
||||
await settle();
|
||||
await release('webData:work');
|
||||
assert.equal(await workCookie().count(), 0);
|
||||
@@ -136,7 +140,7 @@ try {
|
||||
await hold('webData:user');
|
||||
await refresh.click();
|
||||
await pending('webData:user');
|
||||
await profile.selectOption('work');
|
||||
await selectProfile('work');
|
||||
await workCookie().waitFor();
|
||||
await settle();
|
||||
await release('webData:user', 'Stale personal error');
|
||||
@@ -147,11 +151,11 @@ try {
|
||||
await hold('removeCookie:work');
|
||||
await workCookie().click();
|
||||
await pending('removeCookie:work');
|
||||
await profile.selectOption('user');
|
||||
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.inputValue(), 'user');
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { releaseVersion } from './releaseVersion.mjs';
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const exists = file => fs.access(file).then(() => true, () => false);
|
||||
const files = ['package.json', 'src-tauri/tauri.conf.json', 'src-tauri/Cargo.toml', 'src-tauri/Cargo.lock'].map(file => path.join(root, file));
|
||||
const before = await Promise.all(files.map(file => fs.readFile(file, 'utf8')));
|
||||
const current = releaseVersion(JSON.parse(before[0]).version);
|
||||
const args = process.argv.slice(2);
|
||||
if (args.length && (args.length !== 2 || args[0] !== '--version')) throw Error('Use --version followed by the release version.');
|
||||
const next = releaseVersion(args[1] ?? current.version);
|
||||
const config = JSON.parse(before[1]);
|
||||
const cargoVersion = /^version = "([^"]+)"/m.exec(before[2])?.[1];
|
||||
const lockedVersion = /name = "runestone"\r?\nversion = "([^"]+)"/.exec(before[3])?.[1];
|
||||
if ([config.version, cargoVersion, lockedVersion].some(value => value !== current.toolchain)) throw Error('The release version fields do not match.');
|
||||
const cargoRelease = /\[package\.metadata\.runestone\]\r?\nversion = "([^"]+)"/.exec(before[2])?.[1];
|
||||
if (cargoRelease && cargoRelease !== current.version) throw Error('The Cargo release metadata does not match.');
|
||||
if (config.bundle?.windows?.allowDowngrades === true) throw Error('Downgrade protection must remain enabled.');
|
||||
const platformConfig = JSON.parse(await fs.readFile(path.join(root, 'src-tauri/tauri.windows.conf.json'), 'utf8'));
|
||||
if (platformConfig.bundle.windows.allowDowngrades !== false) throw Error('Downgrade protection must remain enabled.');
|
||||
if (process.platform !== 'win32') throw Error('Build the Windows installer on Windows.');
|
||||
const artifactDir = path.join(root, 'src-tauri/target/release/bundle/nsis');
|
||||
const artifact = path.join(artifactDir, `RuneStone_${next.version}_x64-setup.exe`);
|
||||
const internalArtifact = path.join(artifactDir, `RuneStone_${next.toolchain}_x64-setup.exe`);
|
||||
const releaseDir = path.join(root, 'output/releases', next.version);
|
||||
const releaseArtifact = path.join(releaseDir, path.basename(artifact));
|
||||
const metadataPath = path.join(releaseDir, 'host.json');
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) if (await exists(file)) throw Error('The release file already exists: ' + file);
|
||||
const staging = path.join(root, 'output/installer-build', next.version);
|
||||
await fs.mkdir(staging, { recursive: true });
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(path.join(staging, path.basename(files[i]) + '.before'), before[i]);
|
||||
let template = await fs.readFile(path.join(root, 'src-tauri/windows/installer.nsi'), 'utf8');
|
||||
for (const [key, value] of Object.entries({ RUNESTONE_VERSION: next.version, RUNESTONE_WINDOWS_VERSION: next.windows,
|
||||
RUNESTONE_COMPARE: path.join(root, 'src-tauri/windows/versionCompare.nsh') })) {
|
||||
if (!template.includes(`@${key}@`)) throw Error('The installer template is missing ' + key);
|
||||
template = template.replaceAll(`@${key}@`, value);
|
||||
}
|
||||
const templatePath = path.join(staging, 'installer.nsi');
|
||||
await fs.writeFile(templatePath, template);
|
||||
const override = path.join(staging, 'config.json');
|
||||
await fs.writeFile(override, JSON.stringify({ bundle: { windows: { allowDowngrades: false, nsis: { template: templatePath } } } }));
|
||||
const packageJson = JSON.parse(before[0]);
|
||||
packageJson.version = next.version;
|
||||
config.version = next.toolchain;
|
||||
let cargo = before[2].replace(/^version = "[^"]+"/m, `version = "${next.toolchain}"`);
|
||||
if (/\[package\.metadata\.runestone\]/.test(cargo)) {
|
||||
cargo = cargo.replace(/(\[package\.metadata\.runestone\]\r?\nversion = ")[^"]+"/, `$1${next.version}"`);
|
||||
} else cargo += `\n[package.metadata.runestone]\nversion = "${next.version}"\n`;
|
||||
const lock = before[3].replace(/(name = "runestone"\r?\nversion = ")[^"]+"/, `$1${next.toolchain}"`);
|
||||
const updated = [JSON.stringify(packageJson, null, 2) + '\n', JSON.stringify(config, null, 2) + '\n', cargo, lock];
|
||||
const env = { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'safe.directory', GIT_CONFIG_VALUE_0: root.replaceAll('\\', '/') };
|
||||
async function run(command, parameters) {
|
||||
console.log(command + ' ' + parameters.join(' '));
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
const child = spawn(command, parameters, { cwd: root, env, stdio: 'inherit', windowsHide: true });
|
||||
child.on('error', reject); child.on('exit', resolve);
|
||||
});
|
||||
if (code !== 0) throw Error('The build command failed with exit code ' + code);
|
||||
}
|
||||
let complete = false;
|
||||
try {
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], updated[i]);
|
||||
const cli = path.join(root, 'node_modules/@tauri-apps/cli/tauri.js');
|
||||
await run(process.execPath, [cli, 'build', '--no-bundle', '--', '--locked']);
|
||||
await run('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', path.join(root, 'scripts/setWindowsVersion.ps1'),
|
||||
'-Path', path.join(root, 'src-tauri/target/release/runestone.exe'), '-Version', next.version, '-NumericVersion', next.windows]);
|
||||
await run(process.execPath, [cli, 'bundle', '--bundles', 'nsis', '--config', override]);
|
||||
await fs.access(internalArtifact);
|
||||
if (internalArtifact !== artifact) await fs.rename(internalArtifact, artifact);
|
||||
await fs.mkdir(releaseDir, { recursive: true });
|
||||
await fs.copyFile(artifact, releaseArtifact, 1);
|
||||
const bytes = await fs.readFile(releaseArtifact);
|
||||
const metadata = { version: next.version, toolchainVersion: next.toolchain, windowsVersion: next.windows,
|
||||
source: artifact, path: releaseArtifact, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') };
|
||||
await fs.writeFile(metadataPath, JSON.stringify(metadata, null, 2) + '\n', { flag: 'wx' });
|
||||
complete = true;
|
||||
console.log('Installer available: ' + releaseArtifact);
|
||||
} finally {
|
||||
if (!complete) {
|
||||
for (let i = 0; i < files.length; i++) await fs.writeFile(files[i], before[i]);
|
||||
for (const file of new Set([artifact, internalArtifact, releaseArtifact, metadataPath])) {
|
||||
if (await exists(file)) await fs.rename(file, file + '.failed-' + Date.now());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -95,7 +95,7 @@ try {
|
||||
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-preview pre").click();
|
||||
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);
|
||||
@@ -122,7 +122,7 @@ try {
|
||||
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-preview pre").textContent()).includes("const value = ;"));
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
try {
|
||||
await mkdir('output/round4-editor-menu', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:5187');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.keyboard.press('Control+p');
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
|
||||
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
|
||||
});
|
||||
const menu = () => page.getByRole('menu', { name: 'Markdown text actions', exact: true });
|
||||
async function setSource(value, anchor = 0, head = anchor) {
|
||||
await page.evaluate(({value,anchor,head}) => window.__CM__.dispatch({changes:{from:0,to:window.__CM__.state.doc.length,insert:value},selection:{anchor,head}}), {value,anchor,head});
|
||||
}
|
||||
async function openKeyboard() { await page.locator('.cm-content').focus(); await page.keyboard.press('Shift+F10'); await menu().waitFor(); }
|
||||
async function source() { return page.evaluate(() => window.__CM__.state.doc.toString()); }
|
||||
for (const theme of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({theme:'default',mode}); }, theme);
|
||||
await setSource('');
|
||||
await page.locator('.cm-line').first().click({button:'right'});
|
||||
await menu().waitFor();
|
||||
for (const label of ['Add link','Add external link','Format','Paragraph','Insert','Paste','Paste as plain text','Select all']) assert.equal(await menu().getByRole('menuitem', {name:label,exact:true}).count(),1,label);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Cut',exact:true}).isDisabled(),true);
|
||||
assert.equal(await menu().getByRole('menuitem',{name:'Copy',exact:true}).isDisabled(),true);
|
||||
await page.screenshot({path:`output/round4-editor-menu/empty-${theme}.png`});
|
||||
await menu().getByRole('menuitem',{name:'Format',exact:true}).focus();
|
||||
await page.keyboard.press('ArrowRight');
|
||||
const format = page.getByRole('menu',{name:'Format',exact:true});
|
||||
for (const label of ['Bold','Italic','Strikethrough','Highlight','Code','Math','Comment','Clear formatting']) assert.equal(await format.getByRole('menuitem',{name:label,exact:true}).count(),1);
|
||||
await page.keyboard.press('End');
|
||||
assert.equal(await page.getByRole('menuitem',{name:'Comment',exact:true}).evaluate(el=>el===document.activeElement),true);
|
||||
await page.screenshot({path:`output/round4-editor-menu/format-${theme}.png`});
|
||||
await page.keyboard.press('ArrowLeft');
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.locator('.cm-content').evaluate(el=>el===document.activeElement),true);
|
||||
await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Paragraph',exact:true}).click();
|
||||
await page.getByRole('menu',{name:'Paragraph',exact:true}).getByRole('menuitem',{name:'Heading 6',exact:true}).click();
|
||||
assert.equal(await source(),'###### ');
|
||||
await setSource(''); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Insert',exact:true}).click();
|
||||
await page.screenshot({path:`output/round4-editor-menu/insert-${theme}.png`});
|
||||
await page.getByRole('menu',{name:'Insert',exact:true}).getByRole('menuitem',{name:'Code block',exact:true}).click();
|
||||
assert.match(await source(),/^```\nCode\n```/);
|
||||
await setSource(''); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
|
||||
assert.equal(await source(),'[]()');
|
||||
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),1);
|
||||
assert.equal(await page.getByRole('dialog').count(),0);
|
||||
await setSource('label',0,5); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
|
||||
assert.equal(await source(),'[label]()');
|
||||
assert.equal(await page.evaluate(()=>window.__CM__.state.selection.main.head),8);
|
||||
await setSource(''); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
|
||||
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
|
||||
await page.screenshot({path:`output/round4-editor-menu/workspace-picker-${theme}.png`});
|
||||
await page.keyboard.press('Enter');
|
||||
await page.getByRole('dialog').waitFor({state:'detached'});
|
||||
assert.equal(await source(),'[[/notes/second.md]]');
|
||||
await setSource('Keep this text'); await openKeyboard();
|
||||
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
|
||||
await page.getByRole('textbox',{name:'Find a file'}).waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await page.getByRole('dialog').waitFor({state:'detached'});
|
||||
assert.equal(await source(),'Keep this text');
|
||||
await setSource('Populated paragraph\n\n');
|
||||
await page.locator('.cm-line').last().click({button:'right'});
|
||||
await menu().waitFor();
|
||||
await page.keyboard.press('Escape');
|
||||
await setSource('');
|
||||
await page.getByRole('button',{name:'Hide outline',exact:true}).click();
|
||||
await page.setViewportSize({width:560,height:420});
|
||||
await page.locator('.cm-scroller').click({button:'right',position:{x:60,y:180}});
|
||||
await menu().waitFor();
|
||||
const box = await menu().boundingBox(); assert.ok(box.x>=8 && box.y>=8 && box.x+box.width<=552 && box.y+box.height<=412);
|
||||
await page.screenshot({path:`output/round4-editor-menu/narrow-${theme}.png`});
|
||||
await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({width:1440,height:1000});
|
||||
await page.getByRole('button',{name:'Show outline',exact:true}).click();
|
||||
}
|
||||
await page.getByRole('group',{name:'Editor layout'}).hover();
|
||||
await page.getByRole('button',{name:'IDE',exact:true}).click();
|
||||
await page.locator('.monaco-editor').waitFor();
|
||||
await page.locator('.monaco-editor textarea').focus();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await menu().waitFor();
|
||||
await menu().getByRole('menuitem',{name:'Add external link',exact:true}).click();
|
||||
assert.equal(await page.getByRole('dialog').count(),0);
|
||||
await page.locator('.monaco-editor textarea').focus();
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.press('Backspace');
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await menu().getByRole('menuitem',{name:'Add link',exact:true}).click();
|
||||
await page.getByRole('textbox',{name:'Find a file'}).fill('second');
|
||||
await page.keyboard.press('Enter');
|
||||
await page.getByRole('dialog').waitFor({state:'detached'});
|
||||
await page.screenshot({path:'output/round4-editor-menu/ide-links.png'});
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: empty and whitespace Writer menus, full submenus, disabled actions, links, picker, selection, keyboard focus, two themes, narrow viewport and IDE.');
|
||||
} catch(error) {
|
||||
await page.screenshot({path:'output/round4-editor-menu/failure.png'});
|
||||
console.error('Browser errors:',errors); throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,182 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
try {
|
||||
await mkdir("output/editor-october12", { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
|
||||
await page.getByText("smoke-workspace", { exact: true }).waitFor();
|
||||
await page.keyboard.press("Control+p");
|
||||
await page.getByRole("textbox", { name: "Find a file" }).fill("welcome.md");
|
||||
await page.getByRole("dialog").getByRole("button").filter({ hasText: "welcome.md" }).first().click();
|
||||
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
|
||||
async function editor() {
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
}
|
||||
await editor();
|
||||
const source = "# First section\n\nParent text.[^long]\n\n## Child section\n\nChild content.\n\n### Nested section\n\nNested content.\n\n# Second section\n\nSecond content.[^long]\n\n## Last section\n\nFinal content.\n\n[^long]: A **bold** footnote.\n Continued on another line.\n";
|
||||
async function setSource(value) {
|
||||
await page.evaluate(value => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: value }, selection: { anchor: 0 } }), value);
|
||||
}
|
||||
await setSource(source);
|
||||
const structural = "# Parent\n\n| A | B |\n| --- | --- |\n| 1 | 2 |\n\n```md\n# Not a heading\n```\n\n## Child\n\nText\n\n# Next\n\nNext text\n";
|
||||
await setSource(structural);
|
||||
assert.equal(await page.getByRole("button", { name: "Collapse Not a heading", exact: true }).count(), 0);
|
||||
await page.getByRole("button", { name: "Collapse Parent", exact: true }).click();
|
||||
assert.equal(await page.locator(".writer-table").count(), 0);
|
||||
assert.equal(await page.getByRole("button", { name: "Collapse Child", exact: true }).count(), 0);
|
||||
await page.getByRole("button", { name: "Expand Parent", exact: true }).click();
|
||||
await page.locator(".writer-table").waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), structural);
|
||||
await setSource("Setext heading\n==============\n\nBody\n\n# Next\n\nNext body");
|
||||
await page.getByRole("button", { name: "Collapse Setext heading", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Setext heading", exact: true }).click();
|
||||
await setSource(source);
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
|
||||
assert.equal(await page.locator(".cm-content").textContent().then(text => text.includes("Child content.")), false);
|
||||
await page.getByRole("button", { name: "Collapse First section", exact: true }).click();
|
||||
assert.equal(await page.getByRole("button", { name: "Expand Child section", exact: true }).count(), 0);
|
||||
await page.getByRole("button", { name: "Expand First section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).waitFor();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
|
||||
await page.keyboard.press("Enter");
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.getAttribute('aria-label')), 'Collapse Child section');
|
||||
assert.equal(await page.evaluate(() => window.__CM__.state.sliceDoc()), source);
|
||||
|
||||
// Insert from the real shared menu and edit the selected definition.
|
||||
await page.evaluate(() => { window.__CM__.dispatch({ selection: { anchor: 20 } }); window.__CM__.focus(); });
|
||||
await page.keyboard.press("Shift+F10");
|
||||
await page.getByRole("menuitem", { name: "Insert", exact: true }).hover();
|
||||
await page.getByRole("menuitem", { name: "Footnote", exact: true }).click();
|
||||
await page.keyboard.type("New footnote");
|
||||
assert.match(await page.evaluate(() => window.__CM__.state.sliceDoc()), /\[\^1\]: New footnote/);
|
||||
await page.keyboard.press("Control+z");
|
||||
await setSource(source);
|
||||
|
||||
for (const theme of ["light", "dark"]) {
|
||||
await page.evaluate(async theme => { const { applyAppearance } = await import('/src/lib/theme/appearance.ts'); applyAppearance({ theme: 'default', mode: theme }); }, theme);
|
||||
await page.setViewportSize({ width: 760, height: 900 });
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
|
||||
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
|
||||
const bounds = button.getBoundingClientRect();
|
||||
const pane = button.closest('.cm-scroller').getBoundingClientRect();
|
||||
return bounds.left >= pane.left && bounds.right <= pane.right;
|
||||
}));
|
||||
await page.screenshot({ path: `output/editor-october12/writer-${theme}-narrow.png` });
|
||||
await page.keyboard.press("Space");
|
||||
const borders = await page.locator(".writer-heading").evaluateAll(headings => headings.map(heading => getComputedStyle(heading).borderBottomWidth));
|
||||
assert.ok(borders.every(border => border === "0px"));
|
||||
assert.ok(await page.locator(".writer-heading").first().evaluate(heading => parseFloat(getComputedStyle(heading).paddingTop) > 8));
|
||||
await page.getByRole("group", { name: "Document view" }).hover();
|
||||
await page.getByRole("button", { name: "Read", exact: true }).click();
|
||||
await page.locator(".md-footnotes").waitFor();
|
||||
assert.equal(await page.locator(".md-footnote-ref").count(), 2);
|
||||
assert.equal(await page.locator(".md-footnotes li").count(), 1);
|
||||
assert.equal(await page.locator(".md-footnote-back").count(), 2);
|
||||
await page.getByRole("button", { name: "Collapse Child section", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Expand Child section", exact: true }).focus();
|
||||
assert.ok(await page.getByRole("button", { name: "Expand Child section", exact: true }).evaluate(button => {
|
||||
const bounds = button.getBoundingClientRect();
|
||||
const pane = button.closest('.reading').parentElement.getBoundingClientRect();
|
||||
return bounds.left >= pane.left && bounds.right <= pane.right;
|
||||
}));
|
||||
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), false);
|
||||
await page.screenshot({ path: `output/editor-october12/reader-${theme}-narrow.png` });
|
||||
await page.keyboard.press("Space");
|
||||
assert.equal(await page.getByText("Child content.", { exact: true }).isVisible(), true);
|
||||
await page.getByRole("button", { name: "Collapse Last section", exact: true }).click();
|
||||
await page.locator(".md-footnote-ref a").first().click();
|
||||
assert.equal(await page.locator(".md-footnotes").isVisible(), true);
|
||||
await page.locator(".md-footnote-back").first().click();
|
||||
assert.equal(await page.evaluate(() => document.activeElement?.id), "rs-fnref-1-1");
|
||||
await page.getByRole("group", { name: "Document view" }).hover();
|
||||
await page.getByRole("button", { name: "Edit", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Writing editor", exact: true }).waitFor();
|
||||
await editor();
|
||||
}
|
||||
await page.keyboard.press("Control+s");
|
||||
await page.waitForFunction(value => window.__TEST__.files.get("notes/welcome.md") === value, source);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: footnote menu, Writer edits, Reader numbering and backlinks, nested folding, keyboard toggles, source preservation, light/dark narrow screenshots.");
|
||||
} catch (error) {
|
||||
console.error("Browser errors:", errors);
|
||||
await page.screenshot({ path: "output/editor-october12/failure.png" });
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
␍
|
||||
@@ -0,0 +1,33 @@
|
||||
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/);
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, readFile } from 'node:fs/promises';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
const gitRoot = new URL('../../RuneStone_Git/dist/', import.meta.url);
|
||||
const git = {
|
||||
manifest: JSON.parse(await readFile(new URL('plugin.json', gitRoot), 'utf8')),
|
||||
code: await readFile(new URL('main.js', gitRoot), 'utf8'),
|
||||
css: (await readFile(new URL('style.css', gitRoot))).toString('base64'),
|
||||
};
|
||||
await context.addInitScript(git => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\host-todo-test';
|
||||
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['folder/nested/note.md', '# Nested'], ['other/keep.md', '# Keep'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
|
||||
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
|
||||
window.__HOST_TEST__ = state;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push({ command, args });
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [{ manifest: git.manifest, hash: 'navigation-git', enabled: true, installedAt: 1, path: 'C:/plugins/runestone.git', error: null, removal: false }] };
|
||||
if (command === 'plugins_load') return git.code;
|
||||
if (command === 'plugins_asset') return git.css;
|
||||
if (command === 'plugins_data') return 'null';
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_list') {
|
||||
const prefix = args.rel ? args.rel + '/' : '';
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
|
||||
const tail = path.slice(prefix.length), name = tail.split('/')[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_write') {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === 'workspace_rename') {
|
||||
if (files.has(args.to)) throw new Error('Destination exists');
|
||||
if (![...files.keys()].some(path => path === args.from || path.startsWith(args.from + '/'))) throw new Error('Missing file');
|
||||
for (const [path, contents] of [...files]) { if (path === args.from || path.startsWith(args.from + '/')) { files.set(args.to + path.slice(args.from.length), contents); files.delete(path); } } return;
|
||||
}
|
||||
if (command === 'workspace_delete') { files.delete(args.rel); return; }
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:dialog|message') return 'Ok';
|
||||
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
}, git);
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5186';
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
const item = name => page.getByRole('menuitem', { name, exact: true });
|
||||
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
|
||||
async function rename(path, name) {
|
||||
await row(path).click({ button: 'right' }); await item('Rename').click();
|
||||
await page.locator('.tree input').fill(name); await page.locator('.tree input').press('Enter');
|
||||
}
|
||||
async function expanded(path) { assert.equal(await row(path).getAttribute('aria-expanded'), 'true', `${path} stays expanded`); }
|
||||
await mkdir('output/host-navigation-pass3', { recursive: true });
|
||||
try {
|
||||
await page.goto(origin);
|
||||
await row('folder').click(); await row('folder/nested').click(); await row('other').click();
|
||||
await rename('folder/nested/note.md', 'renamed.md'); await row('folder/nested/renamed.md').waitFor();
|
||||
await row('folder/nested/renamed.md').focus(); await page.keyboard.press('Control+z');
|
||||
await row('folder/nested/note.md').waitFor();
|
||||
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
|
||||
await page.keyboard.press('Control+y'); await row('folder/nested/renamed.md').waitFor();
|
||||
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
|
||||
await rename('folder', 'renamed-folder'); await row('renamed-folder/nested/renamed.md').waitFor();
|
||||
await row('renamed-folder').focus(); await page.keyboard.press('Control+z');
|
||||
await row('folder/nested/renamed.md').waitFor();
|
||||
for (const path of ['folder', 'folder/nested', 'other']) await expanded(path);
|
||||
await page.keyboard.press('Control+y'); await row('renamed-folder/nested/renamed.md').waitFor();
|
||||
for (const path of ['renamed-folder', 'renamed-folder/nested', 'other']) await expanded(path);
|
||||
await paneMenu(); assert.equal(await item('Manage templates…').isVisible(), false);
|
||||
await item('New note').click(); await row('untitled.md').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('untitled.md')), '');
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
await item('Daily').click(); await row('Daily.md').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
await page.screenshot({ path: `output/host-navigation-pass3/note-menu-${mode}.png` });
|
||||
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
|
||||
}
|
||||
await page.setViewportSize({ width: 600, height: 600 });
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
await page.screenshot({ path: 'output/host-navigation-pass3/note-menu-dark-narrow.png' });
|
||||
assert.ok(await item('Manage templates…').evaluate(node => node.getBoundingClientRect().right <= innerWidth));
|
||||
await page.keyboard.press('Escape'); await page.keyboard.press('Escape');
|
||||
await page.setViewportSize({ width: 1200, height: 850 });
|
||||
await page.evaluate(() => { window.__HOST_TEST__.files.delete('.runestone/templates/Daily.md'); window.dispatchEvent(new Event('runestone-templates-changed')); });
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('ArrowRight');
|
||||
assert.equal(await item('Daily').count(), 0);
|
||||
await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
const creations = await page.evaluate(() => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length);
|
||||
await paneMenu(); await item('New note').focus(); await page.keyboard.press('Enter');
|
||||
await page.waitForFunction(count => window.__HOST_TEST__.calls.filter(call => call.command === 'workspace_create').length === count + 1, creations);
|
||||
await page.getByRole('button', { name: 'Source control', exact: true }).waitFor();
|
||||
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
const graph = page.getByRole('menuitem', { name: /Show Git graph/ });
|
||||
await graph.waitFor();
|
||||
assert.equal(await page.getByRole('menuitem', { name: /source control/i }).count(), 0);
|
||||
const graphIcon = await graph.locator('.action-icon').innerHTML();
|
||||
const expectedIcon = await page.evaluate(async () => (await import('/src/lib/ui/actionIcons.ts')).actionIcon('git').innerHTML);
|
||||
assert.equal(graphIcon, expectedIcon, 'The real Git graph command uses the shared Git icon');
|
||||
await page.screenshot({ path: 'output/host-navigation-pass3/real-git-command-dark.png' });
|
||||
await page.keyboard.press('Escape');
|
||||
await page.evaluate(async () => {
|
||||
const external = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/external.ts').name);
|
||||
external.pluginNavigation.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', icon: 'kanban', placement: 'editor', toolbar: true }, { owner: 'git-test', id: 'source', title: 'Source control', icon: 'git', placement: 'sidebar', toolbar: true }]);
|
||||
external.pluginTools.set([{ owner: 'pm-test', id: 'pm', title: 'Project Management', kind: 'view', surface: 'open' }, { owner: 'git-test', id: 'graph', title: 'Graph view', kind: 'command', surface: 'open', icon: 'git' }]);
|
||||
external.pluginTools.update(items => [...items, { owner: 'runestone.browser', id: 'new-tab', title: 'New browser tab', kind: 'command', surface: 'open' }]);
|
||||
const registry = await import(performance.getEntriesByType('resource').find(entry => new URL(entry.name).pathname === '/src/lib/plugins/registry.ts').name);
|
||||
registry.pluginHost.get('browser').newTab = async () => { window.__HOST_TEST__.browserOpened = true; };
|
||||
});
|
||||
await page.locator('.header-right').getByRole('button', { name: 'New browser tab', exact: true }).click();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.browserOpened), true);
|
||||
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Project Management', exact: true }).count(), 0);
|
||||
assert.equal(await page.locator('.header-left').getByRole('button', { name: 'Source control', exact: true }).count(), 1);
|
||||
assert.equal(await page.locator('.header-right').getByRole('button', { name: 'Source control', exact: true }).count(), 0);
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
assert.equal(await page.getByRole('menuitem', { name: /Project Management/ }).count(), 1);
|
||||
assert.equal(await page.getByRole('menuitem', { name: /New browser tab/ }).count(), 0);
|
||||
await page.getByRole('menuitem', { name: /Graph view/ }).waitFor(); await page.keyboard.press('Escape');
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await page.getByRole('button', { name: 'Plug-in views', exact: true }).click();
|
||||
await page.screenshot({ path: `output/host-navigation-pass3/plugin-navigation-${mode}.png` });
|
||||
await page.keyboard.press('Escape');
|
||||
}
|
||||
const token = '00000000-0000-4000-8000-000000000001';
|
||||
const saved = await page.evaluate(token => {
|
||||
const layout = JSON.stringify({ leftOpen: true, rightOpen: true, leftWidth: 280, rightWidth: 260, leftView: 'files' });
|
||||
localStorage.setItem('runestone.workbenchLayout', layout);
|
||||
localStorage.setItem(`runestone.tab-transfer.${token}`, JSON.stringify({ root: 'C:\\host-todo-test', created: Date.now(), buffer: { id: 'moved', relPath: 'a.md', name: 'a.md', kind: 'text', contents: '# Transferred', saved: '# Note', chrome: 'Writing', pinned: true } }));
|
||||
return layout;
|
||||
}, token);
|
||||
const detached = await context.newPage();
|
||||
detached.on('pageerror', error => errors.push(error.message));
|
||||
await detached.goto(`${origin}/?tabTransfer=${token}`);
|
||||
await detached.getByRole('tab', { name: /a.md/ }).waitFor();
|
||||
await detached.getByText('# Transferred', { exact: true }).waitFor();
|
||||
assert.equal(await detached.locator('.shell.left-open,.shell.right-open').count(), 0);
|
||||
assert.equal(await detached.getByRole('button', { name: 'Show outline', exact: true }).count(), 0);
|
||||
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
|
||||
assert.equal(await detached.getByRole('button', { name: 'Files', exact: true }).count(), 0);
|
||||
await detached.keyboard.press('Control+b');
|
||||
await detached.keyboard.press('Control+Shift+f');
|
||||
assert.equal(await detached.locator('aside.left,aside.right,.plugin-ribbon,.gutter-v').count(), 0);
|
||||
await detached.keyboard.press('Escape');
|
||||
assert.equal(await detached.evaluate(() => localStorage.getItem('runestone.workbenchLayout')), saved);
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await detached.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await detached.setViewportSize({ width: 650, height: 600 });
|
||||
await detached.screenshot({ path: `output/host-navigation-pass3/detached-${mode}-narrow.png` });
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Host navigation passed: nested file/folder rename undo/redo, expanded folders, blank New note parent, template submenu, plugin navigation dedup, detached layout isolation.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,165 @@
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1200, height: 850 } });
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = 'C:\\host-todo-test';
|
||||
const files = new Map([['a.md', '# Note\n\nOriginal text.'], ['.runestone/templates/Daily.md', '# Daily\n\n## Tasks'], ['.runestone/marks.json', JSON.stringify({ pins: ['a.md'], bookmarks: ['a.md'], order: { '': ['a.md'] } })]]);
|
||||
const state = { files, calls: [], exportResult: 'C:\\exports\\my-theme.json', exportError: '' };
|
||||
window.__HOST_TEST__ = state;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async (command, args = {}) => {
|
||||
state.calls.push({ command, args });
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'workspace_last_path') return root;
|
||||
if (command === 'workspace_open') return { root, name: 'host-todo-test', watch_mode: 'native' };
|
||||
if (command === 'workspace_read') { if (!files.has(args.rel)) throw new Error('Missing file'); return files.get(args.rel); }
|
||||
if (command === 'workspace_list') {
|
||||
const prefix = args.rel ? args.rel + '/' : '';
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || (!args.rel && path.startsWith('.runestone/'))) continue;
|
||||
const tail = path.slice(prefix.length), name = tail.split('/')[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes('/') ? 'folder' : 'file' });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === 'workspace_create') { if (files.has(args.rel)) throw new Error('Destination exists'); files.set(args.rel, ''); return; }
|
||||
if (command === 'workspace_write') {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error('Changed on disk');
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === 'workspace_rename') {
|
||||
if (files.has(args.to)) throw new Error('Destination exists');
|
||||
if (!files.has(args.from)) throw new Error('Missing file');
|
||||
files.set(args.to, files.get(args.from)); files.delete(args.from); return;
|
||||
}
|
||||
if (command === 'workspace_delete') { files.delete(args.rel); return; }
|
||||
if (command === 'workspace_search') return [];
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:dialog|message') return 'Ok';
|
||||
if (command === 'theme_export') { if (state.exportError) throw new Error(state.exportError); return state.exportResult; }
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5173';
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
const item = name => page.getByRole('menuitem', { name, exact: true });
|
||||
async function paneMenu() { await page.getByRole('navigation', { name: 'Workspace files' }).click({ button: 'right', position: { x: 90, y: 360 } }); }
|
||||
await mkdir('output/host-todo', { recursive: true });
|
||||
try {
|
||||
await page.goto(origin);
|
||||
await row('a.md').waitFor();
|
||||
await page.getByRole('button', { name: 'New file Ctrl N' }).click();
|
||||
await page.getByRole('textbox', { name: 'New file path relative to the workspace' }).waitFor();
|
||||
await page.mouse.click(5, 700);
|
||||
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses new-file dialog');
|
||||
await page.getByRole('button', { name: 'Find a file Ctrl P' }).click();
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).click();
|
||||
assert.equal(await page.locator('dialog').count(), 1, 'Inside click keeps file search open');
|
||||
await page.mouse.click(5, 700);
|
||||
assert.equal(await page.locator('dialog').count(), 0, 'Outside click dismisses file search');
|
||||
await row('a.md').click({ button: 'right' });
|
||||
assert.equal(await item('Copy path').count(), 0);
|
||||
assert.equal(await item('Copy system path').count(), 1);
|
||||
await item('Rename').click();
|
||||
await page.locator('.tree input').fill('renamed.md');
|
||||
await page.locator('.tree input').press('Enter');
|
||||
await row('renamed.md').waitFor();
|
||||
await row('renamed.md').click({ button: 'right' });
|
||||
assert.equal(await item('Undo rename').count(), 1);
|
||||
await page.keyboard.press('Escape');
|
||||
await row('renamed.md').focus(); await page.keyboard.press('Control+z');
|
||||
await row('a.md').waitFor();
|
||||
assert.deepEqual(await page.evaluate(() => JSON.parse(window.__HOST_TEST__.files.get('.runestone/marks.json')).pins), ['a.md']);
|
||||
await row('a.md').focus(); await page.keyboard.press('Control+y');
|
||||
await row('renamed.md').waitFor();
|
||||
await paneMenu(); await item('New note').hover();
|
||||
await item('Daily').click();
|
||||
await row('Daily.md').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks');
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Rename Daily', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Weekly');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor();
|
||||
await page.evaluate(() => window.__HOST_TEST__.files.set('.runestone/templates/Existing.md', '# Keep this template'));
|
||||
await page.getByRole('button', { name: 'Rename Weekly', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Existing');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByRole('alert').filter({ hasText: 'Destination exists' }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Existing.md')), '# Keep this template');
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode }); }, mode);
|
||||
await page.screenshot({ path: `output/host-todo/templates-${mode}.png` });
|
||||
}
|
||||
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'Weekly.md', exact: true }).waitFor();
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'New template', exact: true }).click();
|
||||
await page.getByRole('textbox', { name: 'Template name', exact: true }).fill('Meeting');
|
||||
await page.getByRole('button', { name: 'Continue', exact: true }).click();
|
||||
await page.getByRole('tab', { name: 'Meeting.md', exact: true }).waitFor();
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('.runestone/templates/Meeting.md')), '');
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
await page.getByRole('button', { name: 'Delete Weekly', exact: true }).click();
|
||||
await page.getByRole('button', { name: 'Edit Weekly', exact: true }).waitFor({ state: 'detached' });
|
||||
assert.equal(await page.evaluate(() => window.__HOST_TEST__.files.get('Daily.md')), '# Daily\n\n## Tasks', 'Deleting template preserves notes');
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
await page.evaluate(() => { for (let i = 0; i < 40; i++) window.__HOST_TEST__.files.set(`.runestone/templates/Long template name ${i}.md`, '# Template'); });
|
||||
await page.setViewportSize({ width: 600, height: 600 });
|
||||
await paneMenu(); await item('New note').hover(); await item('Manage templates…').click();
|
||||
assert.ok(await page.locator('dialog .list').evaluate(node => node.scrollHeight > node.clientHeight), 'Long template list scrolls');
|
||||
await page.screenshot({ path: 'output/host-todo/templates-narrow-long.png' });
|
||||
await page.getByRole('button', { name: 'Close templates', exact: true }).click();
|
||||
await page.setViewportSize({ width: 1200, height: 850 });
|
||||
const settings = await context.newPage(); settings.on('pageerror', error => errors.push(error.message));
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
await settings.getByRole('button', { name: 'Export theme template' }).click();
|
||||
await settings.getByRole('status').filter({ hasText: 'Theme saved to' }).waitFor();
|
||||
assert.equal(await settings.evaluate(() => JSON.parse(window.__HOST_TEST__.calls.find(call => call.command === 'theme_export').args.contents).schema), 1);
|
||||
await settings.evaluate(() => window.__HOST_TEST__.exportResult = null);
|
||||
await settings.getByRole('button', { name: 'Export theme template' }).click();
|
||||
await settings.getByText('Export canceled.', { exact: true }).waitFor();
|
||||
await settings.evaluate(() => window.__HOST_TEST__.exportError = 'Disk is full');
|
||||
await settings.getByRole('button', { name: 'Export theme template' }).click();
|
||||
await settings.getByRole('alert').filter({ hasText: 'Disk is full' }).waitFor();
|
||||
await settings.getByRole('button', { name: 'Color theme', exact: true }).click();
|
||||
await settings.getByRole('menuitemradio', { name: 'RuneStone', exact: true }).focus();
|
||||
await settings.keyboard.press('ArrowDown'); await settings.keyboard.press('Enter');
|
||||
assert.equal(await settings.evaluate(() => document.documentElement.dataset.palette), 'claude');
|
||||
assert.equal(await settings.locator('input[type=color]').count(), 0);
|
||||
await page.getByRole('button', { name: 'New tab (Ctrl T)', exact: true }).click();
|
||||
await page.locator('.empty').waitFor();
|
||||
await page.waitForFunction(() => document.documentElement.dataset.palette === 'claude');
|
||||
assert.equal(await page.locator('.empty').evaluate(node => { const reference = document.createElement('span'); reference.style.color = 'var(--rs-bg)'; node.append(reference); const matches = getComputedStyle(node).backgroundColor === getComputedStyle(reference).color; reference.remove(); return matches; }), true);
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({ name: 'test.png', mimeType: 'image/png', buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64') });
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage.includes('blob:'));
|
||||
await page.reload(); await page.locator('.empty').waitFor();
|
||||
assert.ok(await page.locator('.empty').evaluate(node => getComputedStyle(node).backgroundImage.includes('blob:')), 'Background survives restart');
|
||||
await settings.getByRole('button', { name: 'Remove image', exact: true }).click();
|
||||
await page.waitForFunction(() => getComputedStyle(document.querySelector('.empty')).backgroundImage === 'none');
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => { const { saveAppearance, parseAppearance, APPEARANCE_KEY } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ ...parseAppearance(localStorage.getItem(APPEARANCE_KEY)), theme: 'default', mode }); window.dispatchEvent(new Event('focus')); }, mode);
|
||||
await settings.setViewportSize({ width: 650, height: 760 });
|
||||
await settings.screenshot({ path: `output/host-todo/appearance-${mode}-narrow.png` });
|
||||
}
|
||||
assert.equal(await settings.getByRole('button', { name: 'Reset background', exact: true }).isDisabled(), true);
|
||||
await page.waitForFunction(() => !JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log('Host To Do: dialog dismissal, rename undo/redo with marks, template creation/rename/edit/delete, theme export success/cancel/error, shared theme menu, background persistence/reset passed.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,33 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { normalizeAppearance, parseAppearance, exportAppearanceTheme } from '../src/lib/theme/appearance.ts';
|
||||
|
||||
test('New tab backgrounds retain supported data while rejecting active and remote content', () => {
|
||||
const value = { theme: 'claude', mode: 'light', newTabBackground: { image: 'data:image/png;base64,YQ==', overlay: 0 } };
|
||||
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 storage references retain overlay limits and discard obsolete colors', () => {
|
||||
const imageId = 'd10adda6-a2ec-4d73-a0a6-2cb1ed43bebc';
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, color: '#224466', overlay: 3 } }).newTabBackground, { imageId, overlay: 1 });
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: -3 } }).newTabBackground, { imageId, overlay: -1 });
|
||||
assert.deepEqual(normalizeAppearance({ newTabBackground: { imageId, overlay: NaN } }).newTabBackground, { imageId, overlay: 0 });
|
||||
assert.equal(normalizeAppearance({ newTabBackground: { imageId: 'invalid' } }).newTabBackground, undefined);
|
||||
});
|
||||
|
||||
test('Export follows the selected built-in palette and can be imported as a custom theme', async () => {
|
||||
const { parseCustomTheme } = await import('../src/lib/theme/customThemes.ts');
|
||||
globalThis.localStorage = { getItem: () => null };
|
||||
try {
|
||||
const claude = exportAppearanceTheme('claude');
|
||||
assert.equal(claude.light.bg, '#faf9f5');
|
||||
assert.equal(claude.dark.accent, '#d97757');
|
||||
assert.deepEqual(parseCustomTheme(claude), claude);
|
||||
const sakura = exportAppearanceTheme('sakura');
|
||||
assert.deepEqual(sakura.light, sakura.dark);
|
||||
} finally { delete globalThis.localStorage; }
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
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 { 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));
|
||||
});
|
||||
|
||||
test('the native NSIS comparator blocks older hotfixes and permits reinstall', { skip: process.platform !== 'win32' }, 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 = path.join(process.env.LOCALAPPDATA!, 'tauri/NSIS/makensis.exe');
|
||||
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/);
|
||||
const template = await readFile('src-tauri/windows/installer.nsi', 'utf8');
|
||||
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 });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// Run against the host dev server with PLAYWRIGHT_MODULE and CHROME_PATH when needed.
|
||||
import { createRequire } from "node:module";
|
||||
import { readFile, mkdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import assert from "node:assert/strict";
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(15000);
|
||||
const errors = [];
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
localStorage.setItem("runestone.settings", JSON.stringify({ autosaveEnabled: false }));
|
||||
const root = "C:\\kanban-root-smoke";
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="80"><rect width="100" height="80" fill="#639"/></svg>';
|
||||
const files = new Map([
|
||||
["notes/draft.md", "Before.\n\nAfter.\n"],
|
||||
["files/report [Q1] (#1).pdf", "PDF fixture"],
|
||||
["images/diagram (#1).svg", btoa(svg)],
|
||||
]);
|
||||
const calls = [], callbacks = new Map(), listeners = new Map(); let sequence = 0;
|
||||
window.kanbanRootSmoke = { files, calls };
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback(callback) { callbacks.set(++sequence, callback); return sequence; },
|
||||
unregisterCallback(id) { callbacks.delete(id); },
|
||||
async invoke(command, args = {}) {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") { const values = listeners.get(args.event) || []; values.push(args.handler); listeners.set(args.event, values); return args.handler; }
|
||||
if (command === "plugin:event|unlisten" || command === "spelling_menu_install" || command === "spelling_menu_uninstall") return;
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "kanban-root-smoke", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw Error("File missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_read_data_url") return "data:image/svg+xml;base64," + files.get(args.rel);
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw Error("Save conflict");
|
||||
files.set(args.rel, args.contents); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "", entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length), name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "workspace_recent") return [root];
|
||||
if (command === "plugins_snapshot") return { plugins: [], issues: [] };
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
if (command.startsWith("plugin:window|") || command === "browser_stop") return;
|
||||
throw Error("Unhandled IPC: " + command);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} };
|
||||
});
|
||||
const row = path => page.locator(`[data-tree-rel="${path}"]`);
|
||||
async function drag(path, target) {
|
||||
const from = await row(path).boundingBox(), to = await page.locator(target).boundingBox();
|
||||
assert.ok(from && to, "The file and editor must be visible");
|
||||
await page.mouse.move(from.x + Math.min(80, from.width / 2), from.y + from.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(to.x + 45, to.y + 12, { steps: 15 });
|
||||
await page.locator(".image-drop-target").waitFor();
|
||||
await page.mouse.up();
|
||||
}
|
||||
async function writerSource() { return page.evaluate(() => window.kanbanWriter.state.doc.toString()); }
|
||||
async function ideSource() {
|
||||
return page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
return monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected)?.getValue();
|
||||
});
|
||||
}
|
||||
try {
|
||||
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:5173");
|
||||
await row("notes").click(); await row("notes/draft.md").dblclick();
|
||||
await page.locator(".cm-content").waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
|
||||
window.kanbanWriter = EditorView.findFromDOM(document.querySelector(".cm-content"));
|
||||
});
|
||||
await row("files").click();
|
||||
const original = await writerSource();
|
||||
await drag("files/report [Q1] (#1).pdf", ".cm-content");
|
||||
await page.waitForFunction(() => window.kanbanWriter.state.doc.toString().includes(".pdf)"));
|
||||
const linked = await writerSource();
|
||||
assert.ok(linked.includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"), linked);
|
||||
assert.ok(!linked.includes(""));
|
||||
await page.evaluate(() => window.kanbanWriter.focus()); await page.keyboard.press("Control+z");
|
||||
assert.equal(await writerSource(), original);
|
||||
await page.keyboard.press("Control+e");
|
||||
await page.locator(".monaco-editor textarea").waitFor();
|
||||
const originalIde = await ideSource();
|
||||
await page.evaluate(async () => {
|
||||
const { monaco } = await import("/src/lib/editor/monacoEnv.ts");
|
||||
const editor = monaco.editor.getEditors().find(editor => editor.getDomNode()?.isConnected);
|
||||
window.kanbanMonaco = editor;
|
||||
});
|
||||
await drag("files/report [Q1] (#1).pdf", ".monaco-editor .view-lines");
|
||||
await page.waitForFunction(() => window.kanbanMonaco.getValue().includes(".pdf)"));
|
||||
assert.ok((await ideSource()).includes("[report \\[Q1\\] (#1).pdf](../files/report%20%5BQ1%5D%20%28%231%29.pdf)"));
|
||||
await page.evaluate(() => window.kanbanMonaco.focus());
|
||||
assert.equal(await page.evaluate(() => window.kanbanMonaco.hasTextFocus()), true);
|
||||
await page.keyboard.press("Control+z");
|
||||
await page.waitForFunction(expected => window.kanbanMonaco.getValue() === expected, originalIde, { timeout: 3000 });
|
||||
assert.equal(await ideSource(), originalIde, "IDE undo restores the exact source");
|
||||
await drag("images/diagram (#1).svg", ".monaco-editor .view-lines");
|
||||
assert.ok((await ideSource()).includes(""));
|
||||
assert.equal(await page.evaluate(() => window.kanbanRootSmoke.calls.filter(call => ["workspace_rename", "workspace_write_bytes"].includes(call.command)).length), 0);
|
||||
console.log("PASS: real FileTree pointer drags insert escaped document links in Writer and IDE, undo restores both, and image drags still embed.");
|
||||
|
||||
// Load current Git source through the host origin without creating a distributable.
|
||||
const gitRoot = process.env.RUNESTONE_GIT_ROOT || resolve("../RuneStone_Git");
|
||||
const sources = new Map(await Promise.all(["view.js", "model.js"].map(async file => [file, await readFile(resolve(gitRoot, "src", file), "utf8")])));
|
||||
await page.route("**/__kanban_git/*", route => route.fulfill({ contentType: "text/javascript", body: sources.get(new URL(route.request().url()).pathname.split("/").pop()) || "" }));
|
||||
const css = await readFile(resolve(gitRoot, "src/style.css"), "utf8");
|
||||
await page.evaluate(async css => {
|
||||
const { mountSidebar } = await import("/__kanban_git/view.js");
|
||||
const container = document.createElement("div"); container.id = "git-smoke"; container.style.cssText = "position:fixed;inset:45px 0 0 0;z-index:1000;background:var(--rs-bg)";
|
||||
document.body.append(container);
|
||||
window.gitGraphOpens = 0;
|
||||
window.disposeGitSmoke = mountSidebar(container, {
|
||||
workspace: {},
|
||||
git: { status: async () => ({ available: true, repository: true, branch: "main", changes: [] }), pull: async () => {}, push: async () => {} },
|
||||
openView: () => window.gitGraphOpens++,
|
||||
}, css, () => {});
|
||||
}, css);
|
||||
const graph = page.locator("#git-smoke").getByRole("button", { name: "Graph", exact: true });
|
||||
for (const theme of ["dark", "light"]) {
|
||||
await page.evaluate(async mode => { const { saveAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ theme: "default", mode }); }, theme);
|
||||
await graph.waitFor();
|
||||
assert.equal(await graph.locator("svg").count(), 1);
|
||||
assert.equal(await graph.getAttribute("title"), "Graph");
|
||||
assert.equal(await graph.evaluate(node => [...node.childNodes].filter(child => child.nodeType === Node.TEXT_NODE && child.textContent.trim()).length), 0);
|
||||
assert.equal(await graph.locator(":scope > :not(.rs-git-icon):not(.rs-git-tooltip)").count(), 0, "Graph has no visible text label");
|
||||
await page.mouse.move(800, 800); await graph.evaluate(node => node.blur());
|
||||
assert.equal(await graph.locator(".rs-git-tooltip").isVisible(), false);
|
||||
await graph.hover(); await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
|
||||
await page.mouse.move(800, 800); await page.keyboard.press("Tab"); await graph.focus();
|
||||
assert.equal(await graph.evaluate(node => node.matches(":focus-visible")), true);
|
||||
await graph.locator(".rs-git-tooltip").waitFor({ state: "visible" });
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: `.audit/kanban-git-toolbar-${theme}.png` });
|
||||
}
|
||||
await graph.click(); assert.equal(await page.evaluate(() => window.gitGraphOpens), 1);
|
||||
await page.evaluate(() => window.disposeGitSmoke());
|
||||
assert.deepEqual(errors, []);
|
||||
console.log("PASS: current Git Graph toolbar control is icon-only, keeps its accessible name, shows hover and focus tooltips in both themes, and opens Graph.");
|
||||
} catch (error) {
|
||||
await mkdir(".audit", { recursive: true });
|
||||
await page.screenshot({ path: ".audit/kanban-root-failure.png" });
|
||||
console.error(errors); throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -0,0 +1,31 @@
|
||||
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]);
|
||||
});
|
||||
@@ -123,7 +123,14 @@ try {
|
||||
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();
|
||||
await page.getByText("Original text.", { exact: true }).click({ button: "right" });
|
||||
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 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: [] },
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// 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();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
const { chromium } = createRequire(import.meta.url)(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : { channel: 'chrome' }) });
|
||||
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
|
||||
await context.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
let sequence = 0;
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: 'main' }, currentWebview: { label: 'main' } },
|
||||
transformCallback: () => ++sequence, unregisterCallback: () => {},
|
||||
invoke: async command => {
|
||||
if (command === 'plugins_snapshot') return { root: 'C:/plugins', plugins: [] };
|
||||
if (command === 'plugin:window|is_maximized') return false;
|
||||
if (command === 'plugin:event|listen') return ++sequence;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
|
||||
});
|
||||
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:5187';
|
||||
const settings = await context.newPage();
|
||||
const errors = [];
|
||||
settings.on('pageerror', error => errors.push(error.message));
|
||||
await mkdir('output/round4-overlay', { recursive: true });
|
||||
try {
|
||||
await settings.goto(origin + '/?settingsWindow=true');
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
await settings.getByLabel('Background image file', { exact: true }).setInputFiles({
|
||||
name: 'image.png', mimeType: 'image/png',
|
||||
buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64'),
|
||||
});
|
||||
const input = settings.getByRole('spinbutton', { name: 'Image overlay percentage' });
|
||||
const slider = settings.getByRole('slider', { name: 'Image overlay', exact: true });
|
||||
const saved = () => settings.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).newTabBackground.overlay);
|
||||
await input.fill('-37');
|
||||
assert.equal(await slider.inputValue(), '-37');
|
||||
assert.equal(await saved(), -0.37);
|
||||
await settings.reload();
|
||||
await settings.getByRole('button', { name: 'Appearance', exact: true }).click();
|
||||
assert.equal(await input.inputValue(), '-37');
|
||||
await input.fill('');
|
||||
assert.equal(await saved(), -0.37);
|
||||
await input.blur();
|
||||
assert.equal(await input.inputValue(), '-37');
|
||||
await input.fill('150');
|
||||
await input.blur();
|
||||
assert.equal(await input.inputValue(), '100');
|
||||
assert.equal(await saved(), 1);
|
||||
await slider.fill('24');
|
||||
assert.equal(await input.inputValue(), '24');
|
||||
assert.equal(await saved(), 0.24);
|
||||
for (const mode of ['light', 'dark']) {
|
||||
await settings.evaluate(async mode => {
|
||||
const appearance = await import('/src/lib/theme/appearance.ts');
|
||||
appearance.saveAppearance({ ...appearance.parseAppearance(localStorage.getItem(appearance.APPEARANCE_KEY)), mode });
|
||||
window.dispatchEvent(new Event('focus'));
|
||||
}, mode);
|
||||
for (const width of [1100, 360]) {
|
||||
await settings.setViewportSize({ width, height: 780 });
|
||||
await input.focus();
|
||||
assert.equal(await input.evaluate(node => node === document.activeElement), true);
|
||||
assert.equal(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth + 1), true);
|
||||
await settings.screenshot({ path: `output/round4-overlay/${mode}-${width}.png` });
|
||||
}
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
await writeFile('output/round4-overlay-report.json', JSON.stringify({
|
||||
card: '2d1ae11e-8142-4840-bf0a-70f682e90e53',
|
||||
hostChecks: ['Signed numeric entry and slider synchronization', 'Persistence after reload', 'Empty input retains saved value', 'Values clamp to -100 through 100', 'Both themes, keyboard focus, 360px and 1100px settings'],
|
||||
shared: ['--rs-settings-control-height', '--rs-settings-gap', '--rs-control-radius'],
|
||||
screenshotFolder: 'output/round4-overlay',
|
||||
native: 'Native desktop acceptance remains pending.',
|
||||
}, null, 2));
|
||||
console.log('PASS: numeric overlay, slider, persistence, bounds, themes, narrow settings, keyboard focus.');
|
||||
} finally { await browser.close(); }
|
||||
@@ -86,7 +86,7 @@ export async function packagePlugin(source, destination = "plugin-packages") {
|
||||
for (const key of ["name", "author", "description", "version"]) {
|
||||
requireValue(typeof manifest[key] === "string" && manifest[key].trim() && Buffer.byteLength(manifest[key]) <= 1000, `The manifest needs a valid ${key}.`);
|
||||
}
|
||||
requireValue(/^\d+\.\d+\.\d+$/.test(manifest.version), "Use a plugin version such as 1.0.0.");
|
||||
requireValue(/^\d+\.\d+\.\d+[a-z]*$/.test(manifest.version), "Use a plugin version such as 1.0.0 or 1.0.0a.");
|
||||
requireValue(typeof manifest.entry === "string" && validPath(manifest.entry) && /\.m?js$/.test(manifest.entry), "The entry must be a compiled JavaScript module.");
|
||||
const entry = files.find(([name]) => name === manifest.entry)?.[1];
|
||||
requireValue(entry, "The entry module is missing.");
|
||||
|
||||
@@ -70,7 +70,7 @@ 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(), 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('Task content', { exact: true }).waitFor();
|
||||
await main.evaluate(async () => {
|
||||
|
||||
@@ -21,6 +21,12 @@ test("installed RuneStone packages retain access before their next package updat
|
||||
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;
|
||||
|
||||
@@ -23,6 +23,10 @@ test("plugin packaging rejects invalid release inputs before writing an archive"
|
||||
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/],
|
||||
@@ -40,6 +44,13 @@ test("plugin packaging rejects invalid release inputs before writing an archive"
|
||||
const first = await readFile(path);
|
||||
await packagePlugin(source, output);
|
||||
assert.deepEqual(await readFile(path), first);
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
export function releaseVersion(value) {
|
||||
const match = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)([a-z]*)$/.exec(value);
|
||||
if (!match) throw Error('Use a release version such as 0.1.23 or 0.1.23a.');
|
||||
const parts = match.slice(1, 4).map(Number);
|
||||
let revision = 0;
|
||||
for (const letter of match[4]) revision = revision * 26 + letter.charCodeAt(0) - 96;
|
||||
if (parts.some(part => part > 65535) || revision > 65535) throw Error('The Windows version exceeds 65535.');
|
||||
const base = parts.join('.');
|
||||
return { version: value, base, suffix: match[4], revision,
|
||||
toolchain: revision ? `${base}+${revision}` : base, windows: `${base}.${revision}` };
|
||||
}
|
||||
|
||||
export function nextHotfix(value) {
|
||||
const parsed = releaseVersion(value);
|
||||
let revision = parsed.revision + 1;
|
||||
let suffix = '';
|
||||
while (revision) {
|
||||
revision--;
|
||||
suffix = String.fromCharCode(97 + revision % 26) + suffix;
|
||||
revision = Math.floor(revision / 26);
|
||||
}
|
||||
return releaseVersion(parsed.base + suffix).version;
|
||||
}
|
||||
|
||||
export function compareReleases(left, right) {
|
||||
const a = releaseVersion(left).windows.split('.').map(Number);
|
||||
const b = releaseVersion(right).windows.split('.').map(Number);
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return Math.sign(a[i] - b[i]);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
param(
|
||||
[Parameter(Mandatory)][string]$Path,
|
||||
[Parameter(Mandatory)][string]$Version,
|
||||
[Parameter(Mandatory)][string]$NumericVersion
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Diagnostics;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
public static class RuneStoneVersionResource {
|
||||
[DllImport("kernel32.dll", CharSet=CharSet.Unicode, SetLastError=true)]
|
||||
static extern IntPtr BeginUpdateResource(string path, bool deleteExisting);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool UpdateResource(IntPtr handle, IntPtr type, IntPtr name, ushort language, byte[] data, uint size);
|
||||
[DllImport("kernel32.dll", SetLastError=true)]
|
||||
static extern bool EndUpdateResource(IntPtr handle, bool discard);
|
||||
static void Align(BinaryWriter writer) { while (writer.BaseStream.Position % 4 != 0) writer.Write((byte)0); }
|
||||
static byte[] Text(string value) { return Encoding.Unicode.GetBytes(value + "\0"); }
|
||||
static byte[] Block(string key, ushort type, byte[] value, ushort valueLength, params byte[][] children) {
|
||||
using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) {
|
||||
writer.Write((ushort)0); writer.Write(valueLength); writer.Write(type);
|
||||
writer.Write(Text(key)); Align(writer); writer.Write(value);
|
||||
foreach (var child in children) { Align(writer); writer.Write(child); }
|
||||
long length = stream.Length; stream.Position = 0; writer.Write(checked((ushort)length));
|
||||
return stream.ToArray();
|
||||
}
|
||||
}
|
||||
static byte[] StringValue(string key, string value) {
|
||||
var bytes = Text(value); return Block(key, 1, bytes, checked((ushort)(bytes.Length / 2)));
|
||||
}
|
||||
public static void Set(string path, string version, string numeric) {
|
||||
var p = Array.ConvertAll(numeric.Split('.'), UInt16.Parse);
|
||||
if (p.Length != 4) throw new ArgumentException("Use four Windows version parts.");
|
||||
var previous = FileVersionInfo.GetVersionInfo(path);
|
||||
byte[] fixedInfo;
|
||||
using (var stream = new MemoryStream()) using (var writer = new BinaryWriter(stream)) {
|
||||
uint high = ((uint)p[0] << 16) | p[1], low = ((uint)p[2] << 16) | p[3];
|
||||
foreach (uint value in new uint[] { 0xFEEF04BD, 0x10000, high, low, high, low, 0x3F, 0, 4, 1, 0, 0, 0 }) writer.Write(value);
|
||||
fixedInfo = stream.ToArray();
|
||||
}
|
||||
var strings = Block("StringFileInfo", 1, new byte[0], 0,
|
||||
Block("040904B0", 1, new byte[0], 0,
|
||||
StringValue("CompanyName", previous.CompanyName ?? "RuneStone"),
|
||||
StringValue("FileDescription", previous.FileDescription ?? "RuneStone"),
|
||||
StringValue("ProductName", "RuneStone"),
|
||||
StringValue("OriginalFilename", "runestone.exe"),
|
||||
StringValue("FileVersion", version), StringValue("ProductVersion", version)));
|
||||
var vars = Block("VarFileInfo", 1, new byte[0], 0,
|
||||
Block("Translation", 0, new byte[] { 9, 4, 0xB0, 4 }, 4));
|
||||
var data = Block("VS_VERSION_INFO", 0, fixedInfo, 52, strings, vars);
|
||||
var handle = BeginUpdateResource(path, false);
|
||||
if (handle == IntPtr.Zero) throw new Win32Exception();
|
||||
if (!UpdateResource(handle, (IntPtr)16, (IntPtr)1, 0, data, (uint)data.Length)) {
|
||||
var error = new Win32Exception(); EndUpdateResource(handle, true); throw error;
|
||||
}
|
||||
if (!EndUpdateResource(handle, false)) throw new Win32Exception();
|
||||
}
|
||||
}
|
||||
'@
|
||||
$resolvedPath = (Resolve-Path -LiteralPath $Path).Path
|
||||
[RuneStoneVersionResource]::Set($resolvedPath, $Version, $NumericVersion)
|
||||
$actual = [Diagnostics.FileVersionInfo]::GetVersionInfo($resolvedPath)
|
||||
if ($actual.ProductVersion -ne $Version -or $actual.FileVersion -ne $Version) {
|
||||
throw 'The executable version resource does not match the release version.'
|
||||
}
|
||||
$actual | Select-Object FileVersion, ProductVersion, FileMajorPart, FileMinorPart, FileBuildPart, FilePrivatePart
|
||||
@@ -36,15 +36,26 @@ try {
|
||||
const before = await editor.innerText();
|
||||
await page.keyboard.press("End");
|
||||
await page.keyboard.type(" TEST");
|
||||
assert.notEqual(await editor.innerText(), before);
|
||||
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" });
|
||||
await menu.getByRole("menuitem", { name: "Undo Ctrl+Z", exact: true }).click();
|
||||
await page.waitForFunction(expected => document.querySelector(".cm-content")?.innerText === expected, before);
|
||||
console.log("PASS: real WebView2 command dispatch through the shared menu restores the editor text.");
|
||||
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();
|
||||
@@ -60,6 +71,25 @@ try {
|
||||
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();
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// Run against `pnpm dev`. PLAYWRIGHT_MODULE may point to a shared installation.
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir } from "node:fs/promises";
|
||||
const require = createRequire(import.meta.url);
|
||||
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || "playwright");
|
||||
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } });
|
||||
page.setDefaultTimeout(10000);
|
||||
const errors = [];
|
||||
await mkdir(".audit", { recursive: true });
|
||||
page.on("console", message => { if (message.type() === "error" || message.type() === "warning") console.log(message.type(), message.text()); });
|
||||
page.on("pageerror", error => errors.push(error.message));
|
||||
await page.addInitScript(() => {
|
||||
window.isTauri = true;
|
||||
const root = "C:\\smoke-workspace";
|
||||
const files = new Map([
|
||||
["notes/welcome.md", "---\ntitle: Welcome\n---\n\n# Working notes\n\nFirst paragraph.\n\n- [ ] A task\n\n[[second]]\n"],
|
||||
["notes/second.md", "# Second note\n"],
|
||||
["src/hello.py", "print('hello')\n"],
|
||||
]);
|
||||
const callbacks = new Map();
|
||||
const listeners = new Map();
|
||||
let sequence = 0;
|
||||
const calls = [];
|
||||
const emit = (event, payload) => {
|
||||
for (const id of listeners.get(event) || []) callbacks.get(id)?.({ event, id, payload });
|
||||
};
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback: id => callbacks.delete(id),
|
||||
invoke: async (command, args = {}) => {
|
||||
calls.push({ command, args });
|
||||
if (command === "plugin:event|listen") {
|
||||
const list = listeners.get(args.event) || []; list.push(args.handler); listeners.set(args.event, list); return args.handler;
|
||||
}
|
||||
if (command === "plugin:event|unlisten") { callbacks.delete(args.eventId); return; }
|
||||
if (command === "workspace_last_path") return root;
|
||||
if (command === "workspace_open") return { root, name: "smoke-workspace", watch_mode: "native" };
|
||||
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
|
||||
if (command === "workspace_write") {
|
||||
if (args.expected !== undefined && files.get(args.rel) !== args.expected) throw new Error("Save blocked: file changed on disk");
|
||||
files.set(args.rel, args.contents); emit("workspace-event", { root, kind: "modify", paths: [args.rel] }); return;
|
||||
}
|
||||
if (command === "workspace_list") {
|
||||
const prefix = args.rel ? args.rel + "/" : "";
|
||||
const entries = new Map();
|
||||
for (const path of files.keys()) {
|
||||
if (!path.startsWith(prefix) || path.startsWith(".runestone/")) continue;
|
||||
const tail = path.slice(prefix.length); const name = tail.split("/")[0];
|
||||
entries.set(name, { name, rel_path: prefix + name, kind: tail.includes("/") ? "folder" : "file" });
|
||||
}
|
||||
return [...entries.values()];
|
||||
}
|
||||
if (command === "workspace_create") { if (files.has(args.rel)) throw new Error("exists"); files.set(args.rel, ""); return; }
|
||||
if (command === "workspace_search") return [];
|
||||
if (command === "spelling_menu_install") return;
|
||||
if (command === "pty_open") {
|
||||
const data = [...new TextEncoder().encode("READY 🪨\r\n\x1b[6n")];
|
||||
emit("pty-data", { id: args.id, data: data.slice(0, 8) });
|
||||
emit("pty-data", { id: args.id, data: data.slice(8) });
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
return;
|
||||
}
|
||||
if (command.startsWith("pty_")) return;
|
||||
if (command === "plugin:dialog|message") return "Cancel";
|
||||
throw new Error(`Unhandled IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: (_event, id) => callbacks.delete(id) };
|
||||
window.__TEST__ = { files, calls, emit, root };
|
||||
});
|
||||
|
||||
|
||||
try {
|
||||
await mkdir('output/todo-table', { recursive: true });
|
||||
await page.goto(process.env.SMOKE_URL || 'http://127.0.0.1:1420');
|
||||
await page.getByText('smoke-workspace', { exact: true }).waitFor();
|
||||
await page.keyboard.press('Control+p');
|
||||
await page.getByRole('textbox', { name: 'Find a file' }).fill('welcome.md');
|
||||
await page.getByRole('dialog').getByRole('button').filter({ hasText: 'welcome.md' }).first().click();
|
||||
await page.getByRole('textbox', { name: 'Writing editor', exact: true }).waitFor();
|
||||
await page.evaluate(async () => {
|
||||
const { EditorView } = await import('/node_modules/@codemirror/view/dist/index.js');
|
||||
window.__CM__ = EditorView.findFromDOM(document.querySelector('.cm-content'));
|
||||
});
|
||||
const source = '# Table selection\n\n| Name | Value | Notes |\n| --- | :---: | ---: |\n| Alpha | 10 | First |\n| Beta | 20 | Second |\n| Gamma | 30 | Third |\n\nAfter.\n';
|
||||
const table = page.locator('.live-writer table');
|
||||
const cell = (r,c) => table.locator('tr').nth(r).locator('th,td').nth(c);
|
||||
const selected = table.locator('.is-cell-selected');
|
||||
async function reset() {
|
||||
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), source);
|
||||
await table.waitFor();
|
||||
}
|
||||
const contents = () => page.evaluate(() => window.__CM__.state.sliceDoc());
|
||||
async function drag(r,c,r2,c2) {
|
||||
const start = await cell(r,c).boundingBox(), end = await cell(r2,c2).boundingBox();
|
||||
await page.mouse.move(start.x+start.width/2,start.y+start.height/2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(end.x+end.width/2,end.y+end.height/2,{steps:8});
|
||||
await page.mouse.up();
|
||||
}
|
||||
await reset();
|
||||
await drag(1,0,2,1);
|
||||
assert.equal(await selected.count(),4);
|
||||
assert.deepEqual(await selected.evaluateAll(cells => cells.map(c => c.getAttribute('data-selection-edges'))),['top left','top right','bottom left','bottom right']);
|
||||
await page.keyboard.press('Delete');
|
||||
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
|
||||
assert.equal(await selected.count(),1);
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(source => window.__CM__.state.sliceDoc() === source,source);
|
||||
await drag(2,1,1,0);
|
||||
await page.keyboard.press('Backspace');
|
||||
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
|
||||
await reset();
|
||||
await drag(1,0,2,1);
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Clear cells',exact:true}).click();
|
||||
assert.equal(await contents(),source.replace('Alpha','').replace('10','').replace('Beta','').replace('20',''));
|
||||
assert.equal(await selected.count(),4);
|
||||
await reset();
|
||||
await cell(1,0).click();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
|
||||
assert.equal(await selected.count(),1);
|
||||
await page.keyboard.press('Shift+ArrowRight');
|
||||
await page.keyboard.press('Shift+ArrowDown');
|
||||
assert.equal(await selected.count(),4);
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
|
||||
assert.ok((await contents()).includes('| First | | |\n| Second | | |'));
|
||||
await reset();
|
||||
await cell(1,0).click();
|
||||
await cell(2,2).click({modifiers:['Shift']});
|
||||
assert.equal(await selected.count(),6);
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
|
||||
assert.equal(await table.locator('tr').count(),2);
|
||||
assert.ok((await contents()).includes('Gamma'));
|
||||
await reset();
|
||||
await drag(0,1,3,1);
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
|
||||
assert.equal(await table.locator('th').count(),2);
|
||||
assert.ok(!(await contents()).includes('Value'));
|
||||
const emptyColumns = '# Empty columns\n\n| Column 2 | Column 1 | | | | |\n| --- | --- | --- | --- | --- | --- |\n| 2cm | Value | | | | |\n| text | 123 | | | | |\n| | | | | | |\n| | | | | | |\n\nAfter.\n';
|
||||
for (const theme of ['light','dark']) for (const width of [1440,760]) {
|
||||
await page.setViewportSize({width,height:900});
|
||||
await page.evaluate(async theme => { const {applyAppearance} = await import('/src/lib/theme/appearance.ts'); applyAppearance({theme:'default',mode:theme}); },theme);
|
||||
await reset();
|
||||
await cell(0,1).click();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
|
||||
await page.keyboard.press('Shift+ArrowRight');
|
||||
for (let row = 0; row < 3; row++) await page.keyboard.press('Shift+ArrowDown');
|
||||
assert.equal(await selected.count(),8);
|
||||
assert.ok(await selected.evaluateAll(cells => cells.every(c => getComputedStyle(c).borderRadius === '0px')));
|
||||
await page.screenshot({path:`output/todo-table/selection-${theme}-${width}.png`});
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.screenshot({path:`output/todo-table/menu-${theme}-${width}.png`});
|
||||
await page.keyboard.press('Escape');
|
||||
assert.equal(await page.locator('.writer-table').evaluate(el => document.activeElement === el),true);
|
||||
await page.evaluate(source => window.__CM__.dispatch({ changes: { from: 0, to: window.__CM__.state.doc.length, insert: source }, selection: { anchor: 0 } }), emptyColumns);
|
||||
await table.waitFor();
|
||||
await cell(0,0).click();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
|
||||
for (let col = 0; col < 3; col++) await page.keyboard.press('ArrowRight');
|
||||
for (let col = 0; col < 2; col++) await page.keyboard.press('Shift+ArrowRight');
|
||||
for (let row = 0; row < 4; row++) await page.keyboard.press('Shift+ArrowDown');
|
||||
assert.equal(await selected.count(),15);
|
||||
await page.screenshot({path:`output/todo-table/empty-columns-selected-${theme}-${width}.png`});
|
||||
await page.keyboard.press('Delete');
|
||||
assert.equal(await table.locator('th').count(),3);
|
||||
assert.equal(await table.locator('tr').count(),5);
|
||||
assert.equal(await selected.count(),1);
|
||||
assert.ok((await contents()).includes('| 2cm | Value | |'));
|
||||
await page.screenshot({path:`output/todo-table/empty-columns-deleted-${theme}-${width}.png`});
|
||||
await page.keyboard.press('Control+z');
|
||||
await page.waitForFunction(source => window.__CM__.state.sliceDoc() === source,emptyColumns);
|
||||
await cell(0,0).click();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
|
||||
for (let col = 0; col < 3; col++) await page.keyboard.press('ArrowRight');
|
||||
for (let col = 0; col < 2; col++) await page.keyboard.press('Shift+ArrowRight');
|
||||
for (let row = 0; row < 4; row++) await page.keyboard.press('Shift+ArrowDown');
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
|
||||
assert.equal(await table.locator('th').count(),3);
|
||||
await reset();
|
||||
await cell(2,0).click();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
|
||||
await page.keyboard.press('Shift+ArrowRight');
|
||||
await page.keyboard.press('Shift+ArrowRight');
|
||||
await page.keyboard.press('Shift+ArrowDown');
|
||||
await page.keyboard.press('Backspace');
|
||||
assert.equal(await table.locator('tr').count(),2);
|
||||
assert.ok((await contents()).includes('Alpha'));
|
||||
assert.ok(!(await contents()).includes('Beta'));
|
||||
await reset();
|
||||
await cell(0,0).click();
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Select cell',exact:true}).click();
|
||||
await page.keyboard.press('Shift+ArrowRight');
|
||||
await page.keyboard.press('Shift+ArrowRight');
|
||||
await page.keyboard.press('Delete');
|
||||
assert.equal(await table.locator('th').first().innerText(),'Alpha');
|
||||
await page.keyboard.press('Control+a');
|
||||
await page.keyboard.press('Shift+F10');
|
||||
await page.getByRole('menuitem',{name:'Delete cells',exact:true}).click();
|
||||
assert.equal(await table.count(),0);
|
||||
assert.ok((await contents()).includes('After.'));
|
||||
}
|
||||
assert.deepEqual(errors,[]);
|
||||
console.log('PASS: drag and Shift-click ranges, keyboard range entry and extension, Delete/Backspace remove cells, explicit clear, undo, partial/row/column/all delete, outer edges, light/dark narrow screenshots.');
|
||||
} catch(error) {
|
||||
await page.screenshot({path:'output/todo-table/failure.png'});
|
||||
console.error(errors);
|
||||
throw error;
|
||||
} finally { await browser.close(); }
|
||||
@@ -54,3 +54,18 @@ test("clear preserves structure; delete removes whole rows/columns or shifts par
|
||||
assert.ok(header.startsWith("| one | two | three |\r\n| --- | :---: | ---: |"));
|
||||
assert.equal(deleteTableCells(source, { anchor: { row: 0, column: 0 }, head: { row: 2, column: 2 } }), "\r\n\r\nTail");
|
||||
});
|
||||
|
||||
test("deleting the empty columns shown on the card removes their structure", () => {
|
||||
const emptyColumns = "| Column 2 | Column 1 | | | | |\n| --- | --- | --- | --- | --- | --- |\n| 2cm | Value | | | | |\n| text | 123 | | | | |\n| | | | | | |\n| | | | | | |\n\nAfter.";
|
||||
const result = deleteTableCells(emptyColumns, { anchor: { row: 4, column: 5 }, head: { row: 0, column: 3 } });
|
||||
assert.equal(parseMarkdownTable(result)?.columns, 3);
|
||||
assert.equal(parseMarkdownTable(result)?.rows.length, 6);
|
||||
assert.ok(result.includes("| 2cm | Value | |"));
|
||||
assert.ok(result.endsWith("\n\nAfter."));
|
||||
});
|
||||
|
||||
test("deleting the last body rows retains a valid header and alignment", () => {
|
||||
const result = deleteTableCells(source, { anchor: { row: 2, column: 2 }, head: { row: 1, column: 0 } });
|
||||
assert.equal(result, "| A | B | C |\r\n| --- | :---: | ---: |\r\n\r\nTail");
|
||||
assert.equal(parseMarkdownTable(result)?.rows.length, 2);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { workspaceFileLink } from "../src/lib/editor/workspaceFileLink.ts";
|
||||
import { wordAt } from "../src/lib/editor/spellingWord.ts";
|
||||
|
||||
test("file links resolve across nested folders and escape Markdown punctuation", () => {
|
||||
assert.equal(workspaceFileLink("notes/deep/source.md", "docs/a [draft](1).pdf"), "[a \\[draft\\](1).pdf](../../docs/a%20%5Bdraft%5D%281%29.pdf)");
|
||||
assert.equal(workspaceFileLink("notes/source.md", "notes/target.md"), "[target.md](target.md)");
|
||||
assert.equal(workspaceFileLink("notes/source.md", "assets/pic.png"), "");
|
||||
});
|
||||
|
||||
test("spelling finds Unicode words and apostrophes without including punctuation", () => {
|
||||
assert.deepEqual(wordAt("A naïve word.", 5), { word: "naïve", from: 2, to: 7 });
|
||||
assert.equal(wordAt("Don't stop", 3)?.word, "Don't");
|
||||
assert.equal(wordAt("word next", 5), null);
|
||||
});
|
||||
Reference in New Issue
Block a user