Make Background a native feature

- Background replaces the Background Slideshow plugin and the background image of Appearance. It shows a folder as a slideshow, or one image.
- It is on by default. Its module loads at launch only when a folder or an image is chosen.
- Rust keeps the one folder in background-folder.json. The interface never sends a path. Eight background_* commands replace the six deprecated backgrounds_* commands.
- The first start moves the slideshow folder and settings, and keeps the saved image as the image source.
- One blur worker with a cache, fewer folder reads, and a decode before each fade. The hub writes only the changed properties.
- Remove the deprecated folder methods of api.backgrounds. set, get, and subscribe stay for the Project Management plugin.
- Show the view buttons in the workbench test without text, after UI-056.
- Update the tests, the measurement tool, the docs, and UI-057.
This commit is contained in:
Knotty Wyvern
2026-10-29 17:25:17 -07:00
parent 115c32fa92
commit ab868bbe8e
81 changed files with 3179 additions and 812 deletions
+16 -1
View File
@@ -88,6 +88,18 @@ export async function chooseView(scope, name) {
return scope.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name, exact: true }).click();
}
/**
* Select the image source of Background, so that the saved image of `appearance.newTabBackground` shows
* (src/lib/features/backgroundSettings.ts). Call it after the test saves an image. It waits until the frame is on the body.
*/
export async function showSavedImage(page) {
await page.evaluate(async () => {
const { readBackground, writeBackground } = await import("/src/lib/features/backgroundSettings.ts");
await writeBackground({ ...readBackground(), source: "image" });
});
await page.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image").includes("blob:"));
}
/**
* Mock the Tauri IPC layer before the app loads. The mock handles the event plugin.
*
@@ -195,7 +207,7 @@ function installMock(options, commands) {
if (target !== pageId) channel.postMessage({ event, payload, target });
};
const SETTINGS_FILE = "runestone.smoke.settings-file", TRANSFERS = "runestone.smoke.tab-transfers";
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features"];
const SECTIONS = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background"];
const readJson = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key)) ?? fallback; } catch { return fallback; } };
const settingsFile = () => readJson(SETTINGS_FILE, null);
const snapshot = () => {
@@ -227,6 +239,9 @@ function installMock(options, commands) {
features_legacy: () => [],
// The editor asks for the Git line of the cursor while the Git feature is on. Tests of Git replace it.
git_blame: () => null,
// src-tauri/src/backgrounds.rs: the host has no background folder. Tests of the Background folder replace these.
background_folder: () => null,
background_migrate: () => null,
settings_migrate: ({ sections }) => {
if (!settingsFile()) localStorage.setItem(SETTINGS_FILE, JSON.stringify({ schema: 1, revision: 1, ...sections }));
return snapshot();
@@ -1,7 +1,8 @@
// Workarea backgrounds in both themes: splash, writer, reader, split, Source, narrow layouts, fades, reduced motion, and removal.
// The saved image shows through the Background feature (src/lib/features/background/). The test also sets its own frames.
import assert from 'node:assert/strict';
import { writeFile } from 'node:fs/promises';
import { chooseView, mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
import { chooseView, mockTauri, openPage, outputDir, runSmoke, showSavedImage, smokeUrl } from '../_harness/index.mjs';
const viewport = { width: 1280, height: 820 };
@@ -43,6 +44,7 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
const urls = [make('#bd486c', '#438f67'), make('#286f9b', '#725ea2')].map(url => URL.createObjectURL(blob(url)));
window.backgroundTest = { hub: backgroundHub, owner: Symbol(), urls, saved, theme };
}, theme);
await showSavedImage(page);
const background = page.locator('.workarea-background');
const style = (locator, property, pseudo) => locator.evaluate((node, [property, pseudo]) => getComputedStyle(node, pseudo)[property], [property, pseudo]);
async function openWelcome() {
@@ -120,12 +122,14 @@ await runSmoke('appearance/backgroundFrames', async ({ browser }) => {
await page.screenshot({ path: `${output}/${theme}-splash-narrow.png` });
await page.emulateMedia({ reducedMotion: 'reduce' });
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.set(owner, 'app', { url: urls[0], overlay: 0.2, position: 'center', size: 'cover', previous: { url: urls[1], overlay: 0.2, position: 'center', size: 'cover' }, transitionMs: 2000 }); });
assert.equal(await background.evaluate(node => node.getAnimations().length), 0);
assert.equal(await background.evaluate(node => node.getAnimations({ subtree: true }).length), 0);
await page.evaluate(() => { const { hub, owner, urls } = window.backgroundTest; hub.removeOwner(owner); urls.forEach(URL.revokeObjectURL); });
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), '');
// The frame of Background (the saved image) shows again, without a fade.
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-previous-image')), 'none');
assert.match(await style(background, 'backgroundImage'), /blob:/);
await page.evaluate(async () => { const { saveAppearance } = await import('/src/lib/theme/appearance.ts'); saveAppearance({ theme: 'default', mode: window.backgroundTest.theme }); });
assert.equal(await style(background, 'backgroundImage'), 'none');
await page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage === 'none');
assert.equal(await page.evaluate(() => document.body.style.getPropertyValue('--rs-background-image')), '', 'Without an image, the body has no background properties');
await openWelcome();
await page.locator('.editor > .body').waitFor();
assert.equal(await style(page.locator('.editor > .body'), 'backgroundColor'), await style(page.locator('.shell'), 'backgroundColor'));
@@ -4,7 +4,9 @@ import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/layout/Workbench.svelte:1258, 1543).
// The image is painted on .workarea-background, not on the empty tab (src/lib/theme/background.css).
// Background (src/lib/features/background/) loads after the first render, so each check waits for the image.
const waitForImage = page => page.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
await runSmoke('appearance/backgroundImages', async ({ browser }) => {
const output = await outputDir('appearance/backgroundImages');
@@ -50,7 +52,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).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();
await main.reload(); await main.locator('.empty').waitFor(); await waitForImage(main);
url = await background(); assert.equal(await decoded(main, url), 700, 'The saved image survives reload');
const pixel = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=', 'base64');
@@ -60,8 +62,7 @@ await runSmoke('appearance/backgroundImages', async ({ browser }) => {
await main.waitForFunction(old => /url\("(blob:[^"]+)"\)/.exec(getComputedStyle(document.querySelector('.workarea-background')).backgroundImage)?.[1] !== old, url);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image decodes');
assert.ok(await settings.evaluate(() => JSON.stringify(window.__TEST__.settings('appearance')).length < 500), 'Image bytes stay outside the settings file');
await main.reload(); await main.locator('.empty').waitFor();
await main.waitForFunction(() => getComputedStyle(document.querySelector('.workarea-background')).backgroundImage.includes('blob:'));
await main.reload(); await main.locator('.empty').waitFor(); await waitForImage(main);
url = await background(); assert.equal(await decoded(main, url), 1, '50 MiB image survives reload');
const acceptedId = await savedImageId();
@@ -4,7 +4,8 @@ import { writeFile } from 'node:fs/promises';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
// The image is painted on .workarea-background, not on the empty tab (src/lib/layout/Workbench.svelte:1258, 1543).
// The image is painted on .workarea-background, not on the empty tab (src/lib/theme/background.css).
// The controls are in Appearance → Background (src/lib/features/background/BackgroundSettings.svelte).
await runSmoke('appearance/backgroundLayout', async ({ browser }) => {
const output = await outputDir('appearance/backgroundLayout');
const context = await browser.newContext({ viewport: { width: 1100, height: 780 } });
@@ -1,4 +1,4 @@
// The empty tab background image: set it in Settings, keep it after a reload, remove it, and leave Reset background disabled.
// The empty tab background image: set it in Settings, keep it after a reload, and remove it. The source stays Image.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
@@ -24,13 +24,14 @@ await runSmoke(name, async ({ browser }) => {
await settings.goto(smokeUrl + "/?settingsWindow=true");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=", "base64");
// The image now lives on the work area layer behind the empty tab (src/lib/layout/Workbench.svelte:1258, :1543-1549).
// The image lives on the work area layer behind the empty tab (src/lib/theme/background.css).
const layer = ".workarea-background";
await settings.getByLabel("Background image file", { exact: true }).setInputFiles({ name: "test.png", mimeType: "image/png", buffer: png });
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage.includes("blob:"), layer);
assert.equal(await page.evaluate(() => window.__TEST__.settings("background").source), "image", "A chosen image selects the image source");
await page.reload();
await page.locator(".empty").waitFor();
assert.ok(await page.locator(layer).evaluate(node => getComputedStyle(node).backgroundImage.includes("blob:")), "Background survives restart");
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage.includes("blob:"), layer);
await settings.getByRole("button", { name: "Remove image", exact: true }).click();
await page.waitForFunction(layer => getComputedStyle(document.querySelector(layer)).backgroundImage === "none", layer);
for (const mode of ["light", "dark"]) {
@@ -42,8 +43,10 @@ await runSmoke(name, async ({ browser }) => {
await settings.setViewportSize({ width: 650, height: 760 });
await settings.screenshot({ path: path.join(output, `appearance-${mode}-narrow.png`) });
}
assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).isDisabled(), true);
assert.equal(await settings.getByRole("button", { name: "Reset background", exact: true }).count(), 0);
assert.equal(await settings.getByRole("button", { name: "Background source", exact: true }).innerText(), "Image");
assert.equal(await settings.getByRole("button", { name: "Choose image…", exact: true }).count(), 1);
await page.waitForFunction(() => !window.__TEST__.settings("appearance").newTabBackground);
assert.deepEqual([...page.errors, ...settings.errors], []);
console.log("PASS: background image applies, survives a reload, and is removed; Reset background is disabled");
console.log("PASS: background image applies, survives a reload, and is removed; the image source stays selected");
});
+12 -3
View File
@@ -1,4 +1,5 @@
// Theme variants: transparency slider in eight variants, custom theme fonts, a single tooltip, and slideshow command icons.
// Theme variants: transparency slider in eight variants, custom theme fonts, a single tooltip, plugin command icons,
// and the native Background commands in the command palette.
import assert from 'node:assert/strict';
import path from 'node:path';
import { mockTauri, openPage, outputDir, runSmoke, smokeUrl } from '../_harness/index.mjs';
@@ -53,13 +54,21 @@ await runSmoke('appearance/themeVariants', async ({ browser }) => {
const main = await openPage(context); await main.goto(smokeUrl);
await main.bringToFront();
await main.getByRole('button', { name: 'Files', exact: true }).waitFor();
// The commands of the native Background feature (src/lib/features/catalog.ts) are in the command palette, without the feature code.
await main.keyboard.press('Control+Shift+P');
const palette = main.getByRole('dialog', { name: 'Commands', exact: true });
await palette.getByRole('textbox', { name: 'Find a command', exact: true }).fill('background');
for (const title of ['Next background image', 'Pause background']) await palette.getByRole('button').filter({ hasText: title }).first().waitFor();
assert.equal(await main.evaluate(async () => (await import('/src/lib/features/loader.ts')).featureRequested('background')), false, 'The palette lists the commands without the feature code');
await main.keyboard.press('Escape');
// A third-party plugin with command icons. The Commands menu lists plugin commands only (src/lib/plugins/PluginAccessMenu.svelte).
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' }];
const commands = [{ owner: 'org.test.slideshow', id: 'next-image', title: 'Next test image', kind: 'command', surface: 'commands', icon: 'skip-forward' }, { owner: 'org.test.slideshow', id: 'pause-resume', title: 'Pause or resume test slideshow', kind: 'command', surface: 'commands', icon: 'pause' }];
pluginTools.set(commands);
});
const visibleTooltips = () => main.locator('[role=tooltip]:visible').count();
@@ -77,7 +86,7 @@ await runSmoke('appearance/themeVariants', async ({ browser }) => {
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: path.join(output, `${mode}-slideshow-command-icons.png`) }); await main.keyboard.press('Escape');
await main.screenshot({ path: path.join(output, `${mode}-plugin-command-icons.png`) }); await main.keyboard.press('Escape');
}
assert.deepEqual([...page.errors, ...main.errors], []);
console.log('PASS: eight theme variants, slider endpoints, persistence, disabled states, narrow layout, font import/export, single tooltip, and command icons.');
@@ -1,7 +1,7 @@
// Tab tooltips, translucent text selection, zero-transparency backgrounds, a stable transparency slider, and the themed install checkbox.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const output = await outputDir("appearance/tooltipsAndSelection");
@@ -35,6 +35,7 @@ await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const { saveAppearance } = await import("/src/lib/theme/appearance.ts");
saveAppearance({ theme: "default", mode, transparency: { enabled: true, amount: 0 }, newTabBackground: { image: "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=" } });
}, mode);
await showSavedImage(page);
const tab = page.getByRole("tab", { name: /welcome\.md/ });
assert.equal(await tab.getAttribute("title"), null);
await page.mouse.move(600, 600);
@@ -50,9 +51,10 @@ await runSmoke("appearance/tooltipsAndSelection", async ({ page }) => {
const writer = page.getByRole("textbox", { name: "Writing editor", exact: true });
await writer.click(); await page.keyboard.press("Control+a");
const colors = await writer.evaluate(node => {
const root = getComputedStyle(document.documentElement);
const root = getComputedStyle(document.documentElement), body = getComputedStyle(document.body);
// Background sets the image and the surfaces on the body (src/lib/plugins/backgrounds.ts).
return { selection: root.getPropertyValue("--rs-selection"), bg: getComputedStyle(node, "::selection").backgroundColor,
text: getComputedStyle(node).color, image: root.getPropertyValue("--rs-new-tab-image"), pluginBg: root.getPropertyValue("--rs-workarea-plugin-bg") };
text: getComputedStyle(node).color, image: body.getPropertyValue("--rs-background-image"), pluginBg: body.getPropertyValue("--rs-workarea-plugin-bg") };
});
assert.match(colors.selection.trim(), /^#[0-9a-f]{6}a6$/i);
assert.match(colors.bg, /0\.65/);
+2 -1
View File
@@ -1,6 +1,6 @@
// Editor menu surfaces: Writer, spelling, Source, and code menus share the file menu styles; and the code tint match in both themes.
import assert from "node:assert/strict";
import { chooseView, mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { chooseView, mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("editor/surfaces", async ({ page }) => {
await mockTauri(page, {
@@ -42,6 +42,7 @@ await runSmoke("editor/surfaces", async ({ page }) => {
c.fillStyle = g; c.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: .15, position: 'center', size: 'cover' } });
}, theme);
await showSavedImage(page);
await page.locator('[data-tree-rel="a.md"]').click({ button: 'right' });
const reference = await styles(menu('File actions'));
await dismiss();
+212
View File
@@ -0,0 +1,212 @@
// The native Background feature (src/lib/features/background/): a folder slideshow with mocked host commands, a fade,
// reduced motion, Next and Pause from the command palette, the targets, menus at 92% with an image and opaque with
// Background off, a browser window, the settings section in both themes and at 360 pixels, the image source,
// and the first-start migration from seeded plugin settings and from a seeded image.
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import path from "node:path";
import { mockTauri, openPage, outputDir, repoRoot, runSmoke, smokeUrl } from "../_harness/index.mjs";
const SETTINGS_FILE = "runestone.smoke.settings-file";
const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jM1sAAAAASUVORK5CYII=";
/**
* The host commands of the image folder (src-tauri/src/backgrounds.rs). Each image is a PNG of one color.
* The mock runs this function in the page, so it uses only `test`. `test.state.legacy` is an old plugin package.
*/
function folderCommands(test) {
const snapshot = { profiles: [{ id: "user", name: "User" }], tabs: [], bookmarks: [], settings: { search: "duckduckgo", adblock: true, linkDestination: "internal", personalRules: "", homepage: "", filterLists: [] } };
return {
...test.workspace({ root: "C:\\background-feature", files: { "note.md": "# Note\n\nText." } }),
plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }),
"plugin:window|is_maximized": () => false,
spelling_menu_install: () => null,
spelling_menu_uninstall: () => null,
background_folder: () => test.state.folder,
background_choose_folder: () => test.state.folder,
background_clear_folder: () => { test.state.folder = null; return null; },
background_list: () => test.state.names,
background_read: async ({ name }) => {
const [width, height] = name.startsWith("portrait") ? [300, 600] : [640, 400];
const canvas = new OffscreenCanvas(width, height);
const context = canvas.getContext("2d");
context.fillStyle = test.state.colors[name] ?? "#808080"; context.fillRect(0, 0, width, height);
return (await canvas.convertToBlob({ type: "image/png" })).arrayBuffer();
},
background_read_sidecar: () => test.state.sidecar,
background_write_sidecar: ({ contents, expected }) => {
if (expected !== test.state.sidecar) throw "The sidecar file changed. Read it again before you save.";
test.state.sidecar = contents;
return null;
},
background_migrate: () => test.state.folder,
features_legacy: ({ ids }) => test.state.legacy ? ids.filter(id => id === test.state.legacy.id).map(() => test.state.legacy) : [],
browser_connect: () => "background-session",
browser_stop: () => null,
browser_request: () => structuredClone(snapshot),
};
}
const folderState = { folder: "D:\\Backgrounds", names: ["a.png", "b.png", "portrait.png"], colors: { "a.png": "#3a6ea5", "b.png": "#a5533a", "portrait.png": "#4f8a4b" }, sidecar: null };
const image = page => page.evaluate(() => document.body.style.getPropertyValue("--rs-background-image"));
const waitForChange = (page, old) => page.waitForFunction(old => { const value = document.body.style.getPropertyValue("--rs-background-image"); return value.includes("blob:") && value !== old; }, old, { timeout: 15000 });
async function command(page, title) {
await page.keyboard.press("Control+Shift+P");
const palette = page.getByRole("dialog", { name: "Commands", exact: true });
await palette.getByRole("textbox", { name: "Find a command", exact: true }).fill(title);
await palette.getByRole("button").filter({ hasText: title }).first().waitFor();
await page.keyboard.press("Enter");
}
async function menuBackground(page) {
await page.locator('[data-tree-rel="note.md"]').click({ button: "right" });
const menu = page.getByRole("menu", { name: "File actions", exact: true });
await menu.waitFor();
const color = await menu.evaluate(node => getComputedStyle(node).backgroundColor);
await page.keyboard.press("Escape");
return color;
}
await runSmoke("features/background", async ({ browser }) => {
const output = await outputDir("features/background");
// A folder slideshow of 2 seconds, from a settings file that exists before the start.
const context = await browser.newContext({ viewport: { width: 1200, height: 820 } });
await mockTauri(context, { state: folderState, commands: folderCommands });
await context.addInitScript(([key, file]) => { if (!localStorage.getItem(key)) localStorage.setItem(key, JSON.stringify(file)); }, [SETTINGS_FILE, {
schema: 1, revision: 1, features: { git: true, background: true },
background: { source: "folder", seconds: 2, order: "name", paused: false, targets: ["app"], overlay: 0.1, position: "center", size: "cover" },
}]);
const main = await openPage(context);
await main.goto(smokeUrl);
await main.locator('[data-tree-rel="note.md"]').waitFor();
await waitForChange(main, "");
const first = await image(main);
assert.match(first, /rgba\(0,0,0,0\.1\)/, "The folder overlay applies");
// The timer shows the next image with a fade of 2 seconds.
await waitForChange(main, first);
assert.equal(await main.locator(".workarea-background").evaluate(node => node.getAnimations({ subtree: true }).length), 1, "The image fades in");
assert.notEqual(await main.evaluate(() => document.body.style.getPropertyValue("--rs-background-previous-image")), "none");
await main.screenshot({ path: path.join(output, "folder-fade.png") });
// Pause keeps the image. Next still works. The same command resumes.
await command(main, "Pause background");
await main.waitForFunction(() => window.__TEST__.settings("background").paused === true);
const paused = await image(main);
await main.waitForTimeout(3000);
assert.equal(await image(main), paused, "A paused slideshow keeps its image");
await command(main, "Next background image");
await waitForChange(main, paused);
// The folder has a portrait image after b.png. It shows in full over a blurred fill.
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-layer-sizes") === "100% 100%, contain, cover", null, { timeout: 15000 });
await main.screenshot({ path: path.join(output, "portrait.png") });
await command(main, "Pause background");
await main.waitForFunction(() => window.__TEST__.settings("background").paused === false);
// Reduced motion: the next image shows without a fade.
await main.emulateMedia({ reducedMotion: "reduce" });
const before = await image(main);
await command(main, "Next background image");
await waitForChange(main, before);
assert.equal(await main.locator(".workarea-background").evaluate(node => node.getAnimations({ subtree: true }).length), 0, "Reduced motion has no fade");
await main.emulateMedia({ reducedMotion: "no-preference" });
// With an image, menus are at least 92% opaque and blur it (UI-043).
assert.match(await menuBackground(main), /0\.92/);
// Targets: only the boards removes the workspace frame. The frame of all boards stays for Project Management.
await main.evaluate(() => window.__TEST__.writeSettings("background", { ...window.__TEST__.settings("background"), targets: ["pm-all"] }));
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image") === "");
assert.equal(await main.evaluate(async () => !!(await import("/src/lib/plugins/backgrounds.ts")).backgroundHub.get("pm-all")), true);
assert.match(await menuBackground(main), /^rgb\(/, "Without a workspace image, menus are opaque");
await main.evaluate(() => window.__TEST__.writeSettings("background", { ...window.__TEST__.settings("background"), targets: ["app"] }));
await waitForChange(main, "");
// A browser window shows the background behind a blank tab, and calls only the commands that browser.json grants.
const browserPage = await openPage(context);
await mockTauri(browserPage, { label: "browser-background", state: folderState, commands: folderCommands });
await browserPage.goto(smokeUrl + "/?browserWindow=true");
await browserPage.getByRole("application", { name: "RuneStone browser" }).waitFor();
assert.equal(await browserPage.evaluate(() => window.__TEST__.label), "browser-background");
await browserPage.waitForFunction(() => getComputedStyle(document.querySelector(".workarea-background")).backgroundImage.includes("blob:"), null, { timeout: 15000 });
await browserPage.screenshot({ path: path.join(output, "browser-window.png") });
const granted = new Set(JSON.parse(await readFile(path.join(repoRoot, "src-tauri/capabilities/browser.json"), "utf8")).permissions);
const calls = await browserPage.evaluate(() => [...new Set(window.__TEST__.calls.map(call => call.command))]);
for (const call of calls.filter(name => name.startsWith("background_"))) assert(granted.has(`allow-${call.replaceAll("_", "-")}`), `browser.json grants ${call}`);
assert(calls.includes("background_read"), "The browser window reads the folder images");
await browserPage.close();
// The settings section in both themes and at 360 pixels.
const settings = await openPage(context);
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
const section = settings.locator(".background-settings");
await section.waitFor();
assert.equal(await settings.getByRole("button", { name: "Background source", exact: true }).innerText(), "Folder");
assert.equal(await settings.getByRole("textbox", { name: "Image folder", exact: true }).inputValue(), "D:\\Backgrounds");
await settings.getByRole("status").filter({ hasText: "3 images." }).waitFor();
assert.equal(await settings.evaluate(async () => (await import("/src/lib/features/loader.ts")).featureRequested("background")), true, "The section loads the feature module");
assert.equal(await settings.evaluate(() => document.body.style.getPropertyValue("--rs-background-image")), "", "The slideshow does not run in the settings window");
await settings.locator("summary").filter({ hasText: "Per-image appearance" }).click();
await settings.getByRole("button", { name: "Image fit", exact: true }).waitFor();
await settings.waitForFunction(() => !document.querySelector('button[aria-label="Image fit"]').disabled);
for (const theme of ["dark", "light"]) {
await settings.evaluate(async mode => { const { saveAppearance, readAppearance } = await import("/src/lib/theme/appearance.ts"); saveAppearance({ ...readAppearance(), theme: "default", mode }); }, theme);
for (const width of [1100, 360]) {
// A tall window shows the whole section, also the targets below the per-image editor.
await settings.setViewportSize({ width, height: 1800 });
await section.scrollIntoViewIfNeeded();
assert.equal(await settings.locator(".content").evaluate(node => node.scrollWidth <= node.clientWidth + 1), true, `No horizontal scroll at ${width} pixels`);
await section.screenshot({ path: path.join(output, `settings-${theme}-${width}.png`) });
}
}
await settings.setViewportSize({ width: 1100, height: 900 });
// The per-image editor saves only the changed values of the selected image.
await settings.getByRole("button", { name: "Image fit", exact: true }).click();
await settings.getByRole("menuitemradio", { name: "Fit", exact: true }).click();
await settings.getByRole("button", { name: "Save image appearance", exact: true }).click();
await settings.getByRole("status").filter({ hasText: "Image appearance saved." }).waitFor();
assert.deepEqual(JSON.parse(await settings.evaluate(() => window.__TEST__.state.sidecar)), { schema: 1, images: { "a.png": { fit: "contain" } } });
// Off applies at once in every window: the image goes away, and menus are opaque again.
await settings.getByRole("button", { name: "Features", exact: true }).click();
await settings.getByRole("switch", { name: "Background", exact: true }).click();
await main.waitForFunction(() => document.body.style.getPropertyValue("--rs-background-image") === "");
assert.match(await menuBackground(main), /^rgb\(/, "With Background off, menus are opaque");
await settings.getByRole("button", { name: "Appearance", exact: true }).click();
await settings.getByText("Background is off. Turn it on in Settings → Features.", { exact: true }).waitFor();
await settings.screenshot({ path: path.join(output, "settings-off.png") });
await settings.getByRole("button", { name: "Features", exact: true }).click();
await settings.getByRole("switch", { name: "Background", exact: true }).click();
await waitForChange(main, "");
assert.deepEqual([...main.errors, ...settings.errors], []);
await context.close();
// The image source and the migration from a seeded image: the old image of Appearance shows without a timer.
const imageContext = await browser.newContext({ viewport: { width: 1000, height: 700 } });
await mockTauri(imageContext, { commands: test => ({ ...test.workspace({ root: "C:\\background-image", files: { "note.md": "# Note" } }), plugins_snapshot: () => ({ root: "C:/plugins", plugins: [] }) }) });
await imageContext.addInitScript(image => { if (!localStorage.getItem("runestone.smoke.settings-file")) localStorage.setItem("runestone.appearance", JSON.stringify({ theme: "default", mode: "dark", newTabBackground: { image, overlay: 0.2, position: "top", size: "contain" } })); }, `data:image/png;base64,${PNG}`);
const imagePage = await openPage(imageContext);
await imagePage.goto(smokeUrl);
await waitForChange(imagePage, "");
assert.deepEqual(await imagePage.evaluate(() => window.__TEST__.settings("background")), { source: "image", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover" });
assert.equal(await imagePage.evaluate(() => document.body.style.getPropertyValue("--rs-background-position")), "top", "The image keeps its own layout");
assert.equal(await imagePage.evaluate(() => window.__TEST__.calls.some(call => call.command === "background_migrate")), false, "Without a plugin grant, no folder migrates");
assert.deepEqual(imagePage.errors, []);
await imageContext.close();
// The migration from the kept settings of an enabled Background Slideshow plugin.
const migrationContext = await browser.newContext({ viewport: { width: 1000, height: 700 } });
const legacy = { id: "runestone.bg-slideshow", installed: true, enabled: true,
settings: { grant: "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90", folder: "D:\\Old", enabled: true, seconds: 7, order: "random", targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" } };
await mockTauri(migrationContext, { state: { ...folderState, folder: "D:\\Old", legacy }, commands: folderCommands });
const migrated = await openPage(migrationContext);
await migrated.goto(smokeUrl);
await waitForChange(migrated, "");
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("background")), { source: "folder", seconds: 7, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.3, position: "top", size: "contain" });
assert.deepEqual(await migrated.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true });
assert.equal(await migrated.evaluate(() => window.__TEST__.calls.filter(call => call.command === "background_migrate").length), 1);
assert.deepEqual(migrated.errors, []);
await migrationContext.close();
console.log("PASS: folder slideshow, fade, pause and next, portrait fill, reduced motion, menus, targets, browser window, settings section, off switch, image source, and migrations.");
});
+2 -2
View File
@@ -20,7 +20,7 @@ await runSmoke("features/settings", async ({ browser }) => {
const sourceControl = main.locator(".header-left").getByRole("button", { name: "Source control", exact: true });
await sourceControl.waitFor();
// Without an old package, the migration stores the default of each feature.
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: true, background: true });
const settings = await openPage(context, { timeout: 10000 });
await settings.goto(`${smokeUrl}/?settingsWindow=true`);
@@ -33,7 +33,7 @@ await runSmoke("features/settings", async ({ browser }) => {
await git.click();
await sourceControl.waitFor({ state: "detached" });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false });
assert.deepEqual(await main.evaluate(() => window.__TEST__.settings("features")), { git: false, background: true });
assert.equal(await settings.getByRole("status").innerText(), "Changes saved.");
await git.focus();
await settings.keyboard.press("Space");
+2 -2
View File
@@ -137,10 +137,10 @@ await runSmoke("layout/workbench", async ({ page }) => {
window.__TEST__.emit("workspace-event", { root: window.__TEST__.root, kind: "create", paths: ["reader-showcase.md"] });
}, showcase);
await quickOpen("reader-showcase.md");
// Each view choice shows an icon and its name. The tooltip adds the shortcut (src/lib/layout/ViewModes.svelte).
// Each view choice shows only an icon (UI-056). The accessible name and the tooltip give its name and shortcut (src/lib/layout/ViewModes.svelte).
const read = page.getByRole("radiogroup", { name: "View", exact: true }).getByRole("radio", { name: "Read", exact: true });
const readTip = page.getByRole("tooltip").filter({ hasText: "Read (Ctrl+Shift+E)" });
assert.equal(await read.innerText(), "Read");
assert.equal(await read.innerText(), "");
assert.equal(await read.locator("svg").count(), 1);
await read.hover();
await readTip.waitFor({ state: "visible" });
+2 -1
View File
@@ -1,7 +1,7 @@
// Shared menu design: styles, themes, icons, disabled rows, focus return, submenus, spelling menus, scrolling, and viewport edges.
import assert from "node:assert/strict";
import path from "node:path";
import { mockTauri, outputDir, runSmoke, smokeUrl } from "../_harness/index.mjs";
import { mockTauri, outputDir, runSmoke, showSavedImage, smokeUrl } from "../_harness/index.mjs";
await runSmoke("menus/consistency", async ({ page }) => {
const output = await outputDir("menus/consistency");
@@ -69,6 +69,7 @@ await runSmoke("menus/consistency", async ({ page }) => {
context.fillStyle = gradient; context.fillRect(0, 0, 800, 600);
saveAppearance({ theme: 'default', mode, newTabBackground: { image: canvas.toDataURL(), overlay: 0.15, position: 'center', size: 'cover' } });
}, theme);
await showSavedImage(page);
await row.focus();
await row.click({ button: "right" });
const file = menu("File actions");
+456
View File
@@ -0,0 +1,456 @@
// The Background feature: the engine (ported from the Background Slideshow plugin), the per-image settings,
// the sources, the settings section, the launch rule, and the first-start migration.
import { test } from "node:test";
import assert from "node:assert/strict";
import { DEFAULT_BACKGROUND, hasBackgroundSource, migrateBackground, normalizeBackground, normalizeLayout, type BackgroundMigrationHost, type BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../../../src/lib/features/launch.ts";
import { BLUR_CACHE, RESCAN_SLIDES, Slideshow, transitionMs, type EngineSettings, type ImageSource, type Runtime } from "../../../src/lib/features/background/engine.ts";
import { imageAppearance, imageNames, parseImageSettings, sequence } from "../../../src/lib/features/background/imageSettings.ts";
import { folderSource, imageSource, readSavedImage } from "../../../src/lib/features/background/sources.ts";
import type { LegacyPlugin } from "../../../src/lib/features/migration.ts";
import type { BackgroundFrame } from "../../../src/lib/plugins/backgroundContracts.ts";
const settle = () => new Promise(resolve => setImmediate(resolve));
const on: EngineSettings = { ...normalizeBackground({ source: "folder", seconds: 3, targets: ["app", "pm-all"] }) };
function fixture({ width = 200, height = 100 } = {}) {
const frames = new Map<string, BackgroundFrame>();
const released: string[] = [];
const reads: string[] = [];
const counts = { list: 0, sidecar: 0, blur: 0 };
let names = ["2.png", "1.png", "10.png"];
let sidecar: string | null = null;
let serial = 0;
let scheduled: { callback: () => void; delay: number } | undefined;
const source = (key = "folder:D:\\Pictures"): ImageSource => ({
key, timed: true,
list: async () => { counts.list++; return names; },
read: async name => { reads.push(name); return new Blob([name]); },
sidecar: async () => { counts.sidecar++; return sidecar; },
});
const runtime: Runtime = {
load: async blob => ({ url: `blob:${await blob.text()}-${serial++}`, width, height }),
blur: async image => { counts.blur++; return `${image.url}-blur`; },
release: url => { released.push(url); },
later: (callback, delay) => { scheduled = { callback, delay }; return scheduled; },
cancel: () => { scheduled = undefined; },
random: () => 0,
now: () => 0,
};
const engine = new Slideshow({ set: (target, frame) => { if (frame) frames.set(target, frame); else frames.delete(target); } }, runtime);
return {
engine, frames, released, reads, counts, runtime, source,
names: (value: string[]) => { names = value; },
sidecar: (value: string | null) => { sidecar = value; },
scheduled: () => scheduled,
/** Run the timer, then let the read of the next prepared image finish. */
tick: async () => { await scheduled!.callback(); await settle(); await settle(); },
};
}
test("settings and names normalize, and the order is natural", () => {
assert.equal(normalizeBackground({ seconds: NaN }).seconds, 60);
assert.equal(normalizeBackground({ seconds: -2 }).seconds, 1);
assert.equal(normalizeBackground({ seconds: 1e9 }).seconds, 86400);
assert.equal(normalizeBackground({ overlay: Infinity }).overlay, 0);
assert.equal(normalizeBackground({ overlay: -3 }).overlay, -1);
assert.deepEqual(normalizeBackground({ targets: ["app", "app", "bogus", "pm-board:../x", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"] }).targets, ["app", "pm-board:0c18bcdc-f41e-4a31-87f4-87c369f398c1"]);
assert.deepEqual(normalizeBackground(null), { ...DEFAULT_BACKGROUND, targets: ["app"] });
assert.deepEqual(normalizeBackground({ source: "web", order: "shuffle", paused: "yes", position: "middle", size: "100px" }), { ...DEFAULT_BACKGROUND, targets: ["app"] });
assert.deepEqual(normalizeLayout({ overlay: 0.5, position: "top left", size: "auto" }), { overlay: 0.5, position: "top left", size: "auto" });
assert.deepEqual(imageNames(["10.png", "2.png", "README.md", "../bad.png", "2.png", "a.JPEG"]), ["2.png", "10.png", "a.JPEG"]);
assert.deepEqual(sequence(["a", "b", "c"], "b", "name"), ["c", "a", "b"]);
assert.notEqual(sequence(["a", "b", "c"], "a", "random", () => 0)[0], "a");
assert.deepEqual(sequence(["a"], "a", "random"), ["a"]);
});
test("a folder rotates, shows one frame on every target, and a pause keeps the current image", async () => {
const f = fixture();
await f.engine.configure(f.source(), { ...on, overlay: -0.4, position: "top left", size: "contain" });
assert.equal(f.engine.status.image, "1.png");
assert.equal(f.scheduled()!.delay, 3000);
assert.equal(f.frames.get("app")!.overlay, -0.4);
assert.equal(f.frames.get("app")!.size, "contain");
assert.deepEqual(f.frames.get("app"), f.frames.get("pm-all"));
await f.tick();
assert.equal(f.engine.status.image, "2.png");
await f.engine.next();
assert.equal(f.engine.status.image, "10.png");
await f.engine.configure(f.source(), { ...on, paused: true });
assert.equal(f.engine.status.image, "10.png", "A pause keeps the image.");
assert.equal(f.scheduled(), undefined, "A pause has no timer.");
assert.equal(f.frames.size, 2);
await f.engine.next();
assert.equal(f.engine.status.image, "1.png", "Next works during a pause.");
assert.equal(f.scheduled(), undefined);
await f.engine.configure(null, on);
assert.equal(f.frames.size, 0, "Without a source, the frames go away.");
f.engine.dispose();
});
test("unreadable images are skipped, and an empty folder tries again", async () => {
const f = fixture();
const read = f.source();
const source: ImageSource = { ...read, read: async name => { if (name === "1.png") throw new Error("removed"); return read.read(name); } };
await f.engine.configure(source, on);
assert.equal(f.engine.status.image, "2.png");
assert.match(f.engine.status.message, /skipped 1/);
f.names([]);
f.engine.invalidate();
await f.engine.next();
assert.equal(f.frames.size, 0);
assert.equal(f.engine.status.error, true);
assert.equal(f.scheduled()!.delay, 5000);
f.names(["restored.png"]);
f.engine.invalidate();
await f.tick();
assert.equal(f.engine.status.image, "restored.png");
f.engine.dispose();
});
test("both images of a fade stay alive, and each image is released once", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
assert.equal(first.previous, undefined);
await f.engine.next(); await settle();
const second = f.frames.get("app")!;
assert.deepEqual(second.previous, first);
assert.equal(second.transitionMs, transitionMs);
assert.equal(f.released.length, 0);
await f.engine.next(); await settle();
const third = f.frames.get("app")!;
assert.deepEqual(third.previous, { url: second.url, overlay: 0, position: "center", size: "cover" });
assert.deepEqual(f.released, [first.url]);
f.engine.dispose();
await settle();
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
for (const url of [first.url, second.url, third.url]) assert.ok(f.released.includes(url), url);
});
test("a settings change keeps the current image and applies the new layout without a fade", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
await f.engine.configure(f.source(), { ...on, overlay: 0.4, position: "bottom", targets: ["app"] });
const changed = f.frames.get("app")!;
assert.equal(changed.url, first.url);
assert.equal(changed.overlay, 0.4);
assert.equal(changed.position, "bottom");
assert.equal(changed.previous, undefined);
assert.equal(f.frames.has("pm-all"), false, "A removed target loses its frame.");
assert.equal(f.engine.status.image, "1.png");
assert.deepEqual(f.released, []);
f.engine.dispose();
});
test("the next image is read and decoded before its fade", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
await settle(); await settle();
assert.deepEqual(f.reads, ["1.png", "2.png"], "The next image loads after the current one shows.");
await f.tick();
assert.equal(f.engine.status.image, "2.png");
assert.deepEqual(f.reads, ["1.png", "2.png", "10.png"], "The timer used the prepared image without a new read.");
// A change of order drops the prepared image when the folder no longer has it.
f.names(["1.png", "2.png"]);
f.engine.invalidate();
await f.tick();
assert.equal(f.engine.status.image, "1.png");
assert.ok(f.released.some(url => url.startsWith("blob:10.png")), "The unused prepared image is released.");
f.engine.dispose();
});
test("a missing folder shows an error, and the folder recovers on the next try", async () => {
const f = fixture();
const missing: ImageSource = { ...f.source(), list: async () => { throw new Error("The background folder is missing. Choose the folder again."); } };
await f.engine.configure(missing, on);
assert.equal(f.engine.status.error, true);
assert.match(f.engine.status.message, /Choose the folder again/);
assert.equal(f.frames.size, 0);
await f.engine.configure(f.source("folder:D:\\Other"), on);
assert.equal(f.engine.status.error, false);
assert.equal(f.engine.status.image, "1.png");
f.engine.dispose();
});
test("a host failure clears the published targets and releases every image", async () => {
const f = fixture();
let fail = false;
const engine = new Slideshow({ set: (target, frame) => {
if (fail && target === "pm-all" && frame) throw new Error("Background access ended.");
if (frame) f.frames.set(target, frame); else f.frames.delete(target);
} }, f.runtime);
await engine.configure(f.source(), on);
await engine.next(); await settle();
fail = true;
await engine.next(); await settle();
assert.equal(engine.status.error, true);
assert.equal(f.frames.size, 0);
assert.equal(new Set(f.released).size, f.released.length, "No URL is released twice.");
assert.ok(f.released.length >= 3);
engine.dispose();
});
test("another source starts again, and a late read of the old source is ignored", async () => {
const f = fixture();
let resolve!: (value: string[]) => void;
const slow: ImageSource = { ...f.source("folder:D:\\Slow"), list: () => new Promise(done => { resolve = done; }) };
const pending = f.engine.configure(slow, on);
await settle();
await f.engine.configure(f.source("folder:D:\\Other"), on);
const current = f.frames.get("app")!.url;
resolve(["stale.png"]);
await pending;
assert.equal(f.frames.get("app")!.url, current);
assert.equal(f.engine.status.image, "1.png");
f.engine.dispose();
});
test("the list and the sidecar are read again only after a change, a focus, or every 10 images", async () => {
const f = fixture();
await f.engine.configure(f.source(), { ...on, seconds: 1 });
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1]);
for (let index = 1; index < RESCAN_SLIDES; index++) await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [1, 1], "Nine timer images read nothing again.");
await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [2, 2], "The eleventh image reads the folder again.");
f.engine.invalidate();
await f.tick();
assert.deepEqual([f.counts.list, f.counts.sidecar], [3, 3], "A focus reads it again.");
await f.engine.configure(f.source(), { ...on, seconds: 2 });
assert.deepEqual([f.counts.list, f.counts.sidecar], [4, 4], "A settings change reads it again.");
f.engine.dispose();
});
test("a late image after disposal is released and never published", async () => {
const f = fixture();
let resolve!: (value: { url: string; width: number; height: number }) => void;
f.runtime.load = () => new Promise(done => { resolve = done; });
const pending = f.engine.configure(f.source(), on);
await settle(); await settle();
f.engine.dispose();
resolve({ url: "blob:late", width: 1, height: 1 });
await pending;
assert.deepEqual(f.released, ["blob:late"]);
assert.equal(f.frames.size, 0);
assert.equal(f.scheduled(), undefined);
});
test("disposal clears the targets and stops the timer", async () => {
const f = fixture();
await f.engine.configure(f.source(), on);
const timer = f.scheduled()!;
f.engine.dispose();
timer.callback();
await settle();
assert.equal(f.frames.size, 0);
assert.equal(f.scheduled(), undefined);
});
test("the image source shows one image without a timer and without the portrait default", async () => {
const f = fixture({ width: 100, height: 300 });
const image: ImageSource = { key: "image:abc", timed: false, list: async () => ["image"], read: async () => new Blob(["saved"]), sidecar: async () => { throw new Error("not asked"); } };
await f.engine.configure(image, { ...on, size: "cover" });
assert.equal(f.frames.get("app")!.size, "cover");
assert.equal(f.frames.get("app")!.blurredUrl, undefined);
assert.equal(f.scheduled(), undefined);
await f.engine.next();
assert.equal(f.frames.get("app")!.previous, undefined, "Next keeps the one image.");
assert.equal(f.counts.blur, 0);
f.engine.dispose();
});
test("the sidecar keeps file names and other data, and rejects invalid appearance", () => {
const value = { schema: 1, owner: "personal", images: { "Portrait.png": { fit: "blurred", position: "top", overlay: -0.25 } } };
assert.deepEqual(parseImageSettings(JSON.stringify(value)), value);
assert.deepEqual(parseImageSettings(null), { schema: 1, images: {} });
for (const source of ["{}", '{"schema":2,"images":{}}', '{"schema":1,"images":[]}', '{"schema":1,"images":{"../a.png":{"fit":"cover"}}}', '{"schema":1,"images":{"a.png":{"fit":"crop"}}}', '{"schema":1,"images":{"a.png":{"overlay":2}}}']) {
assert.throws(() => parseImageSettings(source), source);
}
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
assert.equal(imageAppearance(layout, undefined, true).fit, "blurred");
assert.equal(imageAppearance(layout, undefined, false).fit, "auto");
assert.equal(imageAppearance(layout, { fit: "cover", position: "bottom", overlay: -0.2 }, true).fit, "cover");
});
test("a partial image override inherits every other field", () => {
const source = { schema: 1, owner: "personal", images: { "Portrait.png": { position: "top", note: "keep" }, "Other.png": {} } };
assert.deepEqual(parseImageSettings(JSON.stringify(source)), source);
const layout = { overlay: 0.3, position: "center" as const, size: "auto" as const };
assert.deepEqual(imageAppearance(layout, { position: "top" }, false), { fit: "auto", position: "top", overlay: 0.3 });
assert.deepEqual(imageAppearance({ ...layout, size: "contain", overlay: -0.4 }, { position: "top" }, false), { fit: "contain", position: "top", overlay: -0.4 });
assert.deepEqual(imageAppearance(layout, { overlay: 0 }, true), { fit: "blurred", position: "center", overlay: 0 });
for (const value of [null, [], "cover", 1, { fit: null }, { position: "invalid" }, { overlay: "0" }, { overlay: null }]) {
assert.throws(() => parseImageSettings(JSON.stringify({ schema: 1, images: { "Image.png": value } })));
}
});
test("a partial override stays while the folder layout changes", async () => {
const f = fixture();
f.names(["A.png"]);
f.sidecar(JSON.stringify({ schema: 1, images: { "A.png": { position: "top" } } }));
await f.engine.configure(f.source(), on);
assert.equal(f.frames.get("app")!.size, "cover");
await f.engine.configure(f.source(), { ...on, size: "contain", overlay: -0.4, position: "bottom" });
assert.equal(f.frames.get("app")!.size, "contain");
assert.equal(f.frames.get("app")!.overlay, -0.4);
assert.equal(f.frames.get("app")!.position, "top");
f.engine.dispose();
});
test("a portrait image shows in full over a blurred fill that stays alive through the fade", async () => {
const f = fixture({ width: 100, height: 300 });
f.names(["A.png", "B.png"]);
await f.engine.configure(f.source(), on);
const first = f.frames.get("app")!;
assert.equal(first.size, "contain");
assert.equal(first.blurredUrl, `${first.url}-blur`);
f.sidecar(JSON.stringify({ schema: 1, images: { "B.png": { fit: "cover", position: "bottom", overlay: 0.4 } } }));
f.engine.invalidate();
await f.engine.next(); await settle();
const second = f.frames.get("app")!;
assert.equal(second.size, "cover"); assert.equal(second.position, "bottom"); assert.equal(second.overlay, 0.4);
assert.equal(second.blurredUrl, undefined);
assert.equal(second.previous!.blurredUrl, first.blurredUrl);
assert.equal(f.released.includes(first.blurredUrl!), false, "The fill of the fade stays.");
f.engine.dispose(); await settle();
for (const url of [first.url, first.blurredUrl!, second.url]) assert.ok(f.released.includes(url), url);
});
test("the blurred fills of the last three images stay in the cache", async () => {
const f = fixture({ width: 100, height: 300 });
f.names(["A.png", "B.png", "C.png", "D.png", "E.png"]);
await f.engine.configure(f.source(), { ...on, order: "name" });
for (let index = 0; index < 4; index++) { await f.engine.next(); await settle(); await settle(); }
const blurs = f.counts.blur;
const releasedBlurs = f.released.filter(url => url.endsWith("-blur")).length;
assert.ok(releasedBlurs >= 1, "Old fills beyond the cache are released.");
assert.ok(blurs - releasedBlurs <= BLUR_CACHE + 1, "At most the cache and the prepared fill stay.");
// The same image again uses the cached fill.
const repeat = fixture({ width: 100, height: 300 });
repeat.names(["A.png", "B.png"]);
await repeat.engine.configure(repeat.source(), on);
for (let index = 0; index < 4; index++) { await repeat.engine.next(); await settle(); await settle(); }
assert.equal(repeat.counts.blur, 2, "Two images that alternate use their cached fills.");
f.engine.dispose(); repeat.engine.dispose();
});
test("a late blurred fill is released when the source goes away", async () => {
let resolve!: (url: string) => void;
const f = fixture({ width: 100, height: 300 });
f.names(["A.png"]);
f.runtime.blur = () => new Promise(done => { resolve = done; });
const loading = f.engine.configure(f.source(), on);
await settle(); await settle();
await f.engine.configure(null, on);
resolve("blob:blur");
await loading;
assert.equal(f.frames.size, 0);
assert.ok(f.released.includes("blob:blur"));
assert.ok(f.released.some(url => url.startsWith("blob:A.png")));
f.engine.dispose();
});
test("the sources have stable keys, and the saved image of an old data URL decodes", async () => {
assert.equal(folderSource("D:\\Pictures").key, "folder:D:\\Pictures");
assert.equal(folderSource("D:\\Pictures").timed, true);
const id = "01234567-89ab-cdef-0123-456789abcdef";
assert.equal(imageSource({ imageId: id }).key, `image:${id}`);
assert.equal(imageSource({ imageId: id }).timed, false);
assert.deepEqual(await imageSource({ imageId: id }).list(), ["image"]);
const data = "data:image/png;base64,iVBORw0KGgo=";
const blob = await readSavedImage({ image: data });
assert.equal(blob.type, "image/png");
assert.deepEqual([...new Uint8Array(await blob.arrayBuffer())], [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
assert.notEqual(imageSource({ image: data }).key, imageSource({ image: data.replace("KGgo", "KGgp") }).key);
});
test("Background has a source only with a folder or an existing image", () => {
const appearance = { theme: "default" as const, mode: "dark" as const };
const withImage = { ...appearance, newTabBackground: { imageId: "01234567-89ab-cdef-0123-456789abcdef" } };
assert.equal(hasBackgroundSource(normalizeBackground({ source: "none" }), withImage), false);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "folder" }), appearance), true);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), appearance), false);
assert.equal(hasBackgroundSource(normalizeBackground({ source: "image" }), withImage), true);
});
test("the launch rule starts Background when it has a source, also in browser windows, but not in the settings window", () => {
const rule = LAUNCH_RULES.background!;
assert.equal(rule.browserWindow, true);
assert.equal(LAUNCH_RULES.git, undefined, "Git loads at first need.");
assert.equal(runsInWindow("background", { browserWindow: true }), true);
assert.equal(runsInWindow("git", { browserWindow: true }), false);
assert.equal(runsInWindow("git", { browserWindow: false }), true);
assert.equal(launchWanted("git", { settingsWindow: false }), false);
// In Node the settings are empty, so the source is "none".
assert.equal(rule.wanted(), false);
assert.equal(launchWanted("background", { settingsWindow: false }), false);
const wanted = rule.wanted;
rule.wanted = () => true;
try {
assert.equal(launchWanted("background", { settingsWindow: false }), true);
assert.equal(launchWanted("background", { settingsWindow: true }), false);
} finally { rule.wanted = wanted; }
});
function migrationHost({ image = false, folder = true, fails = false } = {}) {
const calls = { folder: 0 };
const written: BackgroundSettings[] = [];
const host: BackgroundMigrationHost = {
missing: () => true,
hasImage: () => image,
migrateFolder: async () => { calls.folder++; if (fails) throw new Error("no folder"); return folder; },
write: async value => { written.push(value); },
};
return { host, calls, written };
}
const plugin = (installed: boolean, enabled: boolean, settings: unknown): LegacyPlugin => ({ id: "runestone.bg-slideshow", installed, enabled, settings });
const grant = "6f0c7a8e-5b1d-4c2e-9a3f-2d7b8e1c4a90";
const kept = { grant, folder: "D:\\Pictures", seconds: 10, order: "random", enabled: true, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" };
test("the migration selects the folder of an installed, enabled, and running slideshow", async () => {
const { host, calls, written } = migrationHost({ image: true });
const value = await migrateBackground(plugin(true, true, kept), host);
assert.equal(calls.folder, 1);
assert.deepEqual(value, { source: "folder", seconds: 10, order: "random", paused: false, targets: ["app", "pm-all"], overlay: 0.25, position: "top", size: "contain" });
assert.deepEqual(written, [value]);
});
test("a disabled package, a stopped slideshow, or a lost folder gives the image or none, and the folder still migrates", async () => {
for (const [legacy, folder] of [[plugin(true, false, kept), true], [plugin(true, true, { ...kept, enabled: false }), true], [plugin(false, false, kept), true], [plugin(true, true, kept), false]] as const) {
const withImage = migrationHost({ image: true, folder });
assert.equal((await migrateBackground(legacy, withImage.host)).source, "image");
assert.equal(withImage.calls.folder, 1, "A kept grant always migrates its folder.");
const without = migrationHost({ folder });
const value = await migrateBackground(legacy, without.host);
assert.equal(value.source, "none");
assert.equal(value.seconds, 10, "The kept settings still give the sequence and the layout.");
}
});
test("a failed folder migration is not a failed start", async () => {
const errors = console.error;
console.error = () => {};
try {
const { host, written } = migrationHost({ image: true, fails: true });
assert.equal((await migrateBackground(plugin(true, true, kept), host)).source, "image");
assert.equal(written.length, 1);
} finally { console.error = errors; }
});
test("without the old plugin, an image gives the image source and nothing gives none", async () => {
const image = migrationHost({ image: true });
assert.deepEqual(await migrateBackground(undefined, image.host), { ...DEFAULT_BACKGROUND, targets: ["app"], source: "image" });
assert.equal(image.calls.folder, 0, "Without a grant, no folder migrates.");
const none = migrationHost();
assert.deepEqual(await migrateBackground(plugin(false, false, null), none.host), { ...DEFAULT_BACKGROUND, targets: ["app"] });
// Settings of version 0.0.10 and earlier have a path and no grant. Only a grant migrates.
const old = migrationHost();
assert.equal((await migrateBackground(plugin(true, true, { folder: "D:\\Pictures", enabled: true }), old.host)).source, "none");
assert.equal(old.calls.folder, 0);
// Invalid kept values take the defaults.
const invalid = migrationHost();
const value = await migrateBackground(plugin(true, true, { grant, enabled: true, seconds: "x", targets: ["bogus"], overlay: 9 }), invalid.host);
assert.deepEqual([value.source, value.seconds, value.targets, value.overlay], ["folder", 60, [], 1]);
});
+65 -7
View File
@@ -4,6 +4,7 @@ import assert from "node:assert/strict";
import { FEATURES, featureEntry, featureOfOwner } from "../../../src/lib/features/catalog.ts";
import { storedSwitches, switchesFrom } from "../../../src/lib/features/state.ts";
import { legacySwitch, migrateFeatures, type LegacyPlugin } from "../../../src/lib/features/migration.ts";
import type { BackgroundMigrationHost, BackgroundSettings } from "../../../src/lib/features/backgroundSettings.ts";
import { featureErrors, featureRequested, loadFeature } from "../../../src/lib/features/loader.ts";
import { FeatureSession } from "../../../src/lib/features/session.ts";
import type { FeatureContext, FeatureInstance, FeatureModule } from "../../../src/lib/features/types.ts";
@@ -18,15 +19,22 @@ test("each feature keeps the ID of its old plugin package as its owner ID", () =
assert.deepEqual(git.views.map(view => [view.id, view.placement]), [["source-control", "sidebar"], ["diff", "editor"], ["graph", "editor"]]);
assert.equal(git.views[0].title(), "Source control");
assert.deepEqual(git.commands.map(command => [command.id, command.view]), [["graph", "graph"]]);
const background = featureEntry("background");
assert.equal(background.owner, "runestone.bg-slideshow");
assert.equal(featureOfOwner("runestone.bg-slideshow")?.id, "background");
assert.deepEqual(background.views, []);
assert.deepEqual(background.commands.map(command => [command.id, command.view, command.title()]), [["next", undefined, "Next background image"], ["pause", undefined, "Pause background"]]);
assert.equal(background.defaultOn, true);
assert.equal(background.followsPackage, false);
});
test("switches keep known booleans only, and missing keys take the default", () => {
assert.deepEqual(storedSwitches({ git: false, terminal: true, other: "yes" }), { git: false });
assert.deepEqual(storedSwitches(null), {});
assert.deepEqual(storedSwitches(["git"]), {});
assert.deepEqual(switchesFrom(undefined), { git: true });
assert.deepEqual(switchesFrom({ git: false }), { git: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true });
assert.deepEqual(switchesFrom(undefined), { git: true, background: true });
assert.deepEqual(switchesFrom({ git: false, background: false }), { git: false, background: false });
assert.deepEqual(switchesFrom({ git: "false" }), { git: true, background: true });
});
test("an installed package gives its state, and without a package the default applies", () => {
@@ -36,8 +44,19 @@ test("an installed package gives its state, and without a package the default ap
assert.equal(legacySwitch(git, legacy(false, false)), true);
assert.equal(legacySwitch(git, legacy(true, false)), false);
assert.equal(legacySwitch(git, legacy(true, true)), true);
// Background is on for every user, also after an update with a disabled Background Slideshow package.
const background = featureEntry("background");
for (const [installed, enabled] of [[false, false], [true, false], [true, true]]) {
assert.equal(legacySwitch(background, { id: "runestone.bg-slideshow", installed, enabled, settings: null }), true);
}
assert.equal(legacySwitch(background, undefined), true);
});
/** A background host with a section already present: the migration of the section does not run. */
function presentBackground(): BackgroundMigrationHost {
return { missing: () => false, hasImage: () => false, migrateFolder: async () => { throw new Error("not asked"); }, write: async () => { throw new Error("not asked"); } };
}
test("the migration asks only for features without a switch, and keeps other keys", async () => {
const writes: unknown[] = [];
const asked: string[][] = [];
@@ -46,20 +65,39 @@ test("the migration asks only for features without a switch, and keeps other key
write: async (value: unknown) => { writes.push(value); },
legacy: async (ids: string[]) => { asked.push(ids); return packages; },
});
assert.deepEqual(await migrateFeatures(host({ future: 1 }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }])), ["git"]);
assert.deepEqual(await migrateFeatures(host({ future: 1, background: false }, [{ id: "runestone.git", installed: true, enabled: false, settings: null }]), presentBackground()), ["git"]);
assert.deepEqual(asked, [["runestone.git"]]);
assert.deepEqual(writes, [{ future: 1, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true }, [])), []);
assert.deepEqual(writes, [{ future: 1, background: false, git: false }]);
assert.deepEqual(await migrateFeatures(host({ git: true, background: true }, []), presentBackground()), []);
assert.equal(asked.length, 1, "A stored switch needs no package read.");
assert.equal(writes.length, 1);
});
test("a missing background section asks for the slideshow package and makes the section", async () => {
const asked: string[][] = [];
const switches: unknown[] = [];
const sections: BackgroundSettings[] = [];
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { sections.push(value); } };
const host = { read: () => ({ git: true, background: false }), write: async (value: unknown) => { switches.push(value); }, legacy: async (ids: string[]) => { asked.push(ids); return []; } };
assert.deepEqual(await migrateFeatures(host, background), []);
assert.deepEqual(asked, [["runestone.bg-slideshow"]]);
assert.deepEqual(switches, [], "Stored switches stay.");
assert.equal(sections.length, 1);
assert.equal(sections[0].source, "image");
// Both migrations together ask once for both packages.
asked.length = 0;
await migrateFeatures({ ...host, read: () => undefined }, background);
assert.deepEqual(asked, [["runestone.git", "runestone.bg-slideshow"]]);
assert.deepEqual(switches, [{ git: true, background: true }]);
});
test("a failed package read writes nothing, so the next start tries again", async () => {
const writes: unknown[] = [];
const error = console.error;
console.error = () => {};
try {
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } });
const background: BackgroundMigrationHost = { missing: () => true, hasImage: () => true, migrateFolder: async () => true, write: async value => { writes.push(value); } };
const result = await migrateFeatures({ read: () => undefined, write: async value => { writes.push(value); }, legacy: async () => { throw new Error("no host"); } }, background);
assert.deepEqual(result, []);
assert.deepEqual(writes, []);
} finally { console.error = error; }
@@ -97,9 +135,29 @@ test("a feature session shows its views and commands without loading the feature
await session.launch("source-control");
assert.deepEqual(opened, ["graph", "source-control"]);
assert.equal(loads, 0, "Commands and navigation do not load the feature.");
assert.equal(session.started, false);
await session.stop();
});
test("an action command loads the feature and runs it, and start loads it without a view", async () => {
const runs: string[] = [];
let starts = 0;
const instance: FeatureInstance = { mount: () => () => {}, run: command => { runs.push(command); }, dispose() { runs.push("dispose"); } };
const session = new FeatureSession(featureEntry("background"), fakeContext(), async () => ({ start: () => { starts++; return instance; } }));
assert.deepEqual([...session.commands.keys()], ["next", "pause"]);
assert.equal(session.commands.get("pause")?.title, "Pause background");
assert.equal(session.started, false);
await session.run("next");
assert.equal(session.started, true);
await session.start();
await session.run("pause");
assert.equal(starts, 1, "One instance runs the commands and the start.");
await session.stop();
assert.deepEqual(runs, ["next", "pause", "dispose"]);
await assert.rejects(session.run("missing"), /This command is unavailable/);
await assert.rejects(session.start(), /This feature is off/);
});
test("the first mount starts one instance, and stop disposes it", async () => {
const events: string[] = [];
let starts = 0;
+3 -3
View File
@@ -30,12 +30,12 @@ test("a feature module in a start chunk fails, and a separate dynamic chunk pass
chunk("app.js", { isEntry: true, moduleIds: [`${root}src/lib/features/catalog.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts`, moduleIds: [`${root}src/lib/features/git/index.ts`], size: 2048 }),
];
assert.deepEqual(checkChunks(good), { problems: [], sizes: { git: 2048 } });
assert.deepEqual(checkChunks(good, ["git"]), { problems: [], sizes: { git: 2048 } });
const bad = [
chunk("app.js", { isEntry: true, imports: ["shared.js"] }),
chunk("shared.js", { moduleIds: [`${root}src/lib/features/git/model.ts`] }),
chunk("git.js", { isDynamicEntry: true, facadeModuleId: `${root}src/lib/features/git/index.ts` }),
];
assert.deepEqual(checkChunks(bad).problems, ["shared.js loads at start and contains src/lib/features/git/model.ts"]);
assert.deepEqual(checkChunks([chunk("app.js", { isEntry: true })]).problems, ["No chunk starts at src/lib/features/git/index.ts."]);
assert.deepEqual(checkChunks(bad, ["git"]).problems, ["shared.js loads at start and contains src/lib/features/git/model.ts"]);
assert.deepEqual(checkChunks([chunk("app.js", { isEntry: true })], ["git"]).problems, ["No chunk starts at src/lib/features/git/index.ts."]);
});
+1 -2
View File
@@ -65,9 +65,8 @@ test("a required function stays bound to its parent object", async () => {
test("the current host gives every SDK feature when all services are present", async () => {
const pty = { open: async () => {}, write: async () => {}, resize: async () => {}, close: async () => {}, profiles: async () => [], openWindow: async () => {}, dictation: async () => {} };
const files = { chooseFolder: async () => null, pictureFolder: async () => ({ id: "g", path: "p", name: "n" }), grants: async () => [], revoke: async () => false, list: async () => [], readBytes: async () => new Uint8Array(), readSidecar: async () => null, writeSidecar: async () => {} };
const backgrounds = { chooseFolder: async () => null, list: async () => [], read: async () => new Uint8Array() };
const { api, session } = await hostApi({
pty, files, backgrounds, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
pty, files, backgrounds: true, serviceHub: new ServiceHub(), openFile: async () => {}, completionTransport: async () => {},
workspace: { ...base.workspace, listMarkdown: async () => [], readMany: async () => [], readBytes: async () => new Uint8Array(), readOptional: async () => null, create: async () => {}, subscribe: () => () => {} },
settings: { ...base.settings, subscribe: () => () => {} },
}, true);
+2 -2
View File
@@ -65,6 +65,6 @@ test('Migration keeps renamed theme IDs and a background image data URL', () =>
});
test('Every section has one old key', () => {
// `runestone.features` came after the settings file. Only the browser preview uses it.
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings']);
// `runestone.features` and `runestone.background` came after the settings file. Only the browser preview uses them.
assert.deepEqual(Object.values(LEGACY_KEYS).sort(), ['runestone.appearance', 'runestone.background', 'runestone.custom-themes', 'runestone.custom-themes.legacy', 'runestone.features', 'runestone.language', 'runestone.settings']);
});
+34 -18
View File
@@ -103,20 +103,13 @@ test('subscriber errors do not prevent frame cleanup or remaining notifications'
assert.equal(hub.get('pm-all'), null);
});
test('disable removes frames and subscriptions before cleanup and rejects pending file results', async () => {
test('disable removes frames and subscriptions before cleanup', async () => {
let api!: PluginApi;
let finishRead!: (value: Uint8Array) => void;
let finishList!: (value: { name: string }[]) => void;
let finishPicker!: (value: string | null) => void;
const session = new ExternalSession('org.test.backgrounds', {
workspace: { list: async () => [], read: async () => '', write: async () => {} },
settings: { read: async () => null, write: async () => {} },
assets: { read: async () => new Uint8Array() },
backgrounds: {
chooseFolder: () => new Promise(resolve => { finishPicker = resolve; }),
list: () => new Promise(resolve => { finishList = resolve; }),
read: () => new Promise(resolve => { finishRead = resolve; }),
},
backgrounds: true,
}, () => {}, () => {});
let notifications = 0;
await session.start({ activate(value) {
@@ -130,26 +123,49 @@ test('disable removes frames and subscriptions before cleanup and rejects pendin
assert.throws(() => api.backgrounds!.get('app'), /disabled/);
});
} });
const pending = [api.backgrounds!.read('folder', 'file.png'), api.backgrounds!.list('folder'), api.backgrounds!.chooseFolder()];
const rejected = pending.map(request => assert.rejects(request, /disabled/));
// The deprecated folder methods are gone. Plugins use the folder grants of `api.files`.
for (const name of ['chooseFolder', 'defaultFolder', 'list', 'read', 'readImageSettings', 'writeImageSettings']) assert.equal(name in api.backgrounds!, false, name);
await session.stop();
finishRead(new Uint8Array([1])); finishList([{ name: 'file.png' }]); finishPicker('folder');
await Promise.all(rejected);
assert.equal(notifications, 2);
assert.throws(() => api.backgrounds!.set('app', frame), /disabled/);
assert.throws(() => api.backgrounds!.read('folder', 'file.png'), /disabled/);
assert.throws(() => api.backgrounds!.subscribe(() => {}), /disabled/);
assert.equal(backgroundHub.get('app'), null);
});
test('background commands are allowed in main and settings windows', () => {
test('the Background commands are allowed in the windows that use them, and the old plugin commands are gone', () => {
const build = readFileSync(new URL('../../../src-tauri/build.rs', import.meta.url), 'utf8');
for (const scope of ['default', 'settings']) {
const all = ['background_choose_folder', 'background_folder', 'background_clear_folder', 'background_list', 'background_read', 'background_read_sidecar', 'background_write_sidecar', 'background_migrate'];
const scopes: Record<string, string[]> = { default: all, settings: all, browser: ['background_folder', 'background_list', 'background_read', 'background_read_sidecar'] };
for (const [scope, commands] of Object.entries(scopes)) {
const capability = JSON.parse(readFileSync(new URL(`../../../src-tauri/capabilities/${scope}.json`, import.meta.url), 'utf8'));
for (const command of ['backgrounds_choose_folder', 'backgrounds_default_folder', 'backgrounds_list', 'backgrounds_read', 'backgrounds_read_image_settings', 'backgrounds_write_image_settings']) {
for (const command of all) {
assert(build.includes(`"${command}"`), `${command} needs a generated desktop permission`);
assert(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), `${scope} must allow ${command}`);
assert.equal(capability.permissions.includes(`allow-${command.replaceAll('_', '-')}`), commands.includes(command), `${scope} and ${command}`);
}
assert.equal(capability.permissions.some((permission: string) => permission.startsWith('allow-backgrounds-')), false, `${scope} has no old plugin command`);
}
assert.equal(/"backgrounds_/.test(build), false);
});
test('a new app frame changes only the custom properties with a new value', () => {
const writes: string[] = [];
const properties = new Map<string, string>();
const style = { getPropertyValue: (key: string) => properties.get(key) ?? '', getPropertyPriority: () => '',
setProperty: (key: string, value: string) => { writes.push(key); properties.set(key, value); }, removeProperty: (key: string) => { properties.delete(key); } };
const hub = new BackgroundHub(() => ({ style }) as unknown as HTMLElement), owner = Symbol();
hub.set(owner, 'app', frame);
assert.equal(writes.length, 19);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, ['--rs-background-image']);
writes.length = 0;
hub.set(owner, 'app', { ...frame, url: 'blob:http://localhost/second' });
assert.deepEqual(writes, [], 'The same frame writes nothing');
hub.removeOwner(owner);
assert.equal(properties.size, 0);
writes.length = 0;
hub.set(owner, 'app', frame);
assert.equal(writes.length, 19, 'After a removal, the next frame writes every property again');
hub.removeOwner(owner);
});