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
+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");