Add interface languages and improve themes and workspace controls for 0.1.36

This commit is contained in:
Knotty Wyvern
2026-10-15 10:55:59 -07:00
parent b066359b66
commit 68e86ab6eb
98 changed files with 5499 additions and 874 deletions
+5 -5
View File
@@ -47,7 +47,7 @@ test('Character palettes restore one appearance and export readable surfaces and
const exported = exportAppearanceTheme(theme);
for (const mode of ['light', 'dark'] as const) {
assert.deepEqual(parseAppearance(JSON.stringify({ theme, mode })), { theme, mode: CHARACTER_THEMES[theme].mode });
const colors = exported[mode];
const colors = exported.colors;
for (const foreground of ['text', 'text-dim', 'text-strong', 'accent'] as const) {
for (const background of ['bg', 'bg-elevated', 'bg-active', 'selection'] as const) {
if (foreground === 'accent' && background === 'selection') continue;
@@ -56,15 +56,15 @@ test('Character palettes restore one appearance and export readable surfaces and
}
}
assert.deepEqual(themeModes(theme), [CHARACTER_THEMES[theme].mode]);
assert.deepEqual(exported.light, exported.dark);
assert.equal(exported.schema, 2);
assert.deepEqual(parseCustomTheme(exported), exported);
for (const role of SYNTAX_ROLES) {
for (const background of ['bg', 'bg-active'] as const) {
assert(contrast(exported.light[`syntax-${role}`]!, exported.light[background]!) >= 4.5, `${theme}: ${role} on ${background}`);
assert(contrast(exported.colors[`syntax-${role}`]!, exported.colors[background]!) >= 4.5, `${theme}: ${role} on ${background}`);
}
}
assert(new Set(SYNTAX_ROLES.map(role => exported.light[`syntax-${role}`])).size >= 7);
assert.notDeepEqual(exported.dark, exportAppearanceTheme('default').dark);
assert(new Set(SYNTAX_ROLES.map(role => exported.colors[`syntax-${role}`])).size >= 7);
assert.notDeepEqual(exported.colors, exportAppearanceTheme('default').colors);
}
});
test('Sakura cannot restore or save a dark appearance', () => {
+125
View File
@@ -0,0 +1,125 @@
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
await mkdir('.audit/appearance-language', { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = "C:\\appearance-smoke";
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
const callbacks = new Map();
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const settings = await context.newPage();
const main = await context.newPage();
for (const page of [settings, main]) { page.on('pageerror', error => errors.push(error.message)); page.setDefaultTimeout(15000); }
await main.goto(origin);
await settings.goto(`${origin}/?settingsWindow=true`);
await settings.locator('#language-picker').waitFor();
for (const [language, name, heading, appearance, enabled, files] of [
['fr', 'Français', 'Paramètres', 'Apparence', 'Surfaces transparentes', 'Fichiers'],
['ja', '日本語', '設定', '外観', '背景を透過', 'ファイル'],
['zh-CN', '简体中文', '设置', '外观', '透明界面', '文件'],
['en', 'English', 'Settings', 'Appearance', 'Transparent surfaces', 'Files'],
]) {
await settings.locator('#language-picker').click();
await settings.getByRole('menuitemradio', { name, exact: true }).click();
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
await main.getByRole('button', { name: files, exact: true }).waitFor();
assert.equal(await settings.locator('html').getAttribute('lang'), language);
assert.equal(await main.locator('html').getAttribute('lang'), language);
assert.equal(await settings.evaluate(() => localStorage.getItem('runestone.language')), language);
await settings.reload();
await settings.getByRole('heading', { name: heading, exact: true }).waitFor();
// Arrow keys and Escape retain shared menu focus behavior.
await settings.locator('#language-picker').focus();
await settings.keyboard.press('Enter');
await settings.keyboard.press('End');
await settings.keyboard.press('Home');
await settings.keyboard.press('Escape');
assert(await settings.locator('#language-picker').evaluate(node => node === document.activeElement));
assert(await main.evaluate(async () => {
const { imageControls } = await import('/src/lib/editor/imageControls.ts');
const root = document.createElement('div'); root.innerHTML = '<img data-md-src="sample.png" alt="sample">'; document.body.append(root);
let removed = false;
const cleanup = imageControls(root, { remove: () => { removed = true; } });
root.querySelector('.md-image-frame').dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
cleanup(); root.remove(); return removed;
}), `${language}: Delete image keyboard action`);
assert(await main.evaluate(async () => {
const { tableSelectionControls } = await import('/src/lib/editor/tableSelectionControls.ts');
const root = document.createElement('div'); root.innerHTML = '<div><table><tr><th>A</th><th>B</th></tr><tr><td>one</td><td>two</td></tr></table></div>'; document.body.append(root);
const wrapper = root.firstElementChild, table = root.querySelector('table');
let text = '| A | B |\n| --- | --- |\n| one | two |';
const view = { posAtDOM: () => 0, dom: root, focus() {} };
const controls = tableSelectionControls(root, wrapper, table, view, () => text, () => {}, next => { text = next; }, { get: () => undefined, activate() {}, editSource() {} }, {});
controls.select({ anchor: { row: 1, column: 0 }, head: { row: 1, column: 0 } });
wrapper.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true }));
controls.destroy(); root.remove(); return !text.includes('one') && text.includes('two');
}), `${language}: Delete selected table cell keyboard action`);
await settings.screenshot({ path: `.audit/appearance-language/${language}-general.png` });
await main.locator('[data-tree-rel="theme-0.py"]').click();
await main.locator('.monaco-editor textarea').waitFor();
await main.locator('.view-lines').first().click({ button: 'right' });
await main.locator('.rs-menu').waitFor();
const copyLabels = { fr: 'Copier', ja: 'コピー', 'zh-CN': '复制', en: 'Copy' };
await main.locator('.rs-menu .action-label').filter({ hasText: new RegExp('^' + copyLabels[language] + '$') }).waitFor();
await main.screenshot({ path: `.audit/appearance-language/${language}-workbench-editor-menu.png` });
await main.keyboard.press('Escape');
await settings.getByRole('button', { name: appearance, exact: true }).click();
for (const mode of ['dark', 'light']) {
await settings.evaluate(async mode => {
const appearance = await import('/src/lib/theme/appearance.ts');
appearance.saveAppearance({ theme: 'default', mode, transparency: { enabled: true, amount: 18 } });
window.dispatchEvent(new Event('focus'));
}, mode);
const toggle = settings.getByRole('switch', { name: enabled, exact: true });
await toggle.uncheck();
assert.equal(await settings.locator('html').getAttribute('data-transparency'), 'off');
await main.waitForFunction(() => document.documentElement.dataset.transparency === 'off');
const opacity = await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim());
assert.equal(opacity, '100%');
await settings.locator('.picker').first().click();
const menu = settings.getByRole('menu');
const bg = await menu.evaluate(node => getComputedStyle(node).backgroundColor);
assert(!bg.endsWith('/ 0.82)') && !bg.startsWith('rgba'), `Opaque menu: ${bg}`);
await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-opaque-menu.png` });
await settings.keyboard.press('Escape');
await toggle.check();
await settings.locator('#surface-transparency').fill('30');
assert.equal(await settings.evaluate(() => getComputedStyle(document.documentElement).getPropertyValue('--rs-surface-opacity').trim()), '70%');
await settings.setViewportSize({ width: 360, height: 640 });
await settings.locator("#surface-transparency").scrollIntoViewIfNeeded();
assert(await settings.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth), `${language} ${mode}: narrow overflow`);
await settings.screenshot({ path: `.audit/appearance-language/${language}-${mode}-narrow.png` });
await settings.setViewportSize({ width: 1100, height: 800 });
}
await settings.reload();
}
assert.deepEqual(errors, []);
console.log('PASS: 4 locales, persistence, cross-window updates, keyboard menu focus, both themes, opaque menus, transparency levels, narrow layout.');
} finally { await browser.close(); }
+2 -2
View File
@@ -40,8 +40,8 @@ test('app override uses body properties and removes them without changing curren
const owner = Symbol();
hub.set(owner, 'app', frame);
assert.match(properties.get('--rs-background-image')!, /blob:http/);
assert.equal(properties.get('--rs-workarea-surface-opacity'), '82%');
assert.equal(properties.get('--rs-workarea-plugin-bg'), 'transparent');
assert.equal(properties.get('--rs-workarea-surface-opacity'), 'var(--rs-surface-opacity, 82%)');
assert.equal(properties.get('--rs-workarea-plugin-bg'), 'var(--rs-transparent-plugin-bg, transparent)');
root.set('--rs-background-image', 'new saved image');
hub.set(owner, 'app', { ...frame, overlay: -0.5, size: 'contain' });
assert.match(properties.get('--rs-background-image')!, /255,255,255,0.5/);
+2 -2
View File
@@ -5,12 +5,12 @@ import { fileURLToPath } from "node:url";
import { packagePlugin } from "./packagePlugin.mjs";
const root = fileURLToPath(new URL("../", import.meta.url));
const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_TableFormulas"));
const formulasRoot = resolve(process.env.RUNESTONE_TABLE_FORMULAS_ROOT || resolve(root, "../RuneStone_Table_Formulas"));
const formulasBuild = resolve(formulasRoot, "scripts/build.mjs");
try {
await access(formulasBuild);
} catch {
throw new Error("Clone RuneStone_TableFormulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins.");
throw new Error("Clone RuneStone_Table_Formulas beside RuneStone, or set RUNESTONE_TABLE_FORMULAS_ROOT. Install its dependencies before building plugins.");
}
execFileSync(process.execPath, [formulasBuild], { cwd: formulasRoot, stdio: "inherit" });
const formulasOutput = resolve(root, "plugin-packages/table-formulas");
+107 -11
View File
@@ -1,15 +1,111 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseCustomTheme } from "../src/lib/theme/customThemes.ts";
const palette = { bg: "#123", text: "#abcdef", accent: "#AABBCC" };
const theme = { schema: 1, id: "my-theme", name: "My theme", light: palette, dark: palette };
test("theme files accept explicit color tokens in both appearances", () => {
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { COLOR_TOKENS, parseCustomTheme } from '../src/lib/theme/customThemes.ts';
import { applyTransparency, normalizeAppearance, exportAppearanceTheme, BUILTIN_THEMES, themeModes } from '../src/lib/theme/appearance.ts';
const palette = { bg: '#123', text: '#abcdef', accent: '#AABBCC' };
const theme = { schema: 2, id: 'my-theme', name: 'My theme', colors: palette };
test('Fixed theme palettes retain all supplied colors', () => {
assert.deepEqual(parseCustomTheme(theme), theme);
});
test("theme files reject CSS injection, unknown tokens, and incomplete palettes", () => {
for (const dark of [{ ...palette, bg: "url(https://invalid.test)" }, { ...palette, position: "fixed" }, { bg: "#000" }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, dark }));
test('Legacy import selects the current appearance and validates both palettes', () => {
const light = { ...palette, bg: '#fff' };
const legacy = { schema: 1, id: theme.id, name: theme.name, light, dark: palette };
assert.deepEqual(parseCustomTheme(legacy).colors, palette);
assert.deepEqual(parseCustomTheme(legacy, 'light').colors, light);
assert.throws(() => parseCustomTheme({ ...legacy, light: {} }));
});
test('Theme files reject CSS injection, unknown tokens, and incomplete palettes', () => {
for (const colors of [{ ...palette, bg: 'url(https://invalid.test)' }, { ...palette, position: 'fixed' }, { bg: '#000' }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, colors }));
}
assert.throws(() => parseCustomTheme({ ...theme, id: "../unsafe" }));
assert.throws(() => parseCustomTheme({ ...theme, id: '../unsafe' }));
});
test('Every built-in template contains every current color token and one palette', () => {
for (const item of BUILTIN_THEMES) for (const mode of themeModes(item.id)) {
const exported = exportAppearanceTheme(item.id, mode);
assert.deepEqual(Object.keys(exported.colors).sort(), [...COLOR_TOKENS].sort());
assert.deepEqual(parseCustomTheme(exported), exported);
assert.equal('light' in exported, false);
assert.equal('dark' in exported, false);
}
assert.notDeepEqual(exportAppearanceTheme('default', 'light').colors, exportAppearanceTheme('default', 'dark').colors);
});
test('Transparency normalizes old, invalid, and extreme saved values', () => {
assert.equal(normalizeAppearance(null).transparency, undefined);
assert.deepEqual(normalizeAppearance({ transparency: { enabled: false, amount: 27 } }).transparency, { enabled: false, amount: 27 });
for (const [amount, expected] of [[-10, 0], [55, 55], [100, 100], [120, 100], [NaN, 18], [Infinity, 18], [12.8, 13]]) {
assert.equal(normalizeAppearance({ transparency: { amount } }).transparency?.amount, expected);
}
});
test('Theme font roles round-trip and reject CSS injection', () => {
const fonts = { ui: 'Arial, sans-serif', prose: '"Times New Roman", serif', heading: 'Georgia, serif', mono: 'Consolas, monospace' };
assert.deepEqual(parseCustomTheme({ ...theme, fonts }).fonts, fonts);
for (const fonts of [{ ui: 'url(https://example.test)' }, { ui: 'Arial; color: red' }, { unknown: 'Arial' }, { ui: '' }, { ui: 'Arial,,serif' }, { ui: '"Arial' }, []]) {
assert.throws(() => parseCustomTheme({ ...theme, fonts }));
}
for (const item of BUILTIN_THEMES) {
const exported = exportAppearanceTheme(item.id);
assert.deepEqual(Object.keys(exported.fonts!).sort(), ['heading', 'mono', 'prose', 'ui']);
assert.deepEqual(parseCustomTheme(exported), exported);
}
assert.match(exportAppearanceTheme('claude').fonts!.heading!, /Poppins/);
assert.match(exportAppearanceTheme('harvest-moon').fonts!.ui!, /Candara/);
});
test('Full transparency range produces valid surface opacity values', () => {
const values = new Map<string, string>();
const root = { dataset: {}, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
for (const amount of [0, 18, 40, 55, 99, 100]) {
applyTransparency({ enabled: true, amount }, root);
assert.equal(values.get('--rs-surface-opacity'), `${100 - amount}%`);
for (const key of ['--rs-surface-opacity', '--rs-editor-surface-opacity', '--rs-hover-surface-opacity']) {
const opacity = parseFloat(values.get(key)!);
assert(opacity >= 0 && opacity <= 100);
}
}
});
test('Opaque mode removes surface transparency and retains the amount for re-enabling', () => {
const values = new Map<string, string>();
const root = { dataset: {} as Record<string, string>, style: { setProperty: (key: string, value: string) => values.set(key, value) } } as unknown as HTMLElement;
applyTransparency({ enabled: false, amount: 32 }, root);
assert.equal(values.get('--rs-surface-opacity'), '100%');
assert.equal(values.get('--rs-editor-surface-opacity'), '100%');
assert.equal(values.get('--rs-transparent-plugin-bg'), 'var(--rs-bg)');
assert.equal(root.dataset.transparency, 'off');
applyTransparency({ enabled: true, amount: 18 }, root);
assert.equal(values.get('--rs-surface-opacity'), '82%');
assert.equal(values.get('--rs-editor-surface-opacity'), '90%');
assert.equal(root.dataset.transparency, 'on');
});
test('Saved legacy light themes migrate once and preserve both original palettes', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../src/lib/theme/customThemes.ts');
const legacy = { schema: 1, id: 'saved-light', name: 'Saved light', light: { ...palette, bg: '#fff' }, dark: { ...palette, bg: '#111' } };
const stored = new Map([[CUSTOM_THEMES_KEY, JSON.stringify([legacy])], ['runestone.appearance', JSON.stringify({ theme: 'custom:saved-light', mode: 'light' })]]);
const previous = globalThis.localStorage;
try {
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as Storage;
assert.deepEqual(customThemes()[0].colors, legacy.light);
assert.deepEqual(themeModes('custom:saved-light'), ['light']);
assert.equal(normalizeAppearance({ theme: 'custom:saved-light', mode: 'dark' }).mode, 'light');
assert.deepEqual(exportAppearanceTheme('custom:saved-light').colors.bg, '#fff');
assert.equal(JSON.parse(stored.get(CUSTOM_THEMES_KEY)!)[0].schema, 2);
assert.deepEqual(JSON.parse(stored.get(`${CUSTOM_THEMES_KEY}.legacy`)!)[0], legacy);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
} finally { globalThis.localStorage = previous; }
});
test('Legacy migration storage failure leaves the original palette available', async () => {
const { customThemes, CUSTOM_THEMES_KEY } = await import('../src/lib/theme/customThemes.ts');
const legacy = { schema: 1, id: 'quota-light', name: 'Quota light', light: { ...palette, bg: '#fefefe' }, dark: palette };
const raw = JSON.stringify([legacy]);
const previous = globalThis.localStorage;
let original = raw;
try {
globalThis.localStorage = { getItem: (key: string) => key === CUSTOM_THEMES_KEY ? original : null, setItem: () => { throw new Error('Quota exceeded'); } } as unknown as Storage;
assert.deepEqual(customThemes('light')[0].colors, legacy.light);
assert.equal(original, raw);
assert.deepEqual(customThemes('dark')[0].colors, legacy.light);
} finally { globalThis.localStorage = previous; }
});
+40
View File
@@ -2,6 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import { ExternalSession } from "../src/lib/plugins/externalSession.ts";
import type { PluginApi } from "../src/lib/plugins/sdk.ts";
import { locale } from "../src/lib/i18n/index.ts";
function fixture() {
let writes = 0;
const session = new ExternalSession("org.test.demo", {
@@ -12,6 +13,25 @@ function fixture() {
return { session, writes: () => writes };
}
test("plugin language changes stop before cleanup and reject later access", async () => {
const { session } = fixture();
const changes: string[] = [];
let api!: PluginApi;
try {
await session.start({ activate(value) {
api = value;
api.i18n!.subscribe(language => changes.push(language));
api.onDispose(() => { locale.set('ja'); });
} });
locale.set('fr');
assert.equal(api.i18n!.t('Settings'), 'Paramètres');
await session.stop();
assert.deepEqual(changes, ['en', 'fr']);
assert.throws(() => api.i18n!.t('Settings'), /disabled/);
assert.throws(() => api.i18n!.locale, /disabled/);
} finally { await session.stop(); locale.set('en'); }
});
test("native Markdown discovery remains optional and is revoked on disable", async () => {
let api!: PluginApi;
let scans = 0;
@@ -93,3 +113,23 @@ test("cleanup returned by late activation still blocks shutdown when it fails",
await Promise.resolve(); const stopping = session.stop(); done();
await assert.rejects(starting, /Late cleanup failed/); await assert.rejects(stopping, /Late cleanup failed/);
});
test("batch workspace reads remain optional and stop when the plugin is disabled", async () => {
let api!: PluginApi;
let calls = 0;
const rows = [{ path: "Card.md", source: "Card source" }, { path: "Missing.md", error: "File not found" }];
const session = new ExternalSession("org.test.batch", {
workspace: { list: async () => [], read: async () => "", write: async () => {},
readMany: async paths => { calls++; assert.deepEqual(paths, ["Card.md", "Missing.md"]); return rows; } },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
}, () => {}, () => {});
await session.start({ activate(value) { api = value; } });
assert.deepEqual(await api.workspace.readMany!(["Card.md", "Missing.md"]), rows);
await session.stop();
assert.throws(() => api.workspace.readMany!(["Card.md"]), /disabled/);
assert.equal(calls, 1);
const old = fixture().session;
await old.start({ activate(value) { assert.equal(value.workspace.readMany, undefined); } });
await old.stop();
});
+100
View File
@@ -0,0 +1,100 @@
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const origin = process.env.SMOKE_URL || 'http://127.0.0.1:1420';
const browser = await chromium.launch({ headless: true, ...(process.env.CHROME_PATH ? { executablePath: process.env.CHROME_PATH } : {}) });
const errors = [];
await mkdir('.audit/host-ui', { recursive: true });
try {
const context = await browser.newContext({ viewport: { width: 1100, height: 800 } });
await context.addInitScript(() => {
window.isTauri = true;
const root = "C:\\appearance-smoke";
const files = new Map(Array.from({ length: 12 }, (_, index) => [`theme-${index}.py`, `# Theme sample ${index}\ndef sample(parameter):\n return parameter\nname = "RuneStone"\nprint(name, 42)\n`]));
const callbacks = new Map();
let sequence = 0;
window.__TAURI_INTERNALS__ = {
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
transformCallback: callback => { const id = ++sequence; callbacks.set(id, callback); return id; },
unregisterCallback: id => callbacks.delete(id),
invoke: async (command, args = {}) => {
if (command === "plugins_snapshot") return { root: "C:/appearance-smoke-plugins", plugins: [] };
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "appearance-smoke", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("File absent"); return files.get(args.rel); }
if (command === "workspace_write") { files.set(args.rel, args.contents); return; }
if (command === "workspace_list") return [...files.keys()].filter(path => !path.startsWith(".")).map(path => ({ name: path, rel_path: path, kind: "file" }));
if (command === "workspace_search") return [];
if (command === "plugin:event|listen") return args.handler;
if (command === "plugin:window|is_maximized") return false;
return null;
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
});
const page = await context.newPage();
page.on('pageerror', error => errors.push(error.message));
await page.goto(`${origin}/?settingsWindow=true`);
await page.getByRole('button', { name: 'Appearance', exact: true }).click();
for (const [theme, mode] of [['default','dark'],['default','light'],['claude','dark'],['claude','light'],['sakura','light'],['harvest-moon','dark'],['crimson-pilot','dark'],['silver-serpent','dark']]) {
await page.evaluate(async ({theme,mode}) => {
(await import('/src/lib/theme/appearance.ts')).saveAppearance({theme,mode,transparency:{enabled:true,amount:18}});
window.dispatchEvent(new Event('focus'));
},{theme,mode});
const slider = page.locator('#surface-transparency');
await slider.fill('100');
assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem('runestone.appearance')).transparency.amount),100);
await slider.focus(); await page.keyboard.press('Home'); assert.equal(await slider.inputValue(),'0');
await page.keyboard.press('End'); assert.equal(await slider.inputValue(),'100');
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-focus.png`});
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).uncheck();
assert(await slider.isDisabled());
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-slider-disabled.png`});
await page.getByRole('switch',{name:'Transparent surfaces',exact:true}).check();
await page.setViewportSize({width:360,height:740}); await slider.scrollIntoViewIfNeeded();
assert(await page.locator('.content').evaluate(node => node.scrollWidth <= node.clientWidth));
await page.screenshot({path:`.audit/host-ui/${theme}-${mode}-narrow.png`});
await page.setViewportSize({width:1100,height:800});
}
await page.evaluate(async () => {
const {installTheme} = await import('/src/lib/theme/customThemes.ts');
const {saveAppearance,exportAppearanceTheme} = await import('/src/lib/theme/appearance.ts');
const theme = exportAppearanceTheme('default'); theme.fonts = {ui:'Arial, sans-serif',prose:'Georgia, serif',heading:'Georgia, serif',mono:'Consolas, monospace'};
installTheme(theme); saveAppearance({theme:'custom:my-theme',mode:'dark'}); window.dispatchEvent(new Event('focus'));
});
assert.match(await page.locator('.preview-prose').evaluate(node => getComputedStyle(node).fontFamily),/Georgia/);
assert.match(await page.evaluate(async () => (await import('/src/lib/theme/appearance.ts')).exportAppearanceTheme('custom:my-theme').fonts.ui),/Arial/);
await page.screenshot({path:'.audit/host-ui/custom-fonts.png'});
const main = await context.newPage(); await main.goto(origin);
await main.bringToFront();
await main.getByRole('button',{name:'Files',exact:true}).waitFor();
await main.evaluate(async () => {
const loaded = performance.getEntriesByType('resource').map(entry => entry.name).find(name => new URL(name).pathname === '/src/lib/plugins/external.ts');
const {pluginTools,refreshPlugins} = await import(loaded || '/src/lib/plugins/external.ts');
await refreshPlugins();
const invoke = window.__TAURI_INTERNALS__.invoke;
window.__TAURI_INTERNALS__.invoke = (command,args) => command === 'plugins_snapshot' ? Promise.resolve(null) : invoke(command,args);
const commands = [{owner:'runestone.background-slideshow',id:'next-image',title:'Next background image',kind:'command',surface:'commands',icon:'skip-forward'},{owner:'runestone.background-slideshow',id:'pause-resume',title:'Pause or resume background slideshow',kind:'command',surface:'commands',icon:'pause'}];
pluginTools.set(commands);
});
for (const mode of ['dark','light']) {
await main.evaluate(async mode => (await import('/src/lib/theme/appearance.ts')).saveAppearance({theme:'default',mode}),mode);
const button = main.getByRole('button',{name:'Commands',exact:true});
assert.equal(await button.getAttribute('title'),null);
await button.hover(); await main.waitForTimeout(1100);
assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
await main.screenshot({path:`.audit/host-ui/${mode}-single-tooltip.png`});
await main.keyboard.press('Escape'); assert.equal(await main.locator('[role=tooltip]:visible').count(),0);
await main.mouse.move(400,400);
await button.evaluate(node => node.blur());
await button.focus(); await main.waitForTimeout(600); assert.equal(await main.locator('[role=tooltip]:visible').count(),1);
await button.click(); await main.getByRole('menu').waitFor();
const paths = await main.locator('.rs-menu svg').evaluateAll(nodes => nodes.map(node => node.innerHTML));
assert(paths.some(path => path.includes('M7 4v16'))); assert(paths.some(path => path.includes('m4 4 12 8')));
await main.screenshot({path:`.audit/host-ui/${mode}-slideshow-command-icons.png`}); await main.keyboard.press('Escape');
}
assert.deepEqual(errors,[]);
console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.');
} finally { await browser.close(); }
+75
View File
@@ -0,0 +1,75 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { catalogs, messageRows } from '../src/lib/i18n/messages.ts';
import { get } from 'svelte/store';
import { LANGUAGE_KEY, locale, normalizeLocale, setLocale, t, translate, syncLocale } from '../src/lib/i18n/index.ts';
test('Every catalog entry has all translations and preserves its placeholders', () => {
const seen = new Set<string>();
for (const [english, ...translations] of messageRows) {
assert(!seen.has(english), `Duplicate message: ${english}`); seen.add(english);
const placeholders = (value: string) => [...value.matchAll(/\{(\w+)\}/g)].map(match => match[1]).sort();
for (const value of translations) {
assert(value.trim(), `Empty translation: ${english}`);
assert.deepEqual(placeholders(value), placeholders(english), english);
}
}
assert.equal(Object.keys(catalogs.fr).length, messageRows.length);
});
test('Locale parsing rejects unsupported values and interpolation preserves user text', () => {
assert.equal(normalizeLocale('ja'), 'ja');
assert.equal(normalizeLocale('zh-CN'), 'zh-CN');
for (const value of [null, undefined, 'constructor', 'de', [], {}]) assert.equal(normalizeLocale(value), 'en');
assert.equal(translate('fr', 'Missing source text'), 'Missing source text');
assert.equal(translate('ja', 'Close {name}', { name: '<script>例.md</script>' }), '<script>例.md</script>を閉じる');
});
test('Language saves before reactive changes and syncs across windows', () => {
const stored = new Map<string, string>();
const events = new Map<string, Function>();
const priorStorage = globalThis.localStorage, priorWindow = globalThis.window, priorDocument = globalThis.document;
try {
globalThis.localStorage = { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => stored.set(key, value) } as Storage;
globalThis.window = { addEventListener: (key: string, handler: Function) => events.set(key, handler), removeEventListener: (key: string) => events.delete(key) } as unknown as Window & typeof globalThis;
globalThis.document = { documentElement: { lang: '' } } as unknown as Document;
const stop = syncLocale();
setLocale('fr');
assert.equal(stored.get(LANGUAGE_KEY), 'fr');
assert.equal(get(t)('Settings'), 'Paramètres');
assert.equal(document.documentElement.lang, 'fr');
stored.set(LANGUAGE_KEY, 'zh-CN'); events.get('storage')!({ key: LANGUAGE_KEY });
assert.equal(get(locale), 'zh-CN'); assert.equal(get(t)('Settings'), '设置');
globalThis.localStorage.setItem = () => { throw new Error('Storage unavailable'); };
assert.throws(() => setLocale('ja'));
assert.equal(get(locale), 'zh-CN');
stop(); assert.equal(events.size, 0);
} finally { globalThis.localStorage = priorStorage; globalThis.window = priorWindow; globalThis.document = priorDocument; locale.set('en'); }
});
import { readFileSync, readdirSync } from 'node:fs';
import path from 'node:path';
import ts from 'typescript';
function sourceFiles(dir: string): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory() ? sourceFiles(path.join(dir, entry.name)) : /\.(ts|svelte)$/.test(entry.name) ? [path.join(dir, entry.name)] : []);
}
test('Every static host translation call has all three catalog entries', () => {
const missing: string[] = [];
for (const file of sourceFiles('src/lib')) {
const source = readFileSync(file, 'utf8');
for (const match of source.matchAll(/(?:\$t|\btr)\(\s*((?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'))/g)) {
const parsed = ts.createSourceFile('literal.ts', match[1], ts.ScriptTarget.Latest, true);
const statement = parsed.statements[0];
const value = ts.isExpressionStatement(statement) && ts.isStringLiteral(statement.expression) ? statement.expression.text : '';
if (value && !Object.hasOwn(catalogs.fr, value)) missing.push(`${file}: ${value}`);
}
}
assert.deepEqual(missing, []);
});
test('Keyboard identifiers remain untranslated in event handlers', () => {
const failures: string[] = [];
for (const file of sourceFiles('src/lib')) {
const source = readFileSync(file, 'utf8');
for (const line of source.split(/\r?\n/)) {
if (/event\.(?:key|code)\s*[!=]==?\s*(?:tr|\$t)\(/.test(line) || /(?:tr|\$t)\([^\n]+\]\.(?:includes|indexOf)\(event\.(?:key|code)/.test(line)) failures.push(`${file}: ${line.trim()}`);
}
}
assert.deepEqual(failures, []);
});
+46 -1
View File
@@ -25,7 +25,10 @@ await page.addInitScript(() => {
if (command === "plugin:event|listen") { listeners.set(args.event, args.handler); return ++sequence; }
if (command === "plugin:event|unlisten") return;
if (command.startsWith("spelling_menu_")) { window.spellingTest.commands.push({ method: command, ...args }); return; }
if (command === "spelling_suggestions") return { language: "en-US", words: [], misspelled: false };
if (command === "spelling_suggestions") {
if (window.spellingTest.delay) return new Promise(resolve => window.spellingTest.resolve = resolve);
return { language: "en-US", words: [], misspelled: false };
}
if (command === "workspace_last_path") return root;
if (command === "workspace_open") return { root, name: "tab-menu-workspace", watch_mode: "native" };
if (command === "workspace_read") { if (!files.has(args.rel)) throw new Error("missing"); return files.get(args.rel); }
@@ -208,6 +211,37 @@ try {
await emitSpelling("new");
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "old", command: null });
await dismiss();
await page.evaluate(() => {
window.spellingTest.delay = true;
const input = document.querySelector('#native-spelling-test');
input.value = 'recieved'; input.focus(); input.setSelectionRange(3, 3);
input.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }));
window.spellingTest.emit({ request: 'delayed-spelling', fallback_spelling: true, items: [
{ id: 90, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] },
] });
});
await spelling.waitFor();
assert.equal(await item('Copy').count(), 1, 'Editing actions appear before the spelling service resolves');
await page.evaluate(() => { window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true }); window.spellingTest.delay = false; });
await item('received').waitFor();
await page.screenshot({ path: `.audit/menu-spelling-async-${theme}.png` });
await dismiss();
await page.evaluate(() => {
window.spellingTest.delay = true;
document.querySelector('#native-spelling-test').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true }));
window.spellingTest.emit({ request: 'dismissed-spelling', fallback_spelling: true, items: [
{ id: 91, name: 'copy', label: 'Copy', shortcut: '', kind: 0, enabled: true, checked: false, children: [] },
] });
});
await spelling.waitFor();
await dismiss();
await page.evaluate(async () => {
window.spellingTest.resolve({ language: 'en-US', words: ['received'], misspelled: true });
window.spellingTest.delay = false;
await new Promise(resolve => requestAnimationFrame(resolve));
});
assert.equal(await spelling.count(), 0, 'Late spelling results cannot reopen a dismissed menu');
await page.evaluate(() => { document.querySelector('#native-spelling-test').value = 'Original'; });
await page.locator("#native-spelling-test").evaluate(node => node.remove());
await page.evaluate(() => {
const input = document.createElement("input");
@@ -220,6 +254,17 @@ try {
assert.deepEqual(await page.evaluate(() => window.spellingTest.commands.at(-1)), { method: "spelling_menu_select", request: "ordinary-input", command: null, fallback: true });
}
await page.setViewportSize({ width: 420, height: 320 });
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const root = actionMenu(418, 318, [{ label: "Modifier toutes les occurrences dans le document", icon: "select", shortcut: "Ctrl+F2" }], () => root.remove(), "Long translated label");
});
const translated = menu("Long translated label");
assert(await translated.locator('.action-label').evaluate(node => {
const css = getComputedStyle(node);
return css.whiteSpace === 'normal' && css.textOverflow !== 'ellipsis' && node.scrollWidth <= node.clientWidth;
}), 'Long translated actions wrap without truncation');
await page.screenshot({ path: '.audit/menu-translated-long-label.png' });
await dismiss();
await page.evaluate(async () => {
const { actionMenu } = await import("/src/lib/ui/actionMenu.ts");
const root = actionMenu(418, 318, [
+1 -1
View File
@@ -3,7 +3,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('../', import.meta.url));
export const projects = ['RuneStone', 'RuneStone_ProjectManagement', 'RuneStone_Terminal', 'RuneStone_BG_Slideshow', 'RuneStone_LocalAutocomplete', 'RuneStone_Git', 'RuneStone_PDFViewer', 'RuneStone_TableFormulas', 'RuneStone_CSVViewer'];
export const projects = ['RuneStone', 'RuneStone_Project_Management', 'RuneStone_Terminal', 'RuneStone_Background_Slideshow', 'RuneStone_Local_Autocomplete', 'RuneStone_Git', 'RuneStone_PDF_Viewer', 'RuneStone_Table_Formulas', 'RuneStone_CSV_Viewer'];
const patterns = {
action: /\b(?:showActionMenu|actionMenu)\s*\(/g,
svelteMenu: /<ContextMenu\b/g,
+35
View File
@@ -0,0 +1,35 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { locale } from '../src/lib/i18n/index.ts';
import { pluginTranslation } from '../src/lib/plugins/translation.ts';
test('Plugin messages use the host language, explicit catalogs, and safe fallbacks', () => {
const api = pluginTranslation(() => {}, () => {});
try {
locale.set('fr');
assert.equal(api.locale, 'fr');
assert.equal(api.t('Settings'), 'Paramètres');
assert.equal(api.t('Column {name}', { name: '<b>User data</b>' }, { fr: { 'Column {name}': 'Colonne {name}' } }), 'Colonne <b>User data</b>');
assert.equal(api.t('Unknown {name}', { name: 'text' }), 'Unknown text');
assert.equal(api.t('constructor'), 'constructor');
assert.equal(api.t('Settings', {}, { fr: Object.create({ Settings: 'Inherited' }) }), 'Paramètres');
} finally { locale.set('en'); }
});
test('Plugin language subscriptions stop at disposal and reject access after disable', () => {
const cleanup: (() => void)[] = [], languages: string[] = [];
let stopped = false;
const api = pluginTranslation(() => { if (stopped) throw new Error('Disabled'); }, off => cleanup.push(off));
try {
api.subscribe(language => languages.push(language));
locale.set('ja');
assert.deepEqual(languages, ['en', 'ja']);
stopped = true;
for (const off of cleanup) off();
locale.set('zh-CN');
assert.deepEqual(languages, ['en', 'ja']);
assert.throws(() => api.locale, /Disabled/);
assert.throws(() => api.t('Settings'), /Disabled/);
assert.throws(() => api.subscribe(() => {}), /Disabled/);
} finally { locale.set('en'); }
});
+28 -2
View File
@@ -10,7 +10,7 @@ page.on("pageerror", err => errors.push(err.message));
await page.addInitScript(() => {
window.isTauri = true;
let current = "D:\\Notes";
let recent = [current, "D:\\Writing\\Notes", "D:\\Missing"];
let recent = ["D:\\Writing\\Notes", current, "D:\\Missing"];
let picked = null;
let contents = "Original note";
const calls = [];
@@ -22,6 +22,7 @@ await page.addInitScript(() => {
calls.push({ command, args });
if (command === "workspace_last_path") return current;
if (command === "workspace_recent") return recent;
if (command === "workspace_forget") { recent = recent.filter(path => path !== args.path); return recent; }
if (command === "workspace_list") return args.rel ? [] : [{ name: "note.txt", rel_path: "note.txt", kind: "file" }];
if (command === "workspace_read") { if (args.rel === "note.txt") return contents; throw "File not found"; }
if (command === "workspace_write") { contents = args.contents; return; }
@@ -49,7 +50,7 @@ await page.addInitScript(() => {
},
};
window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };
window.__TEST__ = { calls, windows, pick: path => picked = path, clear: () => recent = [] };
window.__TEST__ = { calls, windows, pick: path => picked = path, clear: () => recent = [], reorder: () => recent = ["D:\\Writing\\Notes", current, "D:\\Missing"] };
});
try {
await page.goto(process.env.SMOKE_URL || "http://127.0.0.1:1420");
@@ -64,8 +65,13 @@ try {
});
const trigger = page.getByRole("button", { name: "Open folder", exact: true });
const menu = page.getByRole("dialog", { name: "Workspaces", exact: true });
await page.evaluate(() => window.__TEST__.reorder());
await trigger.click();
await menu.getByText("D:\\Writing\\Notes", { exact: true }).waitFor();
await page.mouse.move(1000, 50);
assert.equal(await menu.locator('.workspace-row').first().evaluate(node => node === document.activeElement), false, "Pointer opening does not force focus onto a different workspace");
assert.equal(await menu.locator('.workspace-row').first().evaluate(node => getComputedStyle(node).backgroundColor), "rgba(0, 0, 0, 0)", "The first workspace has no stuck highlight");
assert.equal(await menu.locator('[aria-current="true"]').count(), 1);
assert.equal(await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "plugin:dialog|open").length), 0);
await page.screenshot({ path: ".audit/workspaces-menu.png" });
const opened = await page.evaluate(() => window.__TEST__.calls.filter(c => c.command === "workspace_open").length);
@@ -109,6 +115,26 @@ try {
assert.equal(await page.locator(":focus").textContent(), " Open another folder…");
await page.keyboard.press("Escape");
await menu.waitFor({ state: "hidden" });
for (const theme of ['light', 'dark']) {
await page.evaluate(async mode => {
const { applyAppearance } = await import('/src/lib/theme/appearance.ts');
applyAppearance({ theme: 'default', mode });
}, theme);
await page.setViewportSize({ width: theme === 'light' ? 1100 : 380, height: 800 });
await trigger.click();
await menu.getByRole('button', { name: 'Remove D:\\Missing from recent workspaces', exact: true }).focus();
await page.screenshot({ path: `.audit/workspaces-remove-${theme}.png` });
if (theme === 'dark') {
await page.keyboard.press('Enter');
await menu.getByText('D:\\Missing', { exact: true }).waitFor({ state: 'detached' });
assert.equal(await page.locator('.ws').textContent(), 'Notes', 'History removal does not close the current workspace');
await page.keyboard.press('Escape');
await trigger.click();
assert.equal(await menu.getByText('D:\\Missing', { exact: true }).count(), 0, 'Removed paths stay absent after reopening');
}
await page.keyboard.press('Escape');
}
await page.setViewportSize({ width: 1100, height: 800 });
await page.evaluate(() => window.__TEST__.clear());
await trigger.click();
await menu.getByText("No recent workspaces yet.").waitFor();