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
+27 -70
View File
@@ -1,43 +1,42 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, onDestroy } from 'svelte';
import { onMount } from 'svelte';
import { invoke, isTauri } from '@tauri-apps/api/core';
import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes';
import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { onSettingsChange } from '$lib/settings/store';
import { featureSwitches } from '$lib/features/state';
import { loadFeature } from '$lib/features/loader';
import ThemePicker from './ThemePicker.svelte';
import { requestThemeEditor } from './themeEditorRequest';
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, themeNotice, BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, themeNotice, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
let status = $state('');
let exporting = $state(false);
let backgroundInput: HTMLInputElement;
let backgroundRevision = 0;
let backgroundHost = $state<HTMLElement>();
let backgroundError = $state('');
let installed = $state<CustomTheme[]>([]);
let themeInput: HTMLInputElement;
let closePicker = () => {};
const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme =>
themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? $t('Light') : $t('Dark')}`,
}))));
const notice = $derived(themeNotice(appearance.theme));
onDestroy(() => closePicker());
const positionLabels = $derived([$t('Center'), $t('Top left'), $t('Top center'), $t('Top right'), $t('Center left'), $t('Center right'), $t('Bottom left'), $t('Bottom center'), $t('Bottom right')]);
const sizeLabels = $derived([$t('Fill'), $t('Fit'), $t('Actual size')]);
function backgroundPicker(event: MouseEvent, field: 'position' | 'size') {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const values = field === 'position' ? BACKGROUND_POSITIONS : BACKGROUND_SIZES;
const labels = field === 'position' ? positionLabels : sizeLabels;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? $t('Image position') : $t('Image size'), parent: anchor.closest('dialog') ?? undefined,
items: values.map((value, index) => ({ label: labels[index], radio: true, checked: value === appearance.newTabBackground?.[field],
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
}
// The settings of Background come from the feature module. The module loads only while Background is on.
$effect(() => {
const host = backgroundHost;
if (!host || !$featureSwitches.background) return;
let dispose: (() => void) | undefined;
let stopped = false;
backgroundError = '';
loadFeature('background').then(module => {
if (stopped || !module.mountSettings) return;
dispose = module.mountSettings(host);
}, reason => { if (!stopped) backgroundError = $t('{name} could not load: {error}', { name: $t('Background'), error: String(reason) }); });
return () => { stopped = true; dispose?.(); };
});
onMount(() => {
const read = () => { try { installed = customThemes(); appearance = readAppearance(); } catch { error = $t('Could not read appearance settings.'); } };
read();
@@ -51,18 +50,6 @@
}
catch { error = $t('Could not save appearance settings.'); return false; }
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
if (!Number.isFinite(percent)) return;
change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 } });
}
async function removeBackground() {
backgroundRevision++;
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { error = $t('Could not remove the saved image from storage.'); }
}
}
async function importTheme(file?: File) {
if (!file) return;
try {
@@ -73,20 +60,6 @@
} catch (reason) { error = String(reason); }
finally { themeInput.value = ''; }
}
async function importBackground(file?: File) {
if (!file) return;
const revision = ++backgroundRevision;
try {
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error($t('Choose a PNG, JPEG, WebP, or GIF image.'));
const imageId = await saveBackgroundImage(file);
if (revision !== backgroundRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
if (old) await removeBackgroundImage(old);
} else await removeBackgroundImage(imageId);
} catch (reason) { if (revision === backgroundRevision) error = String(reason); }
finally { if (revision === backgroundRevision) backgroundInput.value = ''; }
}
async function exportTemplate() {
if (exporting) return;
exporting = true; error = ''; status = '';
@@ -132,23 +105,13 @@
<div class="setting-row"><label for="surface-transparency">{$t("Transparency amount")}</label><div class="overlay-controls"><input id="surface-transparency" type="range" min="0" max="100" step="1" disabled={appearance.transparency?.enabled === false} value={appearance.transparency?.amount ?? 18} oninput={event => change({ ...appearance, transparency: { enabled: true, amount: event.currentTarget.valueAsNumber } })} /><output for="surface-transparency">{appearance.transparency?.amount ?? 18}%</output></div></div>
</div>
<p>{$t("Turn off transparency to use opaque surfaces and reduce compositing work. Text and icons remain opaque.")}</p>
<h3>{$t("Background image")}</h3>
<div class="background-preview" aria-label={$t("Background image preview")}><span>{$t("Background")}</span></div>
{#if appearance.newTabBackground}
<div class="card">
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="overlay-controls"><input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div>
</div>
<p>{$t("Move left to lighten the image or right to darken it.")}</p>
<h3>{$t("Background")}</h3>
{#if $featureSwitches.background}
<div class="background-host" bind:this={backgroundHost}></div>
{#if backgroundError}<p role="alert">{backgroundError}</p>{/if}
{:else}
<p>{$t("Background is off. Turn it on in Settings → Features.")}</p>
{/if}
<div class="theme-actions">
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>{$t("Choose image…")}</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>{$t("Remove image")}</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>{$t("Reset background")}</button>
</div>
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.")}</p>
{#if status}<p role="status">{status}</p>{/if}
{#if error}<p role="alert">{error}</p>{/if}
<style>
@@ -156,10 +119,6 @@
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5}
.card{padding:0 var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated)}
label,.setting-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}
.setting-row+.setting-row{border-top:1px solid var(--rs-border)}
.picker{display:flex;align-items:center;gap:8px;min-height:var(--rs-settings-control-height);max-width:100%;padding:4px 8px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.picker :global(svg){width:14px;height:14px;flex-shrink:0}
.picker:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}
.theme-preview{display:flex;gap:var(--rs-settings-gap);margin-top:var(--rs-settings-gap);padding:var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);min-height:100px}
.preview-sidebar{display:flex;flex-direction:column;gap:var(--rs-settings-gap);width:22%;padding:var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
.preview-sidebar span{height:6px;background:var(--rs-text-dim);opacity:.5;border-radius:var(--rs-control-radius)}
@@ -187,13 +146,11 @@
.overlay-controls input[type=range]:disabled{cursor:default}
.overlay-controls input[type=range]:disabled::-webkit-slider-thumb{background:var(--rs-text-dim)}
.overlay-controls input[type=range]:disabled::-moz-range-thumb{background:var(--rs-text-dim)}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap}
.overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit}
.overlay-value input:focus-visible{outline:2px solid var(--rs-focus);outline-offset:2px}
[role=alert]{color:var(--rs-error)}
.theme-actions{display:flex;gap:var(--rs-settings-gap);flex-wrap:wrap;margin-top:var(--rs-settings-gap)}
.theme-actions button{display:inline-flex;align-items:center;gap:6px;min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);padding:4px 8px}
.theme-actions button :global(svg){width:14px;height:14px;fill:none;stroke:currentColor;stroke-width:2}
h3{margin-top:var(--rs-settings-section-gap);font-size:14px}.background-preview{height:120px;background-color:var(--rs-bg);background-image:var(--rs-background-image,none);background-size:100% 100%,var(--rs-background-size,cover);background-position:center,var(--rs-background-position,center);background-repeat:no-repeat;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);display:grid;place-items:center;margin-bottom:var(--rs-settings-gap)}.background-preview span{padding:8px 14px;background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
h3{margin-top:var(--rs-settings-section-gap);font-size:14px}
.background-host{min-width:0}
</style>
+5 -61
View File
@@ -1,5 +1,4 @@
import { customThemes, FONT_ROLES, type ThemeFonts, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { readSection, writeSection } from '../settings/store.ts';
import { BUILTIN_THEMES as THEME_DATA, DEFAULT_FONTS, DEFAULT_THEME, LEGACY_THEME_IDS, builtinTheme, type BuiltinThemeId } from './themes/index.ts';
import { ROLES, resolveColors, type Mode, type ResolvedColors } from './roles.ts';
@@ -90,70 +89,15 @@ export function applyTransparency(value: Appearance['transparency'], root: HTMLE
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
root.style.setProperty('--rs-transparent-plugin-bg', 'transparent');
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) {
root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? 'var(--rs-surface-opacity)' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'var(--rs-transparent-plugin-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-menu-bg', hasImage ? 'var(--rs-image-menu-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-menu-active-bg', hasImage ? 'var(--rs-image-menu-active-bg)' : 'var(--rs-bg-active)');
root.style.setProperty('--rs-menu-backdrop', hasImage ? 'var(--rs-image-menu-backdrop)' : 'none');
}
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId;
backgroundRequests.set(root, id);
if (!id) { applyBackgroundImage(root, background?.image); return; }
const previous = backgroundUrls.get(root);
if (previous?.image === id) { root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`); applyBackgroundSurfaces(root, true); return; }
applyBackgroundImage(root);
try {
const file = await readBackgroundImage(id);
if (!file || backgroundRequests.get(root) !== id) return;
const url = URL.createObjectURL(file);
const old = backgroundUrls.get(root);
backgroundUrls.set(root, { image: id, url });
root.style.setProperty('--rs-new-tab-image', `url("${url}")`);
applyBackgroundSurfaces(root, true);
if (old) URL.revokeObjectURL(old.url);
} catch { /* Keep the theme usable if image storage is unavailable. */ }
}
function applyBackgroundImage(root: HTMLElement, image?: string) {
const previous = backgroundUrls.get(root);
if (image && previous?.image === image) {
root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`);
applyBackgroundSurfaces(root, true);
return;
}
let url: string | undefined;
if (image) {
try {
const [header, data] = image.split(',');
const bytes = Uint8Array.from(atob(data), character => character.charCodeAt(0));
url = URL.createObjectURL(new Blob([bytes], { type: header.slice(5, header.indexOf(';')) }));
} catch { /* Invalid saved image data must not stop the theme update. */ }
}
// Large data URLs exceed Chromium's CSS variable limit. Keep only a short blob URL in CSS.
root.style.setProperty('--rs-new-tab-image', url ? `url("${url}")` : 'none');
applyBackgroundSurfaces(root, !!url);
if (image && url) backgroundUrls.set(root, { image, url });
else backgroundUrls.delete(root);
if (previous) URL.revokeObjectURL(previous.url);
}
/**
* Apply the theme, the fonts, and the transparency. The Background feature (`src/lib/features/background/`) shows the
* saved image of `newTabBackground` through the background frames, so this function does not draw it.
*/
export function applyAppearance(value: Appearance, root = document.documentElement) {
const normalized = normalizeAppearance(value);
const { theme, newTabBackground } = normalized;
const { theme } = normalized;
const { mode, colors, fonts } = resolveTheme(theme, normalized.mode);
applyTransparency(normalized.transparency, root);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0;
const shade = overlay < 0 ? '255,255,255' : '0,0,0';
root.style.setProperty('--rs-background-overlay', `linear-gradient(rgba(${shade},${Math.abs(overlay)}),rgba(${shade},${Math.abs(overlay)}))`);
root.style.setProperty('--rs-background-image', newTabBackground ? 'var(--rs-background-overlay), var(--rs-new-tab-image, none)' : 'none');
root.style.setProperty('--rs-background-position', newTabBackground?.position ?? 'center');
root.style.setProperty('--rs-background-size', newTabBackground?.size ?? 'cover');
void applySavedBackground(root, newTabBackground);
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
+34
View File
@@ -0,0 +1,34 @@
/*
* The background layer behind the workarea of the workbench and behind a blank browser tab of a browser window.
* `backgroundHub.applyApp` (src/lib/plugins/backgrounds.ts) sets the custom properties on the body and fades `::after`.
* Each window places the layer with its own `position` and `inset`.
*/
.workarea-background {
pointer-events: none;
background-color: var(--rs-bg);
background-image: var(--rs-background-image, none);
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
background-repeat: no-repeat;
}
.workarea-background::before,
.workarea-background::after {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
background-repeat: no-repeat;
}
.workarea-background::before {
background-image: var(--rs-background-previous-image, none);
background-size: var(--rs-background-previous-layer-sizes, 100% 100%, var(--rs-background-previous-size, cover));
background-position: var(--rs-background-previous-layer-positions, center, var(--rs-background-previous-position, center));
}
.workarea-background::after {
background-image: var(--rs-background-transition-image, none);
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
}