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:
@@ -0,0 +1,299 @@
|
||||
<!--
|
||||
Appearance → Background. The source is a folder (a slideshow), one image, or none. The folder layout and the order
|
||||
are in the `background` settings section. The image and its layout stay in `appearance.newTabBackground`.
|
||||
This component also works in the settings window, where the slideshow does not run. It sends Next to every window.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, onMount } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { onSettingsChange } from "$lib/settings/store";
|
||||
import { serviceHub } from "$lib/plugins/services";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, saveAppearance, type Appearance } from "$lib/theme/appearance";
|
||||
import { removeBackgroundImage, saveBackgroundImage } from "$lib/theme/backgroundImages";
|
||||
import { hasImage, normalizeLayout, readBackground, writeBackground, type BackgroundLayout, type BackgroundSettings, type BackgroundSource } from "../backgroundSettings";
|
||||
import { folderHost, readSavedImage, sendBackgroundCommand } from "./sources";
|
||||
import { imageNames } from "./imageSettings";
|
||||
import ImageEditor from "./ImageEditor.svelte";
|
||||
|
||||
/** The Project Management service that lists the boards of the workspace as `{ id, name }[]`. Stage 7-5 makes it native. */
|
||||
const BOARD_SERVICE = ["runestone.pm", "boards"] as const;
|
||||
const boardId = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
|
||||
let settings = $state<BackgroundSettings>(readBackground());
|
||||
let appearance = $state<Appearance>(readAppearance());
|
||||
let folder = $state<string | null>(null);
|
||||
let folderNote = $state("");
|
||||
let boards = $state<{ id: string; name: string }[]>([]);
|
||||
let boardsNote = $state("");
|
||||
let previewUrl = $state("");
|
||||
let error = $state("");
|
||||
let imageInput: HTMLInputElement;
|
||||
let imageRevision = 0;
|
||||
let boardRevision = 0;
|
||||
let previewKey = "";
|
||||
let closeMenu = () => {};
|
||||
let disposed = false;
|
||||
|
||||
const image = $derived(appearance.newTabBackground);
|
||||
const layout = $derived<BackgroundLayout | null>(settings.source === "folder" ? normalizeLayout(settings) : settings.source === "image" && hasImage(appearance) ? normalizeLayout(image) : null);
|
||||
const sourceLabels = $derived<Record<BackgroundSource, string>>({ folder: $t("Folder"), image: $t("Image"), none: $t("None") });
|
||||
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")]);
|
||||
const orderLabels = $derived({ name: $t("File name"), random: $t("Random") });
|
||||
const targets = $derived([
|
||||
{ id: "app", name: $t("The workspace and new tabs") },
|
||||
{ id: "pm-all", name: $t("All Project Management boards") },
|
||||
...boards.map(board => ({ id: `pm-board:${board.id}`, name: $t("Board: {name}", { name: board.name }) })),
|
||||
// Keep saved targets without a current board, so that the user can remove them.
|
||||
...settings.targets.filter(id => id.startsWith("pm-board:") && !boards.some(board => `pm-board:${board.id}` === id))
|
||||
.map(id => ({ id, name: $t("Unavailable board: {id}", { id: id.slice(9) }) })),
|
||||
]);
|
||||
|
||||
const report = (reason: unknown) => { if (!disposed) error = reason instanceof Error ? reason.message : String(reason); };
|
||||
|
||||
function save(next: BackgroundSettings) {
|
||||
settings = next; error = "";
|
||||
writeBackground(next).catch(() => report(tr("Could not save the background settings.")));
|
||||
}
|
||||
|
||||
function saveImageAppearance(next: Appearance) {
|
||||
try {
|
||||
saveAppearance(next).catch(() => report(tr("Could not save appearance settings.")));
|
||||
appearance = readAppearance(); error = ""; return true;
|
||||
} catch { report(tr("Could not save appearance settings.")); return false; }
|
||||
}
|
||||
|
||||
function changeLayout(patch: Partial<BackgroundLayout>) {
|
||||
if (settings.source === "folder") save({ ...settings, ...patch });
|
||||
else if (image) saveImageAppearance({ ...appearance, newTabBackground: { ...image, ...patch } });
|
||||
}
|
||||
|
||||
function changeOverlay(input: HTMLInputElement) {
|
||||
const percent = input.valueAsNumber;
|
||||
if (!Number.isFinite(percent)) return;
|
||||
changeLayout({ overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 });
|
||||
}
|
||||
|
||||
function picker(event: MouseEvent, label: string, choices: { label: string; checked: boolean; run: () => void }[]) {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label, parent: anchor.closest("dialog") ?? undefined,
|
||||
items: choices.map(choice => ({ label: choice.label, radio: true, checked: choice.checked, run: choice.run })) }).close;
|
||||
}
|
||||
|
||||
async function chooseSource(source: BackgroundSource) {
|
||||
error = "";
|
||||
if (source === "folder" && !folder) { await chooseFolder(); return; }
|
||||
if (source === "image" && !hasImage(appearance)) { imageInput.click(); return; }
|
||||
save({ ...settings, source });
|
||||
}
|
||||
|
||||
async function chooseFolder() {
|
||||
try {
|
||||
const chosen = await folderHost.choose(tr("Choose the background folder"));
|
||||
if (!chosen || disposed) return;
|
||||
folder = chosen;
|
||||
save({ ...settings, source: "folder" });
|
||||
await sendBackgroundCommand("reload");
|
||||
void inspectFolder();
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function removeFolder() {
|
||||
try {
|
||||
await folderHost.clear();
|
||||
folder = null; folderNote = "";
|
||||
if (settings.source === "folder") save({ ...settings, source: "none" });
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** Count the images of the folder, so that the user sees a problem at once. */
|
||||
async function inspectFolder() {
|
||||
if (!folder) { folderNote = ""; return; }
|
||||
try {
|
||||
const count = imageNames(await folderHost.list()).length;
|
||||
if (!disposed) folderNote = count ? tr(count === 1 ? "{count} image." : "{count} images.", { count }) : tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.");
|
||||
} catch (reason) { if (!disposed) folderNote = reason instanceof Error ? reason.message : String(reason); }
|
||||
}
|
||||
|
||||
async function importImage(file?: File) {
|
||||
if (!file) return;
|
||||
const revision = ++imageRevision;
|
||||
try {
|
||||
if (!["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)) throw new Error(tr("Choose a PNG, JPEG, WebP, or GIF image."));
|
||||
const imageId = await saveBackgroundImage(file);
|
||||
if (revision !== imageRevision) { await removeBackgroundImage(imageId); return; }
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
|
||||
if (settings.source !== "image") save({ ...settings, source: "image" });
|
||||
if (old) await removeBackgroundImage(old);
|
||||
} else await removeBackgroundImage(imageId);
|
||||
} catch (reason) { if (revision === imageRevision) report(reason); }
|
||||
finally { if (revision === imageRevision) imageInput.value = ""; }
|
||||
}
|
||||
|
||||
async function removeImage() {
|
||||
imageRevision++;
|
||||
const old = appearance.newTabBackground?.imageId;
|
||||
if (saveImageAppearance({ ...appearance, newTabBackground: undefined }) && old) {
|
||||
try { await removeBackgroundImage(old); } catch { report(tr("Could not remove the saved image from storage.")); }
|
||||
}
|
||||
}
|
||||
|
||||
function toggleTarget(id: string, on: boolean) {
|
||||
save({ ...settings, targets: on ? [...new Set([...settings.targets, id])] : settings.targets.filter(target => target !== id) });
|
||||
}
|
||||
|
||||
async function discoverBoards() {
|
||||
const revision = ++boardRevision;
|
||||
const service = serviceHub.get(...BOARD_SERVICE, () => !disposed);
|
||||
if (!service || typeof service.list !== "function") {
|
||||
boards = []; boardsNote = tr("Turn on Project Management to show the background on one board.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const rows = await service.list();
|
||||
if (disposed || revision !== boardRevision) return;
|
||||
boards = (Array.isArray(rows) ? rows : []).flatMap((row: unknown) => {
|
||||
if (!row || typeof row !== "object" || !("id" in row) || typeof row.id !== "string" || !boardId.test(row.id)) return [];
|
||||
return [{ id: row.id, name: "name" in row && typeof row.name === "string" && row.name ? row.name : row.id }];
|
||||
}).filter((board, index, rows) => rows.findIndex(other => other.id === board.id) === index);
|
||||
boardsNote = boards.length ? "" : tr("The workspace has no boards.");
|
||||
} catch (reason) {
|
||||
if (!disposed && revision === boardRevision) boardsNote = tr("Could not read the workspace boards: {error}", { error: reason instanceof Error ? reason.message : String(reason) });
|
||||
}
|
||||
}
|
||||
|
||||
/** The preview of the saved image. It uses its own blob URL, so it works in every window. */
|
||||
async function updatePreview() {
|
||||
const saved = settings.source === "image" ? appearance.newTabBackground : undefined;
|
||||
const key = saved && hasImage(appearance) ? saved.imageId ?? `${saved.image?.length}:${saved.image?.slice(-48)}` : "";
|
||||
if (key === previewKey) return;
|
||||
previewKey = key;
|
||||
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||
previewUrl = "";
|
||||
if (!key || !saved) return;
|
||||
try {
|
||||
const url = URL.createObjectURL(await readSavedImage(saved));
|
||||
if (disposed || previewKey !== key) { URL.revokeObjectURL(url); return; }
|
||||
previewUrl = url;
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
const overlayShade = $derived(layout ? `linear-gradient(rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}),rgba(${layout.overlay < 0 ? "255,255,255" : "0,0,0"},${Math.abs(layout.overlay)}))` : "none");
|
||||
|
||||
$effect(() => { void settings.source; void appearance.newTabBackground; void updatePreview(); });
|
||||
|
||||
onMount(() => {
|
||||
const read = () => { settings = readBackground(); appearance = readAppearance(); };
|
||||
const stops = [onSettingsChange("background", read), onSettingsChange("appearance", read), serviceHub.subscribe((plugin, name) => { if (plugin === BOARD_SERVICE[0] && name === BOARD_SERVICE[1]) void discoverBoards(); })];
|
||||
void folderHost.current().then(value => { if (!disposed) { folder = value; void inspectFolder(); } }, () => { folder = null; });
|
||||
void discoverBoards();
|
||||
return () => stops.forEach(stop => stop());
|
||||
});
|
||||
onDestroy(() => { disposed = true; closeMenu(); if (previewUrl) URL.revokeObjectURL(previewUrl); });
|
||||
</script>
|
||||
|
||||
<div class="background-settings">
|
||||
<div class="card">
|
||||
<div class="setting-row"><span>{$t("Background source")}</span><button class="picker" aria-label={$t("Background source")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Background source"), (["folder", "image", "none"] as const).map(source => ({ label: sourceLabels[source], checked: settings.source === source, run: () => void chooseSource(source) })))}>{sourceLabels[settings.source]}<Icon icon="chevron-down" /></button></div>
|
||||
{#if settings.source === "folder"}
|
||||
<div class="setting-row folder-row"><label for="background-folder">{$t("Image folder")}</label><div class="controls folder-controls">
|
||||
<input id="background-folder" readonly value={folder ?? ""} title={folder ?? ""} placeholder={$t("No folder selected")} />
|
||||
<button onclick={() => void chooseFolder()}><Icon icon="folder-open" />{$t("Choose folder…")}</button>
|
||||
{#if folder}<button onclick={() => void removeFolder()}>{$t("Remove folder")}</button>{/if}
|
||||
</div></div>
|
||||
<div class="setting-row"><label for="background-seconds">{$t("Seconds per image")}</label><input id="background-seconds" type="number" min="1" max="86400" step="1" value={settings.seconds}
|
||||
onchange={event => { if (event.currentTarget.reportValidity()) save({ ...settings, seconds: event.currentTarget.valueAsNumber }); }} /></div>
|
||||
<div class="setting-row"><span>{$t("Image order")}</span><button class="picker" aria-label={$t("Image order")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image order"), (["name", "random"] as const).map(order => ({ label: orderLabels[order], checked: settings.order === order, run: () => save({ ...settings, order }) })))}>{orderLabels[settings.order]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Slideshow")}</span><div class="controls">
|
||||
<button onclick={() => void sendBackgroundCommand("next").catch(report)}><Icon icon="arrow-right" />{$t("Next image")}</button>
|
||||
<button aria-pressed={settings.paused} onclick={() => save({ ...settings, paused: !settings.paused })}>{settings.paused ? $t("Resume slideshow") : $t("Pause slideshow")}</button>
|
||||
</div></div>
|
||||
{:else if settings.source === "image"}
|
||||
<div class="background-preview" role="img" aria-label={$t("Background image preview")}
|
||||
style:background-image={previewUrl ? `${overlayShade}, url("${previewUrl}")` : "none"}
|
||||
style:background-size={layout ? `100% 100%, ${layout.size}` : undefined}
|
||||
style:background-position={layout ? `center, ${layout.position}` : undefined}><span>{$t("Background")}</span></div>
|
||||
<div class="actions">
|
||||
<button onclick={() => imageInput.click()}>{$t("Choose image…")}</button>
|
||||
{#if image}<button onclick={() => void removeImage()}>{$t("Remove image")}</button>{/if}
|
||||
</div>
|
||||
{/if}
|
||||
{#if layout}
|
||||
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu"
|
||||
onclick={event => picker(event, $t("Image position"), BACKGROUND_POSITIONS.map((value, index) => ({ label: positionLabels[index], checked: layout?.position === value, run: () => changeLayout({ position: value }) })))}>{positionLabels[BACKGROUND_POSITIONS.indexOf(layout.position)]}<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 => picker(event, $t("Image size"), BACKGROUND_SIZES.map((value, index) => ({ label: sizeLabels[index], checked: layout?.size === value, run: () => changeLayout({ size: value }) })))}>{sizeLabels[BACKGROUND_SIZES.indexOf(layout.size)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="controls overlay-controls">
|
||||
<input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round(layout.overlay * 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(layout.overlay * 100)}
|
||||
oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((layout?.overlay ?? 0) * 100)); }} /><span>%</span></label>
|
||||
</div></div>
|
||||
{/if}
|
||||
</div>
|
||||
<input bind:this={imageInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importImage(event.currentTarget.files?.[0])} />
|
||||
{#if settings.source === "folder"}
|
||||
<p>{$t("Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.")}</p>
|
||||
{#if folderNote}<p role="status">{folderNote}</p>{/if}
|
||||
{:else if settings.source === "image"}
|
||||
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.")}</p>
|
||||
{:else}
|
||||
<p>{$t("Choose a folder for a slideshow, or one image.")}</p>
|
||||
{/if}
|
||||
{#if layout}<p>{$t("Move the overlay left to lighten the image or right to darken it.")}</p>{/if}
|
||||
{#if settings.source === "folder" && folder}
|
||||
<ImageEditor {settings} />
|
||||
{/if}
|
||||
{#if settings.source !== "none"}
|
||||
<fieldset class="targets">
|
||||
<legend>{$t("Show the background in")}</legend>
|
||||
{#each targets as target (target.id)}
|
||||
<label class="check"><input type="checkbox" checked={settings.targets.includes(target.id)} onchange={event => toggleTarget(target.id, event.currentTarget.checked)} /><span>{target.name}</span></label>
|
||||
{/each}
|
||||
{#if boardsNote}<p>{boardsNote}</p>{/if}
|
||||
</fieldset>
|
||||
{/if}
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.background-settings { display: grid; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.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); min-width: 0; }
|
||||
.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; min-width: 0; }
|
||||
.card > * + * { border-top: 1px solid var(--rs-border); }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; max-width: 100%; }
|
||||
.folder-controls { flex: 1 1 320px; justify-content: flex-end; }
|
||||
.folder-controls input { flex: 1 1 160px; min-width: 120px; width: 0; }
|
||||
input:not([type=checkbox]):not([type=range]), button { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button { display: inline-flex; align-items: center; gap: 6px; background: var(--rs-bg-elevated); cursor: pointer; }
|
||||
button:hover { background: var(--rs-bg-active); }
|
||||
button[aria-pressed="true"] { border-color: var(--rs-accent); }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
.picker { max-width: 100%; background: var(--rs-bg); }
|
||||
input[type=number] { width: 88px; }
|
||||
:is(button, input):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.actions { display: flex; flex-wrap: wrap; gap: var(--rs-settings-gap); padding: var(--rs-settings-row-padding) 0; }
|
||||
.background-preview { height: 120px; margin-top: var(--rs-settings-row-padding); background-color: var(--rs-bg); background-repeat: no-repeat; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); display: grid; place-items: center; }
|
||||
.background-preview span { padding: 8px 14px; background: var(--rs-bg-elevated); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range] { width: 160px; max-width: 100%; min-width: 0; appearance: none; background: transparent; height: var(--rs-settings-control-height); margin: 0; cursor: pointer; }
|
||||
.overlay-controls input[type=range]::-webkit-slider-runnable-track { height: 6px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-webkit-slider-thumb { appearance: none; width: 18px; height: 18px; margin-top: -7px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]::-moz-range-track { height: 4px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); border-radius: var(--rs-control-radius); }
|
||||
.overlay-controls input[type=range]::-moz-range-thumb { width: 14px; height: 14px; background: var(--rs-accent); border: 2px solid var(--rs-text-strong); border-radius: 50%; }
|
||||
.overlay-controls input[type=range]:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; border-radius: var(--rs-control-radius); }
|
||||
.overlay-value { display: flex; align-items: center; gap: 4px; }
|
||||
.overlay-value input { width: 64px; }
|
||||
.targets { display: grid; gap: 2px; min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
.targets legend { padding: 0 4px; color: var(--rs-text); }
|
||||
.check { display: flex; align-items: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); overflow-wrap: anywhere; }
|
||||
.check input { flex-shrink: 0; accent-color: var(--rs-accent); }
|
||||
[role=alert] { color: var(--rs-error); }
|
||||
</style>
|
||||
@@ -0,0 +1,227 @@
|
||||
<!--
|
||||
The appearance of one image of the folder: fit, position, and overlay. It saves the sidecar file of the folder
|
||||
(`.runestone-backgrounds.json`) only when the file did not change since the read. Then every window reads it again.
|
||||
-->
|
||||
<script lang="ts">
|
||||
import { onDestroy, untrack } from "svelte";
|
||||
import { t, tr } from "$lib/i18n";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { showActionMenu } from "$lib/ui/managedActionMenu";
|
||||
import { BACKGROUND_POSITIONS } from "$lib/theme/appearance";
|
||||
import { normalizeLayout, type BackgroundSettings } from "../backgroundSettings";
|
||||
import { folderHost, sendBackgroundCommand } from "./sources";
|
||||
import { imageAppearance, imageFits, imageNames, parseImageSettings, sidecarName, type ImageAppearance, type ImageSettings } from "./imageSettings";
|
||||
|
||||
let { settings }: { settings: BackgroundSettings } = $props();
|
||||
|
||||
let names = $state<string[]>([]);
|
||||
let selected = $state("");
|
||||
let query = $state("");
|
||||
let pickerOpen = $state(false);
|
||||
let draft = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let baseline = $state<ImageAppearance>({ fit: "cover", position: "center", overlay: 0 });
|
||||
let saved = $state<ImageSettings>({ schema: 1, images: {} });
|
||||
let source: string | null = null;
|
||||
let url = $state("");
|
||||
let portrait = false;
|
||||
let loaded = $state(false);
|
||||
let busy = $state(false);
|
||||
let status = $state({ text: "", error: false });
|
||||
let generation = 0;
|
||||
let closed = false;
|
||||
let closeMenu = () => {};
|
||||
let trigger: HTMLButtonElement | undefined = $state();
|
||||
let search: HTMLInputElement | undefined = $state();
|
||||
const pickerId = $props.id();
|
||||
|
||||
const filtered = $derived(names.filter(name => name.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase())));
|
||||
const fitLabels = $derived<Record<string, string>>({ cover: $t("Fill"), contain: $t("Fit"), auto: $t("Actual size"), blurred: $t("Full image with blurred fill") });
|
||||
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 changed = $derived(draft.fit !== baseline.fit || draft.position !== baseline.position || draft.overlay !== baseline.overlay);
|
||||
|
||||
const report = (reason: unknown) => { if (!closed) status = { text: reason instanceof Error ? reason.message : String(reason), error: true }; };
|
||||
|
||||
/** The values that differ from the inherited appearance. Only these go to the file. */
|
||||
function changes(): Partial<ImageAppearance> {
|
||||
return {
|
||||
...(draft.fit !== baseline.fit ? { fit: draft.fit } : {}),
|
||||
...(draft.position !== baseline.position ? { position: draft.position } : {}),
|
||||
...(draft.overlay !== baseline.overlay ? { overlay: draft.overlay } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function load() {
|
||||
const revision = ++generation;
|
||||
loaded = false; pickerOpen = false; names = [];
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const [text, list] = await Promise.all([folderHost.readSidecar(), folderHost.list()]);
|
||||
if (closed || revision !== generation) return;
|
||||
saved = parseImageSettings(text); source = text;
|
||||
names = imageNames(list);
|
||||
if (!names.includes(selected)) selected = names[0] ?? "";
|
||||
if (selected) await choose(selected);
|
||||
else status = { text: tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
async function choose(name: string) {
|
||||
const revision = ++generation;
|
||||
selected = name; loaded = false;
|
||||
if (url) URL.revokeObjectURL(url);
|
||||
url = "";
|
||||
try {
|
||||
const next = URL.createObjectURL(await folderHost.read(name));
|
||||
try {
|
||||
const image = new Image(); image.src = next; await image.decode();
|
||||
if (closed || revision !== generation) { URL.revokeObjectURL(next); return; }
|
||||
portrait = image.naturalHeight > image.naturalWidth;
|
||||
} catch (error) { URL.revokeObjectURL(next); throw error; }
|
||||
url = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
loaded = true;
|
||||
status = { text: saved.images[name] ? tr("Saved appearance.") : tr("Default appearance."), error: false };
|
||||
} catch (reason) { report(reason); }
|
||||
}
|
||||
|
||||
/** A change of the folder layout changes the inherited values. Keep the edits of the user. */
|
||||
function inherit() {
|
||||
if (!loaded) return;
|
||||
const next = imageAppearance(normalizeLayout(settings), saved.images[selected], portrait);
|
||||
if (next.fit === baseline.fit && next.position === baseline.position && next.overlay === baseline.overlay) return;
|
||||
const edited = changes();
|
||||
baseline = next;
|
||||
draft = { ...next, ...edited };
|
||||
}
|
||||
|
||||
async function write(reset: boolean) {
|
||||
if (!loaded || busy) return;
|
||||
const edited = changes();
|
||||
if (!reset && !Object.keys(edited).length) return;
|
||||
busy = true;
|
||||
const revision = generation, name = selected;
|
||||
try {
|
||||
const next = structuredClone($state.snapshot(saved)) as ImageSettings;
|
||||
if (reset) delete next.images[name]; else next.images[name] = { ...next.images[name], ...edited };
|
||||
const contents = JSON.stringify(next, null, 2) + "\n";
|
||||
await folderHost.writeSidecar(contents, source);
|
||||
if (closed || revision !== generation) return;
|
||||
source = contents; saved = next;
|
||||
draft = imageAppearance(normalizeLayout(settings), saved.images[name], portrait);
|
||||
baseline = { ...draft };
|
||||
status = { text: reset ? tr("Default appearance restored.") : tr("Image appearance saved."), error: false };
|
||||
await sendBackgroundCommand("reload");
|
||||
} catch (reason) { report(reason); }
|
||||
finally { busy = false; }
|
||||
}
|
||||
|
||||
function menu(event: MouseEvent, field: "fit" | "position") {
|
||||
closeMenu();
|
||||
const anchor = event.currentTarget as HTMLButtonElement;
|
||||
const bounds = anchor.getBoundingClientRect();
|
||||
const values: readonly string[] = field === "fit" ? imageFits : BACKGROUND_POSITIONS;
|
||||
closeMenu = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === "fit" ? $t("Image fit") : $t("Position of this image"), parent: anchor.closest("dialog") ?? undefined,
|
||||
items: values.map((value, index) => ({ label: field === "fit" ? fitLabels[value] : positionLabels[index], radio: true, checked: draft[field] === value,
|
||||
run: () => { draft = { ...draft, [field]: value }; } })) }).close;
|
||||
}
|
||||
|
||||
function overlay(input: HTMLInputElement) {
|
||||
if (input.validity.valid && Number.isFinite(input.valueAsNumber)) draft = { ...draft, overlay: Math.round(Math.max(-100, Math.min(100, input.valueAsNumber))) / 100 };
|
||||
}
|
||||
|
||||
function openPicker() {
|
||||
if (pickerOpen) { pickerOpen = false; return; }
|
||||
query = ""; pickerOpen = true;
|
||||
queueMicrotask(() => search?.focus());
|
||||
}
|
||||
|
||||
function pick(name: string) {
|
||||
pickerOpen = false;
|
||||
void choose(name).then(() => trigger?.focus());
|
||||
}
|
||||
|
||||
function moveFocus(event: KeyboardEvent, list: HTMLElement) {
|
||||
const rows = [...list.querySelectorAll<HTMLButtonElement>("button")];
|
||||
if (!rows.length) return;
|
||||
const index = rows.indexOf(document.activeElement as HTMLButtonElement);
|
||||
const next = event.key === "Home" ? 0 : event.key === "End" ? rows.length - 1 : index < 0 ? (event.key === "ArrowDown" ? 0 : rows.length - 1) : Math.max(0, Math.min(rows.length - 1, index + (event.key === "ArrowDown" ? 1 : -1)));
|
||||
event.preventDefault();
|
||||
rows[next].focus();
|
||||
}
|
||||
|
||||
$effect(() => { void settings.size; void settings.position; void settings.overlay; untrack(inherit); });
|
||||
void load();
|
||||
onDestroy(() => { closed = true; generation++; closeMenu(); if (url) URL.revokeObjectURL(url); });
|
||||
</script>
|
||||
|
||||
<details class="image-editor">
|
||||
<summary>{$t("Per-image appearance")}</summary>
|
||||
<p>{$t("Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.")}</p>
|
||||
<fieldset disabled={busy}>
|
||||
<div class="row"><span>{$t("Image")}</span>
|
||||
<button bind:this={trigger} class="choice" aria-label={$t("Image to change")} aria-expanded={pickerOpen} aria-controls={pickerId} disabled={!names.length} onclick={openPicker}>
|
||||
<span class="name">{selected || $t("Choose an image")}</span><Icon icon="chevron-down" /></button></div>
|
||||
{#if pickerOpen}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Escape closes the picker.) -->
|
||||
<div id={pickerId} class="rs-picker image-picker" onkeydown={event => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); pickerOpen = false; trigger?.focus(); } }}>
|
||||
<input bind:this={search} type="search" aria-label={$t("Find an image")} placeholder={$t("Find an image")} bind:value={query}
|
||||
onkeydown={event => { if (event.key === "ArrowDown" || event.key === "ArrowUp") moveFocus(event, event.currentTarget.nextElementSibling as HTMLElement); else if (event.key === "Enter" && filtered[0]) { event.preventDefault(); pick(filtered[0]); } }} />
|
||||
<div class="options" role="listbox" aria-label={$t("Image files")} tabindex="-1"
|
||||
onkeydown={event => { if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) moveFocus(event, event.currentTarget); }}>
|
||||
{#each filtered.slice(0, 100) as name (name)}
|
||||
<button class="rs-picker-row" role="option" tabindex="-1" aria-selected={name === selected} onclick={() => pick(name)}>{name}</button>
|
||||
{/each}
|
||||
</div>
|
||||
<p role="status">{!filtered.length ? $t("No matching images.") : filtered.length > 100 ? $t("{count} matches. Type more of the name to see other images.", { count: filtered.length }) : $t(filtered.length === 1 ? "{count} image." : "{count} images.", { count: filtered.length })}</p>
|
||||
</div>
|
||||
{/if}
|
||||
<div class="preview" role="img" aria-label={selected ? $t("Selected image preview: {name}", { name: selected }) : $t("Selected image preview")}>
|
||||
{#if url}
|
||||
{#if draft.fit === "blurred"}<span class="fill" style:background-image={`url("${url}")`}></span>{/if}
|
||||
<span class="foreground" style:background-image={`url("${url}")`} style:background-size={draft.fit === "blurred" ? "contain" : draft.fit} style:background-position={draft.position}></span>
|
||||
{/if}
|
||||
<span class="shade" style:background={draft.overlay < 0 ? "white" : "black"} style:opacity={String(Math.abs(draft.overlay))}></span>
|
||||
</div>
|
||||
<div class="row"><span>{$t("Fit")}</span><button class="choice" aria-label={$t("Image fit")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "fit")}>{fitLabels[draft.fit]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Position")}</span><button class="choice" aria-label={$t("Position of this image")} aria-haspopup="menu" disabled={!loaded} onclick={event => menu(event, "position")}>{positionLabels[BACKGROUND_POSITIONS.indexOf(draft.position)]}<Icon icon="chevron-down" /></button></div>
|
||||
<div class="row"><span>{$t("Overlay")}</span><div class="controls">
|
||||
<input type="range" min="-100" max="100" aria-label={$t("Overlay of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} />
|
||||
<input type="number" min="-100" max="100" step="1" required aria-label={$t("Overlay percentage of this image")} disabled={!loaded} value={Math.round(draft.overlay * 100)} oninput={event => overlay(event.currentTarget)} /><span>%</span>
|
||||
</div></div>
|
||||
<div class="controls">
|
||||
<button disabled={!loaded || !changed} onclick={() => void write(false)}><Icon icon="save" />{$t("Save image appearance")}</button>
|
||||
<button disabled={!loaded || !saved.images[selected]} onclick={() => void write(true)}><Icon icon="undo" />{$t("Reset image appearance")}</button>
|
||||
<button onclick={() => void load()}><Icon icon="refresh" />{$t("Reload image settings")}</button>
|
||||
</div>
|
||||
</fieldset>
|
||||
{#if status.text}<p role={status.error ? "alert" : "status"} class:error={status.error}>{status.text}</p>{/if}
|
||||
</details>
|
||||
|
||||
<style>
|
||||
.image-editor { display: grid; gap: var(--rs-settings-gap); min-width: 0; padding: var(--rs-settings-row-padding); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); }
|
||||
summary { cursor: pointer; min-height: var(--rs-settings-control-height); line-height: var(--rs-settings-control-height); border-radius: var(--rs-control-radius); }
|
||||
p { margin: 0; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); line-height: 1.5; overflow-wrap: anywhere; }
|
||||
.error { color: var(--rs-error); }
|
||||
fieldset { display: grid; gap: var(--rs-settings-gap); min-width: 0; margin: var(--rs-settings-gap) 0 0; padding: 0; border: 0; }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
.controls { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); min-width: 0; }
|
||||
button:not(.rs-picker-row), input:not([type=range]) { min-height: var(--rs-settings-control-height); box-sizing: border-box; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font: inherit; }
|
||||
button:not(.rs-picker-row) { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
|
||||
button:not(.rs-picker-row):hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
button:disabled, input:disabled { opacity: .55; cursor: default; }
|
||||
button :global(svg) { width: 14px; height: 14px; flex-shrink: 0; fill: none; stroke: currentColor; stroke-width: 2; }
|
||||
:is(button, input, summary):focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 2px; }
|
||||
.choice { max-width: 100%; min-width: 0; }
|
||||
.choice .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
input[type=number] { width: 72px; }
|
||||
input[type=range] { width: 160px; max-width: 100%; accent-color: var(--rs-accent); }
|
||||
.image-picker { display: grid; gap: var(--rs-settings-gap); width: 100%; min-width: 0; position: static; }
|
||||
.image-picker input { width: 100%; min-width: 0; }
|
||||
.options { display: grid; gap: 2px; max-height: 220px; overflow: auto; min-width: 0; }
|
||||
.options button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; }
|
||||
.preview { position: relative; width: 100%; height: 170px; overflow: hidden; border-radius: var(--rs-control-radius); background-color: var(--rs-bg-active); }
|
||||
.fill, .foreground, .shade { position: absolute; inset: 0; background-repeat: no-repeat; pointer-events: none; }
|
||||
.fill { inset: -24px; filter: blur(18px); background-size: cover; background-position: center; }
|
||||
</style>
|
||||
@@ -0,0 +1,83 @@
|
||||
// The blurred fill of a portrait image. One worker does the decode, the resize, and the filter away from the
|
||||
// input and paint work of the window. It lives as long as the Background instance.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
|
||||
const workerSource = `
|
||||
self.onmessage = async ({ data: { id, url, width, height } }) => {
|
||||
let image;
|
||||
try {
|
||||
const source = await (await fetch(url)).blob();
|
||||
image = await createImageBitmap(source, { resizeWidth: width, resizeHeight: height, resizeQuality: 'high' });
|
||||
const canvas = new OffscreenCanvas(width, height);
|
||||
const context = canvas.getContext('2d');
|
||||
context.filter = 'blur(24px)';
|
||||
context.drawImage(image, -48, -48, width + 96, height + 96);
|
||||
self.postMessage({ id, blob: await canvas.convertToBlob({ type: 'image/png' }) });
|
||||
} catch (error) {
|
||||
self.postMessage({ id, error: error instanceof Error ? error.message : String(error) });
|
||||
} finally { image?.close(); }
|
||||
};`;
|
||||
|
||||
/** The size of the blurred copy. Its long side is at most 1024 pixels. */
|
||||
export function blurSize(width: number, height: number): { width: number; height: number } {
|
||||
const scale = Math.min(1, 1024 / Math.max(width, height, 1));
|
||||
return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
|
||||
}
|
||||
|
||||
export class BlurWorker {
|
||||
private worker?: Worker;
|
||||
private workerUrl?: string;
|
||||
private serial = 0;
|
||||
private pending = new Map<number, { resolve: (blob: Blob) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
|
||||
|
||||
/** A blob URL of the blurred copy of the image at `url`. The caller releases it. */
|
||||
async blur(url: string, width: number, height: number): Promise<string> {
|
||||
const size = blurSize(width, height);
|
||||
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined") return URL.createObjectURL(await this.inWindow(url, size));
|
||||
const worker = this.start();
|
||||
const id = ++this.serial;
|
||||
const blob = await new Promise<Blob>((resolve, reject) => {
|
||||
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(tr("The blurred image took too long to load."))); }, 10000);
|
||||
this.pending.set(id, { resolve, reject, timer });
|
||||
worker.postMessage({ id, url, ...size });
|
||||
});
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
private start(): Worker {
|
||||
if (this.worker) return this.worker;
|
||||
this.workerUrl = URL.createObjectURL(new Blob([workerSource], { type: "text/javascript" }));
|
||||
const worker = this.worker = new Worker(this.workerUrl);
|
||||
worker.onmessage = ({ data }) => {
|
||||
const request = this.pending.get(data?.id);
|
||||
if (!request) return;
|
||||
this.pending.delete(data.id); clearTimeout(request.timer);
|
||||
if (data.blob instanceof Blob) request.resolve(data.blob);
|
||||
else request.reject(new Error(data.error || tr("Cannot create the blurred image.")));
|
||||
};
|
||||
worker.onerror = () => this.fail(new Error(tr("Cannot create the blurred image.")));
|
||||
return worker;
|
||||
}
|
||||
|
||||
/** A fallback for a window without OffscreenCanvas. */
|
||||
private async inWindow(url: string, size: { width: number; height: number }): Promise<Blob> {
|
||||
const image = new Image(); image.src = url; await image.decode();
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = size.width; canvas.height = size.height;
|
||||
const context = canvas.getContext("2d")!;
|
||||
context.filter = "blur(24px)";
|
||||
context.drawImage(image, -48, -48, size.width + 96, size.height + 96);
|
||||
return new Promise<Blob>((resolve, reject) => canvas.toBlob(value => value ? resolve(value) : reject(new Error(tr("Cannot create the blurred image."))), "image/png"));
|
||||
}
|
||||
|
||||
private fail(error: Error) {
|
||||
for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
|
||||
this.pending.clear();
|
||||
// A failed worker starts again at the next request.
|
||||
this.worker?.terminate(); this.worker = undefined;
|
||||
if (this.workerUrl) URL.revokeObjectURL(this.workerUrl);
|
||||
this.workerUrl = undefined;
|
||||
}
|
||||
|
||||
dispose() { this.fail(new Error(tr("This feature is off."))); }
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
// The Background engine: it shows the images of a source as background frames, one after the other.
|
||||
// It comes from the engine of the Background Slideshow plugin, with these changes for the open card
|
||||
// "Lag before image transition": the next image loads and decodes before its fade, the blurred fills of the
|
||||
// last images stay in a cache, and the folder list and the sidecar are read again only after a settings change,
|
||||
// on window focus, or after every 10 images.
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { BackgroundFrame } from "../../plugins/backgroundContracts.ts";
|
||||
import type { BackgroundLayout } from "../backgroundSettings.ts";
|
||||
import { imageAppearance, imageNames, parseImageSettings, sequence, type ImageAppearance, type ImageSettings } from "./imageSettings.ts";
|
||||
|
||||
/** The time of the fade from one image to the next. */
|
||||
export const transitionMs = 2000;
|
||||
/** The folder list and the sidecar are read again after this number of images. */
|
||||
export const RESCAN_SLIDES = 10;
|
||||
/** The number of blurred fills that stay in the cache. */
|
||||
export const BLUR_CACHE = 3;
|
||||
/** The shortest wait before a new try after an error. */
|
||||
export const RETRY_MS = 5000;
|
||||
|
||||
/** Where the images come from: the image folder of the host, or the one saved image. */
|
||||
export interface ImageSource {
|
||||
/** A different key means a different folder or image. The engine then starts again. */
|
||||
readonly key: string;
|
||||
/** True for a folder: the images change on a timer, and the sidecar and the portrait default apply. */
|
||||
readonly timed: boolean;
|
||||
/** The image names. */
|
||||
list(): Promise<string[]>;
|
||||
read(name: string): Promise<Blob>;
|
||||
/** The text of the sidecar file, or null. */
|
||||
sidecar(): Promise<string | null>;
|
||||
}
|
||||
|
||||
export interface LoadedImage { url: string; width: number; height: number }
|
||||
|
||||
/** The browser services of the engine. Tests replace them. */
|
||||
export interface Runtime {
|
||||
/** Make a blob URL and decode the image before it shows. */
|
||||
load(blob: Blob): Promise<LoadedImage>;
|
||||
/** Make the blurred fill of a loaded image. The engine releases the URL. */
|
||||
blur(image: LoadedImage): Promise<string>;
|
||||
release(url: string): void;
|
||||
later(callback: () => void, milliseconds: number): unknown;
|
||||
cancel(timer: unknown): void;
|
||||
random(): number;
|
||||
now(): number;
|
||||
}
|
||||
|
||||
export interface Frames { set(target: string, frame: BackgroundFrame | null): void }
|
||||
|
||||
export interface EngineSettings extends BackgroundLayout {
|
||||
seconds: number;
|
||||
order: "name" | "random";
|
||||
paused: boolean;
|
||||
targets: string[];
|
||||
}
|
||||
|
||||
export interface Status { message: string; image: string | null; count: number; error: boolean }
|
||||
|
||||
interface Shown { name: string; key: string; image: LoadedImage; appearance: ImageAppearance; blurred?: string }
|
||||
interface Prepared { name: string; key: string; image: LoadedImage }
|
||||
|
||||
function toFrame(shown: Shown): BackgroundFrame {
|
||||
const frame: BackgroundFrame = { url: shown.image.url, overlay: shown.appearance.overlay, position: shown.appearance.position,
|
||||
size: shown.appearance.fit === "blurred" ? "contain" : shown.appearance.fit };
|
||||
if (shown.blurred) frame.blurredUrl = shown.blurred;
|
||||
return frame;
|
||||
}
|
||||
|
||||
const sameAppearance = (a: ImageAppearance, b: ImageAppearance) => a.fit === b.fit && a.position === b.position && a.overlay === b.overlay;
|
||||
|
||||
export class Slideshow {
|
||||
status: Status = { message: "", image: null, count: 0, error: false };
|
||||
private source: ImageSource | null = null;
|
||||
private settings: EngineSettings | null = null;
|
||||
private revision = 0;
|
||||
private stopped = false;
|
||||
private timer: unknown;
|
||||
/** When the current timer fires, or null without a timer. */
|
||||
private due: number | null = null;
|
||||
private names: string[] | null = null;
|
||||
private imageSettings: ImageSettings = { schema: 1, images: {} };
|
||||
private sidecarError = "";
|
||||
private stale = true;
|
||||
private slides = 0;
|
||||
private shown: Shown | null = null;
|
||||
/** The image that the current frame fades from. */
|
||||
private previous: Shown | null = null;
|
||||
private targets = new Set<string>();
|
||||
/** The blurred fills, oldest first. */
|
||||
private blurs = new Map<string, string>();
|
||||
private prepared: { name: string; work: Promise<Prepared | null>; discarded: boolean } | null = null;
|
||||
/** Changes at each `clear`, so that a late blurred fill of an old image does not enter the cache. */
|
||||
private epoch = 0;
|
||||
private listeners = new Set<() => void>();
|
||||
private frames: Frames;
|
||||
private runtime: Runtime;
|
||||
|
||||
constructor(frames: Frames, runtime: Runtime) { this.frames = frames; this.runtime = runtime; }
|
||||
|
||||
subscribe(listener: () => void) { this.listeners.add(listener); return () => { this.listeners.delete(listener); }; }
|
||||
private notify() { for (const listener of [...this.listeners]) listener(); }
|
||||
|
||||
/** Use a new source or new settings. The current image stays when the source is the same and still has it. */
|
||||
configure(source: ImageSource | null, settings: EngineSettings): Promise<void> {
|
||||
if (this.stopped) return Promise.resolve();
|
||||
if (source?.key !== this.source?.key) {
|
||||
this.clear();
|
||||
this.names = null;
|
||||
}
|
||||
this.source = source;
|
||||
this.settings = { ...settings, targets: [...settings.targets] };
|
||||
this.stale = true;
|
||||
return this.update(false);
|
||||
}
|
||||
|
||||
/** Read the list and the sidecar again before the next image, for example after a window focus. */
|
||||
invalidate() { this.stale = true; }
|
||||
|
||||
/** Read the list and the sidecar again now, and apply them to the current image. */
|
||||
reload = () => { this.stale = true; return this.update(false); };
|
||||
|
||||
/** Show the next image now. */
|
||||
next = () => this.update(true);
|
||||
|
||||
dispose() {
|
||||
if (this.stopped) return;
|
||||
this.stopped = true; this.revision++;
|
||||
this.runtime.cancel(this.timer); this.timer = undefined;
|
||||
this.clear(); this.listeners.clear();
|
||||
}
|
||||
|
||||
private async update(advance: boolean): Promise<void> {
|
||||
if (this.stopped) return;
|
||||
const revision = ++this.revision;
|
||||
const remaining = this.due === null ? null : Math.max(0, this.due - this.runtime.now());
|
||||
this.runtime.cancel(this.timer); this.timer = undefined; this.due = null;
|
||||
const valid = () => !this.stopped && revision === this.revision;
|
||||
const source = this.source, settings = this.settings;
|
||||
try {
|
||||
if (!source || !settings) { this.clear(); this.setStatus(tr("Choose a folder or an image to show a background.")); return; }
|
||||
if (!settings.targets.length) { this.clear(); this.setStatus(tr("Select where to show the background.")); return; }
|
||||
if (this.stale || !this.names) {
|
||||
const [list, sidecar] = await Promise.all([source.list(), source.timed ? source.sidecar() : Promise.resolve(null)]);
|
||||
if (!valid()) return;
|
||||
this.names = source.timed ? imageNames(list) : [...list];
|
||||
try { this.imageSettings = parseImageSettings(sidecar); this.sidecarError = ""; }
|
||||
catch (reason) { this.imageSettings = { schema: 1, images: {} }; this.sidecarError = reason instanceof Error ? reason.message : String(reason); }
|
||||
this.stale = false; this.slides = 0;
|
||||
if (this.prepared && !this.names.includes(this.prepared.name)) this.discardPrepared();
|
||||
}
|
||||
const names = this.names;
|
||||
this.status.count = names.length;
|
||||
if (!names.length) throw new Error(tr("No supported images in this folder. Add PNG, JPEG, GIF, or WebP files."));
|
||||
const shown = this.shown;
|
||||
if (shown && names.includes(shown.name) && (!advance || names.length === 1)) {
|
||||
await this.reapply(shown, settings, valid);
|
||||
if (!valid()) return;
|
||||
this.schedule(remaining ?? settings.seconds * 1000, revision);
|
||||
this.prepare();
|
||||
return;
|
||||
}
|
||||
let failures = 0;
|
||||
const order = sequence(names, shown?.name ?? null, settings.order, this.runtime.random);
|
||||
const candidates = this.prepared && order.includes(this.prepared.name) ? [this.prepared.name, ...order.filter(name => name !== this.prepared!.name)] : order;
|
||||
for (const name of candidates) {
|
||||
let loaded: Prepared | null = null;
|
||||
let next: Shown;
|
||||
try {
|
||||
loaded = await this.load(name);
|
||||
if (!valid()) { if (loaded) this.runtime.release(loaded.image.url); return; }
|
||||
if (!loaded) throw new Error(tr("The image cannot be displayed."));
|
||||
next = { ...loaded, appearance: this.appearanceOf(name, loaded.image, settings) };
|
||||
if (next.appearance.fit === "blurred") {
|
||||
next.blurred = await this.blurOf(loaded);
|
||||
if (!valid()) { this.runtime.release(loaded.image.url); return; }
|
||||
}
|
||||
} catch {
|
||||
if (loaded) this.runtime.release(loaded.image.url);
|
||||
if (!valid()) return;
|
||||
failures++; continue;
|
||||
}
|
||||
this.publish(next, settings, true);
|
||||
const message = failures ? tr("{name}: skipped {count} unreadable images.", { name, count: failures }) : name;
|
||||
this.status = { image: name, count: names.length, error: !!this.sidecarError, message: this.sidecarError ? `${message} ${this.sidecarError}` : message };
|
||||
this.notify();
|
||||
if (++this.slides >= RESCAN_SLIDES) this.stale = true;
|
||||
this.schedule(settings.seconds * 1000, revision);
|
||||
this.prepare();
|
||||
return;
|
||||
}
|
||||
throw new Error(tr("No readable images in this folder. Check the image files."));
|
||||
} catch (error) {
|
||||
if (!valid()) return;
|
||||
this.clear();
|
||||
this.status = { ...this.status, image: null, error: true, message: error instanceof Error ? error.message : String(error) };
|
||||
this.notify();
|
||||
if (source?.timed && settings) this.schedule(Math.max(RETRY_MS, settings.seconds * 1000), revision, true);
|
||||
}
|
||||
}
|
||||
|
||||
private setStatus(message: string) {
|
||||
this.status = { message, image: null, count: 0, error: false };
|
||||
this.notify();
|
||||
}
|
||||
|
||||
private appearanceOf(name: string, image: LoadedImage, settings: EngineSettings): ImageAppearance {
|
||||
if (!this.source?.timed) return { fit: settings.size, position: settings.position, overlay: settings.overlay };
|
||||
return imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||
}
|
||||
|
||||
/** The image of `name`: the prepared image when it matches, or a new read. */
|
||||
private async load(name: string): Promise<Prepared | null> {
|
||||
const prepared = this.prepared;
|
||||
if (prepared?.name === name) {
|
||||
this.prepared = null;
|
||||
const result = await prepared.work.catch(() => null);
|
||||
if (result) return result;
|
||||
}
|
||||
const source = this.source!;
|
||||
const blob = await source.read(name);
|
||||
const image = await this.runtime.load(blob);
|
||||
return { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||
}
|
||||
|
||||
/** Load and decode the next image of a timed source now, so that its fade starts on time. */
|
||||
private prepare() {
|
||||
const source = this.source, settings = this.settings, names = this.names, shown = this.shown;
|
||||
if (!source?.timed || !settings || settings.paused || !names || names.length < 2 || !shown || this.prepared) return;
|
||||
const name = sequence(names, shown.name, settings.order, this.runtime.random)[0];
|
||||
const entry: { name: string; work: Promise<Prepared | null>; discarded: boolean } = { name, work: Promise.resolve(null), discarded: false };
|
||||
entry.work = (async (): Promise<Prepared | null> => {
|
||||
const blob = await source.read(name);
|
||||
const image = await this.runtime.load(blob);
|
||||
// A prepared image that nobody wants any more goes away at once.
|
||||
if (this.stopped || entry.discarded) { this.runtime.release(image.url); return null; }
|
||||
const result = { name, key: `${source.key}\n${name}\n${blob.size}`, image };
|
||||
const appearance = imageAppearance(settings, this.imageSettings.images[name], image.height > image.width);
|
||||
if (appearance.fit === "blurred") await this.blurOf(result).catch(() => undefined);
|
||||
return result;
|
||||
})();
|
||||
entry.work.catch(() => undefined);
|
||||
this.prepared = entry;
|
||||
}
|
||||
|
||||
private discardPrepared() {
|
||||
const prepared = this.prepared;
|
||||
this.prepared = null;
|
||||
if (!prepared) return;
|
||||
prepared.discarded = true;
|
||||
void prepared.work.then(result => { if (result) this.runtime.release(result.image.url); }, () => undefined);
|
||||
}
|
||||
|
||||
/** The blurred fill of an image, from the cache when possible. */
|
||||
private async blurOf(image: Prepared): Promise<string> {
|
||||
const cached = this.blurs.get(image.key);
|
||||
if (cached) { this.blurs.delete(image.key); this.blurs.set(image.key, cached); return cached; }
|
||||
const epoch = this.epoch;
|
||||
const url = await this.runtime.blur(image.image);
|
||||
if (this.stopped || epoch !== this.epoch) { this.runtime.release(url); throw new Error(tr("The background changed.")); }
|
||||
const again = this.blurs.get(image.key);
|
||||
if (again) { this.runtime.release(url); return again; }
|
||||
this.blurs.set(image.key, url);
|
||||
this.trimBlurs(url);
|
||||
return url;
|
||||
}
|
||||
|
||||
/** Release the oldest blurred fills beyond the cache size. Fills that a frame shows stay. */
|
||||
private trimBlurs(keep?: string) {
|
||||
const used = new Set([this.shown?.blurred, this.previous?.blurred, keep]);
|
||||
for (const [key, url] of this.blurs) {
|
||||
if (this.blurs.size <= BLUR_CACHE) break;
|
||||
if (used.has(url)) continue;
|
||||
this.blurs.delete(key); this.runtime.release(url);
|
||||
}
|
||||
}
|
||||
|
||||
/** Apply new settings or new image settings to the image that shows, without a fade. */
|
||||
private async reapply(shown: Shown, settings: EngineSettings, valid: () => boolean) {
|
||||
const appearance = this.appearanceOf(shown.name, shown.image, settings);
|
||||
const sameTargets = settings.targets.length === this.targets.size && settings.targets.every(target => this.targets.has(target));
|
||||
const needsBlur = appearance.fit === "blurred" && !shown.blurred;
|
||||
if (sameTargets && sameAppearance(appearance, shown.appearance) && !needsBlur) return;
|
||||
const next: Shown = { ...shown, appearance, blurred: undefined };
|
||||
if (appearance.fit === "blurred") {
|
||||
next.blurred = await this.blurOf(shown);
|
||||
if (!valid()) return;
|
||||
}
|
||||
this.publish(next, settings, false);
|
||||
this.notify();
|
||||
}
|
||||
|
||||
/** Show `next` on every target. With `fade`, the frame fades from the image that showed before. */
|
||||
private publish(next: Shown, settings: EngineSettings, fade: boolean) {
|
||||
const old = this.shown;
|
||||
const frame = toFrame(next);
|
||||
if (fade && old) { frame.previous = toFrame(old); frame.transitionMs = transitionMs; }
|
||||
try {
|
||||
for (const target of this.targets) if (!settings.targets.includes(target)) this.frames.set(target, null);
|
||||
// Track the new targets before the frames go out, so that a cleanup also clears a partial publish.
|
||||
for (const target of settings.targets) this.targets.add(target);
|
||||
for (const target of settings.targets) this.frames.set(target, frame);
|
||||
} catch (error) {
|
||||
if (next.image !== old?.image) this.runtime.release(next.image.url);
|
||||
throw error;
|
||||
}
|
||||
this.targets = new Set(settings.targets);
|
||||
// Keep the image of the fade until the next frame replaces it.
|
||||
const release = this.previous;
|
||||
if (release && release.image !== next.image && release.image !== old?.image) this.runtime.release(release.image.url);
|
||||
this.previous = fade && old && old.image !== next.image ? old : null;
|
||||
if (!fade && old && old.image !== next.image) this.runtime.release(old.image.url);
|
||||
this.shown = next;
|
||||
this.trimBlurs();
|
||||
}
|
||||
|
||||
/** Remove the frames of every target and release every image. */
|
||||
private clear() {
|
||||
for (const target of this.targets) { try { this.frames.set(target, null); } catch { /* The window can close before the cleanup. */ } }
|
||||
this.targets.clear();
|
||||
const images = new Set([this.shown?.image.url, this.previous?.image.url]);
|
||||
for (const url of images) if (url) this.runtime.release(url);
|
||||
for (const url of this.blurs.values()) this.runtime.release(url);
|
||||
this.blurs.clear();
|
||||
this.epoch++;
|
||||
this.discardPrepared();
|
||||
this.shown = null; this.previous = null;
|
||||
this.status = { ...this.status, image: null };
|
||||
}
|
||||
|
||||
private schedule(milliseconds: number, revision: number, retry = false) {
|
||||
const settings = this.settings;
|
||||
if (this.stopped || this.revision !== revision || !this.source?.timed || !settings) return;
|
||||
if (settings.paused && !retry) return;
|
||||
this.due = this.runtime.now() + milliseconds;
|
||||
this.timer = this.runtime.later(() => { this.timer = undefined; this.due = null; void this.update(true); }, milliseconds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// The per-image settings: the sidecar file `.runestone-backgrounds.json` in the image folder.
|
||||
// The Background Slideshow plugin used the same file, so the settings of each image stay.
|
||||
import { BACKGROUND_POSITIONS } from "../../theme/appearance.ts";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import type { BackgroundLayout, BackgroundPosition } from "../backgroundSettings.ts";
|
||||
|
||||
export const sidecarName = ".runestone-backgrounds.json";
|
||||
/** `blurred` shows the full image over a blurred copy that fills the view. Portrait images use it by default. */
|
||||
export const imageFits = ["cover", "contain", "auto", "blurred"] as const;
|
||||
export type ImageFit = typeof imageFits[number];
|
||||
export interface ImageAppearance { fit: ImageFit; position: BackgroundPosition; overlay: number }
|
||||
/** Unknown keys of the file and of each image stay when RuneStone saves the file. */
|
||||
export interface ImageSettings { schema: 1; images: Record<string, Partial<ImageAppearance>>; [key: string]: unknown }
|
||||
|
||||
/** Read the sidecar text. `null` (no file) gives empty settings. Invalid settings throw an error. */
|
||||
export function parseImageSettings(source: string | null): ImageSettings {
|
||||
if (source === null) return { schema: 1, images: {} };
|
||||
const value = JSON.parse(source);
|
||||
if (!value || value.schema !== 1 || !value.images || typeof value.images !== "object" || Array.isArray(value.images)) {
|
||||
throw new Error(tr("The image settings file must use schema 1 and an images object."));
|
||||
}
|
||||
for (const [name, raw] of Object.entries(value.images)) {
|
||||
const appearance = raw as Partial<ImageAppearance>;
|
||||
if (!name || /[\\/]/.test(name) || !appearance || typeof appearance !== "object" || Array.isArray(appearance)
|
||||
|| ("fit" in appearance && !imageFits.includes(appearance.fit!))
|
||||
|| ("position" in appearance && !BACKGROUND_POSITIONS.includes(appearance.position!))
|
||||
|| ("overlay" in appearance && (typeof appearance.overlay !== "number" || !Number.isFinite(appearance.overlay) || Math.abs(appearance.overlay) > 1))) {
|
||||
throw new Error(tr("Invalid image settings for {name}.", { name }));
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The appearance of one image: the folder layout, the portrait default, then the saved values of the image. */
|
||||
export function imageAppearance(layout: BackgroundLayout, override: Partial<ImageAppearance> | undefined, portrait: boolean): ImageAppearance {
|
||||
return { fit: portrait ? "blurred" : layout.size, position: layout.position, overlay: layout.overlay, ...override };
|
||||
}
|
||||
|
||||
/** The supported image names, without duplicates, in natural order. */
|
||||
export function imageNames(names: readonly string[]): string[] {
|
||||
return [...new Set(names.filter(name => !/[\\/]/.test(name) && /\.(png|jpe?g|gif|webp)$/i.test(name)))]
|
||||
.sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }) || a.localeCompare(b, "en"));
|
||||
}
|
||||
|
||||
/** The order of the next images after `current`. A random order puts the current image last. */
|
||||
export function sequence(names: readonly string[], current: string | null, order: "name" | "random", random = Math.random): string[] {
|
||||
if (order === "name") {
|
||||
const index = current === null ? -1 : names.indexOf(current);
|
||||
return [...names.slice(index + 1), ...names.slice(0, index + 1)];
|
||||
}
|
||||
const rest = names.filter(name => name !== current);
|
||||
for (let i = rest.length - 1; i > 0; i--) {
|
||||
const j = Math.min(i, Math.max(0, Math.floor(random() * (i + 1))));
|
||||
[rest[i], rest[j]] = [rest[j], rest[i]];
|
||||
}
|
||||
return current && names.includes(current) ? [...rest, current] : rest;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// The Background feature. `loader.ts` imports this module when a folder or an image is selected (`launch.ts`),
|
||||
// at a palette command, or when Appearance → Background shows its settings.
|
||||
// It shows the images through `backgroundHub`, so the workarea, browser tabs, and Project Management boards get the frames.
|
||||
import { mount, unmount } from "svelte";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { backgroundHub } from "../../plugins/backgrounds.ts";
|
||||
import { readAppearance } from "../../theme/appearance.ts";
|
||||
import { hasImage, normalizeLayout, onBackgroundChange, readBackground, writeBackground } from "../backgroundSettings.ts";
|
||||
import type { FeatureContext, FeatureInstance } from "../types.ts";
|
||||
import { BlurWorker } from "./blur.ts";
|
||||
import { Slideshow, type ImageSource } from "./engine.ts";
|
||||
import { browserRuntime, folderHost, folderSource, imageSource, onBackgroundCommand, sendBackgroundCommand } from "./sources.ts";
|
||||
import BackgroundSettings from "./BackgroundSettings.svelte";
|
||||
|
||||
export function start(_context: FeatureContext): FeatureInstance {
|
||||
const owner = Symbol("background");
|
||||
const blur = new BlurWorker();
|
||||
const engine = new Slideshow({ set: (target, frame) => backgroundHub.set(owner, target, frame) }, browserRuntime(blur));
|
||||
/** The host folder for display. `undefined` until the first read. */
|
||||
let folder: string | null | undefined;
|
||||
let generation = 0;
|
||||
let disposed = false;
|
||||
/** The last source and settings. A change of another appearance setting, such as the theme, gives the same value. */
|
||||
let applied = "";
|
||||
|
||||
/** Give the engine the current source and settings. `reread` asks the host for its folder again. */
|
||||
async function apply(reread: boolean) {
|
||||
const run = ++generation;
|
||||
const settings = readBackground();
|
||||
const appearance = readAppearance();
|
||||
let source: ImageSource | null = null;
|
||||
let layout = normalizeLayout(settings);
|
||||
if (settings.source === "folder") {
|
||||
if (reread || folder === undefined) {
|
||||
try { folder = await folderHost.current(); } catch { folder = null; }
|
||||
if (disposed || run !== generation) return;
|
||||
}
|
||||
source = folder ? folderSource(folder) : null;
|
||||
} else if (settings.source === "image" && hasImage(appearance)) {
|
||||
source = imageSource(appearance.newTabBackground!);
|
||||
layout = normalizeLayout(appearance.newTabBackground);
|
||||
}
|
||||
const next = { ...settings, ...layout };
|
||||
const signature = JSON.stringify([source?.key ?? null, next]);
|
||||
if (!reread && signature === applied) return;
|
||||
applied = signature;
|
||||
await engine.configure(source, next);
|
||||
}
|
||||
|
||||
const stopSettings = onBackgroundChange(() => { void apply(false); });
|
||||
const stopCommands = onBackgroundCommand(command => {
|
||||
if (command === "next") void engine.next();
|
||||
else { engine.invalidate(); void apply(true); }
|
||||
});
|
||||
// Another window or program can change the folder. A focus reads the folder, the list, and the sidecar again.
|
||||
const focus = () => { engine.invalidate(); void apply(true); };
|
||||
window.addEventListener("focus", focus);
|
||||
void apply(true);
|
||||
|
||||
return {
|
||||
mount() { throw new Error(tr("This view is unavailable.")); },
|
||||
async run(command) {
|
||||
if (command === "next") await sendBackgroundCommand("next");
|
||||
else if (command === "pause") {
|
||||
const settings = readBackground();
|
||||
await writeBackground({ ...settings, paused: !settings.paused });
|
||||
} else throw new Error(tr("This command is unavailable."));
|
||||
},
|
||||
dispose() {
|
||||
disposed = true; generation++;
|
||||
stopSettings(); stopCommands();
|
||||
window.removeEventListener("focus", focus);
|
||||
engine.dispose();
|
||||
blur.dispose();
|
||||
backgroundHub.removeOwner(owner);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The settings of Appearance → Background. They work also in a window where Background does not run. */
|
||||
export function mountSettings(element: HTMLElement) {
|
||||
const component = mount(BackgroundSettings, { target: element });
|
||||
return () => { void unmount(component); };
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// The image sources of Background, the host folder commands (`src-tauri/src/backgrounds.rs`), the browser runtime of the
|
||||
// engine, and the commands that reach the Background instance of every window.
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { emit, listen } from "@tauri-apps/api/event";
|
||||
import { tr } from "../../i18n/index.ts";
|
||||
import { readBackgroundImage } from "../../theme/backgroundImages.ts";
|
||||
import type { Appearance } from "../../theme/appearance.ts";
|
||||
import type { BlurWorker } from "./blur.ts";
|
||||
import type { ImageSource, LoadedImage, Runtime } from "./engine.ts";
|
||||
|
||||
const types: Record<string, string> = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp" };
|
||||
const typeOf = (name: string) => types[name.split(".").pop()!.toLowerCase()] ?? "application/octet-stream";
|
||||
|
||||
/** The host commands of the image folder. The host keeps the folder, so no command takes a path. */
|
||||
export const folderHost = {
|
||||
/** Show the folder dialog. Returns the chosen folder for display, or null after Cancel. */
|
||||
choose: (title: string) => invoke<string | null>("background_choose_folder", { title }),
|
||||
/** The current folder for display, or null. */
|
||||
current: () => invoke<string | null>("background_folder"),
|
||||
clear: () => invoke<void>("background_clear_folder"),
|
||||
list: () => invoke<string[]>("background_list"),
|
||||
read: async (name: string): Promise<Blob> => {
|
||||
const bytes = await invoke<ArrayBuffer | Uint8Array | number[]>("background_read", { name });
|
||||
return new Blob([bytes instanceof ArrayBuffer ? bytes : Uint8Array.from(bytes)], { type: typeOf(name) });
|
||||
},
|
||||
readSidecar: () => invoke<string | null>("background_read_sidecar"),
|
||||
writeSidecar: (contents: string, expected: string | null) => invoke<void>("background_write_sidecar", { contents, expected }),
|
||||
};
|
||||
|
||||
/** The images of the host folder. `folder` is the path for display. It makes the key, so another folder starts again. */
|
||||
export function folderSource(folder: string): ImageSource {
|
||||
return { key: `folder:${folder}`, timed: true, list: folderHost.list, read: folderHost.read, sidecar: folderHost.readSidecar };
|
||||
}
|
||||
|
||||
/** The saved image of Appearance, from IndexedDB or from an old data URL. */
|
||||
export async function readSavedImage(background: NonNullable<Appearance["newTabBackground"]>): Promise<Blob> {
|
||||
if (background.imageId) {
|
||||
const blob = await readBackgroundImage(background.imageId);
|
||||
if (!blob) throw new Error(tr("The saved background image is missing. Choose the image again."));
|
||||
return blob;
|
||||
}
|
||||
const image = background.image ?? "";
|
||||
const [header, data] = image.split(",");
|
||||
const bytes = Uint8Array.from(atob(data ?? ""), character => character.charCodeAt(0));
|
||||
return new Blob([bytes], { type: header.slice(5, header.indexOf(";")) });
|
||||
}
|
||||
|
||||
/** A short hash of a data URL, so that another old image gets another key. */
|
||||
function hash(text: string): string {
|
||||
let value = 0x811c9dc5;
|
||||
for (let index = 0; index < text.length; index++) value = Math.imul(value ^ text.charCodeAt(index), 0x01000193);
|
||||
return (value >>> 0).toString(16);
|
||||
}
|
||||
|
||||
/** The one saved image. It has no timer. */
|
||||
export function imageSource(background: NonNullable<Appearance["newTabBackground"]>): ImageSource {
|
||||
const id = background.imageId ?? `data:${background.image?.length ?? 0}:${hash(background.image ?? "")}`;
|
||||
return { key: `image:${id}`, timed: false, list: async () => ["image"], read: () => readSavedImage(background), sidecar: async () => null };
|
||||
}
|
||||
|
||||
/** Make a blob URL and decode the image before it shows, so the fade does not wait for the decode. */
|
||||
export async function loadImage(blob: Blob): Promise<LoadedImage> {
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const image = new Image();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
image.src = url;
|
||||
await Promise.race([image.decode(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error(tr("The image took too long to load."))), 10000); })])
|
||||
.finally(() => clearTimeout(timer));
|
||||
return { url, width: image.naturalWidth, height: image.naturalHeight };
|
||||
} catch (error) { URL.revokeObjectURL(url); throw error; }
|
||||
}
|
||||
|
||||
export function browserRuntime(blur: BlurWorker): Runtime {
|
||||
return {
|
||||
load: loadImage,
|
||||
blur: image => blur.blur(image.url, image.width, image.height),
|
||||
release: url => URL.revokeObjectURL(url),
|
||||
later: (callback, milliseconds) => setTimeout(callback, milliseconds),
|
||||
cancel: timer => clearTimeout(timer as ReturnType<typeof setTimeout>),
|
||||
random: Math.random,
|
||||
now: () => Date.now(),
|
||||
};
|
||||
}
|
||||
|
||||
/** `next` shows the next image. `reload` reads the folder, the list, and the sidecar again. */
|
||||
export type BackgroundCommand = "next" | "reload";
|
||||
const EVENT = "background-command";
|
||||
|
||||
/** Send a command to the Background instance of every window, this window too. */
|
||||
export async function sendBackgroundCommand(command: BackgroundCommand): Promise<void> {
|
||||
if (isTauri()) await emit(EVENT, command);
|
||||
else window.dispatchEvent(new CustomEvent(EVENT, { detail: command }));
|
||||
}
|
||||
|
||||
/** Receive the commands of every window. Returns the function that stops it. */
|
||||
export function onBackgroundCommand(listener: (command: BackgroundCommand) => void): () => void {
|
||||
const accept = (value: unknown) => { if (value === "next" || value === "reload") listener(value); };
|
||||
if (!isTauri()) {
|
||||
const handle = (event: Event) => accept((event as CustomEvent).detail);
|
||||
window.addEventListener(EVENT, handle);
|
||||
return () => window.removeEventListener(EVENT, handle);
|
||||
}
|
||||
let stopped = false;
|
||||
let off: (() => void) | undefined;
|
||||
void listen<unknown>(EVENT, event => accept(event.payload)).then(unlisten => { if (stopped) unlisten(); else off = unlisten; }, () => undefined);
|
||||
return () => { stopped = true; off?.(); };
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// The settings of the Background feature: the `background` section of the settings file.
|
||||
// This file is in the main bundle, because the launch rule and the first-start migration need it without the feature code.
|
||||
// The image source keeps its image and its layout in `appearance.newTabBackground`, so an older version still shows it.
|
||||
// The host keeps the image folder itself (`src-tauri/src/backgrounds.rs`). The interface never sends a folder path.
|
||||
import { onSettingsChange, readSection, writeSection } from "../settings/store.ts";
|
||||
import { BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, type Appearance } from "../theme/appearance.ts";
|
||||
import type { LegacyPlugin } from "./migration.ts";
|
||||
|
||||
export const BACKGROUND_SOURCES = ["folder", "image", "none"] as const;
|
||||
export type BackgroundSource = typeof BACKGROUND_SOURCES[number];
|
||||
export type BackgroundPosition = typeof BACKGROUND_POSITIONS[number];
|
||||
export type BackgroundSize = typeof BACKGROUND_SIZES[number];
|
||||
/** The views that show the background: the workspace, all Project Management boards, or one board. */
|
||||
export const BACKGROUND_TARGET = /^(?:app|pm-all|pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
|
||||
|
||||
export interface BackgroundLayout {
|
||||
/** From -1 (white) to 1 (black). */
|
||||
overlay: number;
|
||||
position: BackgroundPosition;
|
||||
size: BackgroundSize;
|
||||
}
|
||||
|
||||
export interface BackgroundSettings extends BackgroundLayout {
|
||||
source: BackgroundSource;
|
||||
/** The time of each image of a folder, from 1 to 86,400 seconds. */
|
||||
seconds: number;
|
||||
order: "name" | "random";
|
||||
/** A paused folder keeps its current image. */
|
||||
paused: boolean;
|
||||
targets: string[];
|
||||
}
|
||||
|
||||
export const DEFAULT_BACKGROUND: Readonly<BackgroundSettings> = Object.freeze({
|
||||
source: "none", seconds: 60, order: "name", paused: false, targets: ["app"], overlay: 0, position: "center", size: "cover",
|
||||
});
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
|
||||
/** The folder layout fields from any value. Invalid fields take the defaults. */
|
||||
export function normalizeLayout(value: unknown): BackgroundLayout {
|
||||
const raw = record(value);
|
||||
return {
|
||||
overlay: typeof raw.overlay === "number" && Number.isFinite(raw.overlay) ? Math.max(-1, Math.min(1, raw.overlay)) : 0,
|
||||
position: BACKGROUND_POSITIONS.includes(raw.position as BackgroundPosition) ? raw.position as BackgroundPosition : "center",
|
||||
size: BACKGROUND_SIZES.includes(raw.size as BackgroundSize) ? raw.size as BackgroundSize : "cover",
|
||||
};
|
||||
}
|
||||
|
||||
/** Valid settings from any value. Invalid fields take the defaults. */
|
||||
export function normalizeBackground(value: unknown): BackgroundSettings {
|
||||
const raw = record(value);
|
||||
return {
|
||||
source: BACKGROUND_SOURCES.includes(raw.source as BackgroundSource) ? raw.source as BackgroundSource : "none",
|
||||
seconds: typeof raw.seconds === "number" && Number.isFinite(raw.seconds) ? Math.max(1, Math.min(86400, Math.round(raw.seconds))) : 60,
|
||||
order: raw.order === "random" ? "random" : "name",
|
||||
paused: raw.paused === true,
|
||||
targets: Array.isArray(raw.targets)
|
||||
? [...new Set(raw.targets.filter((target): target is string => typeof target === "string" && BACKGROUND_TARGET.test(target)))]
|
||||
: ["app"],
|
||||
...normalizeLayout(raw),
|
||||
};
|
||||
}
|
||||
|
||||
export function readBackground(): BackgroundSettings {
|
||||
return normalizeBackground(readSection("background"));
|
||||
}
|
||||
|
||||
/** Save the settings. Keys of a newer version stay. */
|
||||
export function writeBackground(next: BackgroundSettings): Promise<void> {
|
||||
return writeSection("background", { ...record(readSection("background")), ...normalizeBackground(next) });
|
||||
}
|
||||
|
||||
/** True when the appearance has a saved background image. */
|
||||
export function hasImage(appearance: Appearance = readAppearance()): boolean {
|
||||
return !!(appearance.newTabBackground?.image || appearance.newTabBackground?.imageId);
|
||||
}
|
||||
|
||||
/** True when Background has something to show: a folder, or an image that exists. */
|
||||
export function hasBackgroundSource(settings: BackgroundSettings = readBackground(), appearance: Appearance = readAppearance()): boolean {
|
||||
return settings.source === "folder" || (settings.source === "image" && hasImage(appearance));
|
||||
}
|
||||
|
||||
/** Run `listener` after each change of the background or appearance settings. Returns the function that stops it. */
|
||||
export function onBackgroundChange(listener: () => void): () => void {
|
||||
const stops = [onSettingsChange("background", listener), onSettingsChange("appearance", listener)];
|
||||
return () => stops.forEach(stop => stop());
|
||||
}
|
||||
|
||||
/** The host side of the first-start migration of the `background` section. */
|
||||
export interface BackgroundMigrationHost {
|
||||
/** True when the settings file has no `background` section. */
|
||||
missing(): boolean;
|
||||
/** True when the appearance has a saved background image. */
|
||||
hasImage(): boolean;
|
||||
/** Copy the folder of the old plugin grant to the host. True when the host has a folder after the call. */
|
||||
migrateFolder(): Promise<boolean>;
|
||||
write(value: BackgroundSettings): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the `background` section from the old Background Slideshow plugin and the old background image.
|
||||
* The source is the folder when the plugin was installed, enabled, and on, and its folder migrated.
|
||||
* Otherwise it is the image when one exists. The kept plugin settings give the sequence, the targets, and the layout.
|
||||
*/
|
||||
export async function migrateBackground(legacy: LegacyPlugin | undefined, host: BackgroundMigrationHost): Promise<BackgroundSettings> {
|
||||
const kept = record(legacy?.settings);
|
||||
// Migrate the folder whenever a grant exists, so that a later choice of Folder brings it back.
|
||||
let folder = false;
|
||||
if (typeof kept.grant === "string" && kept.grant) {
|
||||
try { folder = await host.migrateFolder(); } catch (reason) { console.error("RuneStone could not take the old background folder.", reason); }
|
||||
}
|
||||
const slideshow = !!legacy?.installed && legacy.enabled && kept.enabled === true && folder;
|
||||
const copied = Object.fromEntries(["seconds", "order", "targets", "overlay", "position", "size"].filter(key => key in kept).map(key => [key, kept[key]]));
|
||||
const value = normalizeBackground({ ...copied, source: slideshow ? "folder" : host.hasImage() ? "image" : "none", paused: false });
|
||||
await host.write(value);
|
||||
return value;
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
// This file is in the main bundle, so it holds only small static data: names, views, and commands.
|
||||
// The code of a feature loads with a dynamic import at first need (see `loader.ts`), and never while its switch is off.
|
||||
import { message, tr } from "../i18n/index.ts";
|
||||
import type { PluginView } from "../plugins/sdk.ts";
|
||||
import type { PluginCommand, PluginView } from "../plugins/sdk.ts";
|
||||
|
||||
export type FeatureId = "git";
|
||||
export type FeatureId = "git" | "background";
|
||||
|
||||
/** A view of a feature. The workbench shows it as a tab or in the side pane, as it shows a plugin view. */
|
||||
export interface FeatureViewInfo {
|
||||
@@ -21,9 +21,9 @@ export interface FeatureViewInfo {
|
||||
export interface FeatureCommandInfo {
|
||||
id: string;
|
||||
title: () => string;
|
||||
icon?: PluginView["icon"];
|
||||
/** The view that the command opens. */
|
||||
view: string;
|
||||
icon?: PluginCommand["icon"];
|
||||
/** The view that the command opens. Without a view, the command loads the feature and calls `FeatureInstance.run`. */
|
||||
view?: string;
|
||||
}
|
||||
|
||||
export interface FeatureEntry {
|
||||
@@ -37,6 +37,8 @@ export interface FeatureEntry {
|
||||
keywords: string;
|
||||
/** The switch for a user who never installed the old package. */
|
||||
defaultOn: boolean;
|
||||
/** True when the first start gives the switch the state of the old package. False when every user gets `defaultOn`. */
|
||||
followsPackage: boolean;
|
||||
views: readonly FeatureViewInfo[];
|
||||
commands: readonly FeatureCommandInfo[];
|
||||
}
|
||||
@@ -46,7 +48,7 @@ export const FEATURES: readonly FeatureEntry[] = [
|
||||
id: "git", owner: "runestone.git", name: message("Git"),
|
||||
description: message("Review changes, stage files, commit, and see the commit graph of the workspace repository."),
|
||||
keywords: "git source control commit stage diff graph branch push pull blame",
|
||||
defaultOn: true,
|
||||
defaultOn: true, followsPackage: true,
|
||||
views: [
|
||||
{ id: "source-control", title: () => tr("Source control"), placement: "sidebar", icon: "git", navigation: true },
|
||||
{ id: "diff", title: () => tr("Git diff"), placement: "editor", icon: "git" },
|
||||
@@ -54,6 +56,19 @@ export const FEATURES: readonly FeatureEntry[] = [
|
||||
],
|
||||
commands: [{ id: "graph", title: () => tr("Show Git graph"), icon: "git", view: "graph" }],
|
||||
},
|
||||
{
|
||||
// Background replaces the Background Slideshow plugin and the background image of Appearance. Its settings are in
|
||||
// Appearance → Background. It loads at the start only when a folder or an image is selected (see `launch.ts`).
|
||||
id: "background", owner: "runestone.bg-slideshow", name: message("Background"),
|
||||
description: message("Show a folder of images as a slideshow, or one image, behind the workspace and the boards."),
|
||||
keywords: "background image wallpaper slideshow folder picture photo overlay blur",
|
||||
defaultOn: true, followsPackage: false,
|
||||
views: [],
|
||||
commands: [
|
||||
{ id: "next", title: () => tr("Next background image"), icon: "image" },
|
||||
{ id: "pause", title: () => tr("Pause background"), icon: "pause" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export function featureEntry(id: FeatureId): FeatureEntry {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// Launch rules: a feature with a rule starts its instance as soon as the rule wants it, without a view or a command.
|
||||
// A feature without a rule loads at first need. `syncFeatures` in `src/lib/plugins/external.ts` applies the rules.
|
||||
import type { FeatureId } from "./catalog.ts";
|
||||
import { hasBackgroundSource, onBackgroundChange } from "./backgroundSettings.ts";
|
||||
|
||||
export interface LaunchRule {
|
||||
/** True when the feature also runs in browser windows. Other features stay out of them. */
|
||||
browserWindow: boolean;
|
||||
/** True when the rule also starts the feature in the settings window. */
|
||||
settingsWindow: boolean;
|
||||
/** True when the instance must run now. */
|
||||
wanted(): boolean;
|
||||
/** Run `listener` after each change that can change `wanted`. Returns the function that stops it. */
|
||||
subscribe(listener: () => void): () => void;
|
||||
}
|
||||
|
||||
export const LAUNCH_RULES: Partial<Record<FeatureId, LaunchRule>> = {
|
||||
// Background starts at the start of a window when a folder or an image is selected, and at once when the user selects one.
|
||||
// The settings window shows the settings only, so the slideshow does not run there.
|
||||
background: { browserWindow: true, settingsWindow: false, wanted: () => hasBackgroundSource(), subscribe: onBackgroundChange },
|
||||
};
|
||||
|
||||
/** True when a feature runs in a window of this kind. */
|
||||
export function runsInWindow(id: FeatureId, window: { browserWindow: boolean }): boolean {
|
||||
return !window.browserWindow || !!LAUNCH_RULES[id]?.browserWindow;
|
||||
}
|
||||
|
||||
/** True when the launch rule of a feature wants its instance now in a window of this kind. */
|
||||
export function launchWanted(id: FeatureId, window: { settingsWindow: boolean }): boolean {
|
||||
const rule = LAUNCH_RULES[id];
|
||||
return !!rule && (!window.settingsWindow || rule.settingsWindow) && rule.wanted();
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import type { FeatureModule } from "./types.ts";
|
||||
|
||||
const imports: Record<FeatureId, () => Promise<FeatureModule>> = {
|
||||
git: () => import("./git/index.ts"),
|
||||
background: () => import("./background/index.ts"),
|
||||
};
|
||||
|
||||
const modules = new Map<FeatureId, Promise<FeatureModule>>();
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
// The first start of a version with a new native feature. The switch takes the state of the old plugin package.
|
||||
// The first start of a version with a new native feature. The switch takes the state of the old plugin package,
|
||||
// or the default of the feature when the feature does not follow its package (`followsPackage`).
|
||||
// `features_legacy` in `src-tauri/src/features.rs` reads the old package state and its kept settings. It changes nothing.
|
||||
// The first start also makes the `background` section from the old Background Slideshow settings (`backgroundSettings.ts`).
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { readSection, writeSection } from "../settings/store.ts";
|
||||
import { FEATURES, type FeatureEntry, type FeatureId } from "./catalog.ts";
|
||||
import { readAppearance } from "../theme/appearance.ts";
|
||||
import { FEATURES, featureEntry, type FeatureEntry, type FeatureId } from "./catalog.ts";
|
||||
import { storedSwitches } from "./state.ts";
|
||||
import { hasImage, migrateBackground, writeBackground, type BackgroundMigrationHost } from "./backgroundSettings.ts";
|
||||
|
||||
/** What the host reports about one old plugin package. */
|
||||
export interface LegacyPlugin {
|
||||
@@ -14,9 +18,9 @@ export interface LegacyPlugin {
|
||||
settings: unknown;
|
||||
}
|
||||
|
||||
/** An installed package gives its enabled state. Without a package, the default of the feature applies. */
|
||||
/** An installed package gives its enabled state. Without a package, or for a feature that does not follow its package, the default applies. */
|
||||
export function legacySwitch(entry: FeatureEntry, legacy: LegacyPlugin | undefined): boolean {
|
||||
return legacy?.installed ? legacy.enabled : entry.defaultOn;
|
||||
return entry.followsPackage && legacy?.installed ? legacy.enabled : entry.defaultOn;
|
||||
}
|
||||
|
||||
export interface MigrationHost {
|
||||
@@ -31,24 +35,37 @@ const desktopHost: MigrationHost = {
|
||||
legacy: ids => invoke<LegacyPlugin[]>("features_legacy", { ids }),
|
||||
};
|
||||
|
||||
const desktopBackground: BackgroundMigrationHost = {
|
||||
missing: () => readSection("background") === undefined,
|
||||
hasImage: () => hasImage(readAppearance()),
|
||||
migrateFolder: async () => !!await invoke<string | null>("background_migrate"),
|
||||
write: writeBackground,
|
||||
};
|
||||
|
||||
/**
|
||||
* Give each feature without a stored switch the state of its old package. It runs before the first render.
|
||||
* When the host cannot report the packages, nothing is written, so the next start tries again.
|
||||
* Give each feature without a stored switch the state of its old package, and make a missing `background` section.
|
||||
* It runs before the first render. When the host cannot report the packages, nothing is written, so the next start tries again.
|
||||
*/
|
||||
export async function migrateFeatures(host: MigrationHost = desktopHost): Promise<FeatureId[]> {
|
||||
export async function migrateFeatures(host: MigrationHost = desktopHost, background: BackgroundMigrationHost = desktopBackground): Promise<FeatureId[]> {
|
||||
const current = host.read();
|
||||
const stored = storedSwitches(current);
|
||||
const missing = FEATURES.filter(entry => stored[entry.id] === undefined);
|
||||
if (!missing.length) return [];
|
||||
const backgroundOwner = featureEntry("background").owner;
|
||||
const backgroundMissing = background.missing();
|
||||
const owners = [...new Set([...missing.map(entry => entry.owner), ...backgroundMissing ? [backgroundOwner] : []])];
|
||||
if (!owners.length) return [];
|
||||
let legacy: LegacyPlugin[];
|
||||
try { legacy = await host.legacy(missing.map(entry => entry.owner)); }
|
||||
try { legacy = await host.legacy(owners); }
|
||||
catch (reason) {
|
||||
console.error("RuneStone could not read the old plugin packages. The feature defaults apply.", reason);
|
||||
return [];
|
||||
}
|
||||
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
|
||||
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
|
||||
await host.write(next);
|
||||
if (missing.length) {
|
||||
const next: Record<string, unknown> = current && typeof current === "object" && !Array.isArray(current) ? { ...current as Record<string, unknown> } : {};
|
||||
for (const entry of missing) next[entry.id] = legacySwitch(entry, legacy.find(item => item.id === entry.owner));
|
||||
await host.write(next);
|
||||
}
|
||||
if (backgroundMissing) await migrateBackground(legacy.find(item => item.id === backgroundOwner), background);
|
||||
return missing.map(entry => entry.id);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// A feature in the workbench of one window. Its views and commands come from the static catalog, so the
|
||||
// navigation buttons and the command palette show them without the feature code. The first mount,
|
||||
// restore, or command loads the feature module and starts one instance for this window.
|
||||
// restore, or action command loads the feature module and starts one instance for this window.
|
||||
// A launch rule (`launch.ts`) can also start the instance at once.
|
||||
import { tr } from "../i18n/index.ts";
|
||||
import type { Dispose, PluginCommand, PluginDocumentType, PluginView } from "../plugins/sdk.ts";
|
||||
import type { FeatureEntry } from "./catalog.ts";
|
||||
@@ -32,7 +33,9 @@ export class FeatureSession {
|
||||
});
|
||||
}
|
||||
for (const info of entry.commands) {
|
||||
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon, run: () => context.openView(info.view) });
|
||||
const view = info.view;
|
||||
this.commands.set(info.id, { id: info.id, get title() { return info.title(); }, icon: info.icon,
|
||||
run: view ? () => context.openView(view) : async () => { await (await this.running()).run?.(info.id); } });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +65,12 @@ export class FeatureSession {
|
||||
|
||||
async launch(id: string) { this.context.openView(id); }
|
||||
|
||||
/** Load the module and start the instance now, without a view. Later calls use the same instance. */
|
||||
async start(): Promise<void> { await this.running(); }
|
||||
|
||||
/** True after the instance started. */
|
||||
get started(): boolean { return this.instance !== undefined; }
|
||||
|
||||
async run(id: string) {
|
||||
const command = this.commands.get(id);
|
||||
if (!command) throw new Error(tr("This command is unavailable."));
|
||||
|
||||
@@ -13,6 +13,8 @@ export interface FeatureContext {
|
||||
/** One running copy of a feature in one window. */
|
||||
export interface FeatureInstance {
|
||||
mount(view: string, element: HTMLElement): Dispose | Promise<Dispose>;
|
||||
/** Run a command of the catalog that has no view. */
|
||||
run?(command: string): void | Promise<void>;
|
||||
/** The state of a tab for a transfer to another window. */
|
||||
saveTabState?(view: string): unknown;
|
||||
restoreTabState?(view: string, state: unknown): void | Promise<void>;
|
||||
@@ -23,4 +25,6 @@ export interface FeatureInstance {
|
||||
/** The module that `loader.ts` imports at first need. */
|
||||
export interface FeatureModule {
|
||||
start(context: FeatureContext): FeatureInstance;
|
||||
/** Show the settings of the feature in `element`, also in a window where the feature does not run. */
|
||||
mountSettings?(element: HTMLElement): Dispose;
|
||||
}
|
||||
|
||||
+72
-24
@@ -347,12 +347,6 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"透過をオフにすると背景が不透明になり、合成処理を減らせます。文字とアイコンは常に不透明です。",
|
||||
"关闭透明效果可使界面不透明并减少合成工作量。文本和图标始终保持不透明。"
|
||||
],
|
||||
[
|
||||
"Background image",
|
||||
"Image de fond",
|
||||
"背景画像",
|
||||
"背景图片"
|
||||
],
|
||||
[
|
||||
"Background image preview",
|
||||
"Aperçu de l’image de fond",
|
||||
@@ -461,12 +455,6 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"実際のサイズ",
|
||||
"实际大小"
|
||||
],
|
||||
[
|
||||
"Move left to lighten the image or right to darken it.",
|
||||
"Déplacez vers la gauche pour éclaircir, ou vers la droite pour assombrir.",
|
||||
"左に動かすと明るく、右に動かすと暗くなります。",
|
||||
"向左移动可提亮图片,向右移动可调暗。"
|
||||
],
|
||||
[
|
||||
"Background image file",
|
||||
"Fichier de l’image de fond",
|
||||
@@ -485,18 +473,6 @@ export const messageRows: [string, string, string, string][] = [
|
||||
"画像を削除",
|
||||
"删除图片"
|
||||
],
|
||||
[
|
||||
"Reset background",
|
||||
"Réinitialiser le fond",
|
||||
"背景をリセット",
|
||||
"重置背景"
|
||||
],
|
||||
[
|
||||
"PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.",
|
||||
"PNG, JPEG, WebP ou GIF, jusqu’à 50 Mio. L’image s’applique aux nouveaux onglets de cet appareil.",
|
||||
"PNG、JPEG、WebP、GIF(最大50 MiB)。この端末の新しいタブに適用します。",
|
||||
"支持 PNG、JPEG、WebP 或 GIF,最大 50 MiB。此图片用于此设备上的新标签页。"
|
||||
],
|
||||
[
|
||||
"Could not read appearance settings.",
|
||||
"Impossible de lire les paramètres d’apparence.",
|
||||
@@ -3515,6 +3491,78 @@ export const messageRows: [string, string, string, string][] = [
|
||||
["No commits yet. Create a commit to start the graph.", "Aucun commit pour l’instant. Créez un commit pour commencer le graphe.", "まだコミットがありません。コミットを作成するとグラフが始まります。", "还没有提交。创建一个提交以开始图表。"],
|
||||
["Parents: {parents}", "Parents : {parents}", "親: {parents}", "父提交:{parents}"],
|
||||
["Root commit", "Commit racine", "ルートコミット", "根提交"],
|
||||
["Add PNG, JPEG, GIF, or WebP images to the folder. Portrait images show in full over a blurred fill.", "Ajoutez des images PNG, JPEG, GIF ou WebP au dossier. Les images en portrait s’affichent en entier sur un fond flou.", "フォルダーに PNG、JPEG、GIF、WebP の画像を追加してください。縦長の画像は、ぼかした背景の上に全体が表示されます。", "将 PNG、JPEG、GIF 或 WebP 图像添加到该文件夹。纵向图像会完整显示在模糊的填充背景上。"],
|
||||
["All Project Management boards", "Tous les tableaux de Project Management", "Project Management のすべてのボード", "所有 Project Management 看板"],
|
||||
["Background is off. Turn it on in Settings → Features.", "L’arrière-plan est désactivé. Activez-le dans Paramètres → Fonctionnalités.", "背景はオフです。[設定]→[機能]でオンにしてください。", "背景已关闭。请在“设置”→“功能”中将其打开。"],
|
||||
["Background source", "Source de l’arrière-plan", "背景のソース", "背景来源"],
|
||||
["Board: {name}", "Tableau : {name}", "ボード: {name}", "看板:{name}"],
|
||||
["Cannot create the blurred image.", "Impossible de créer l’image floue.", "ぼかした画像を作成できません。", "无法创建模糊图像。"],
|
||||
["Choose a folder for a slideshow, or one image.", "Choisissez un dossier pour un diaporama, ou une seule image.", "スライドショーのフォルダー、または 1 枚の画像を選択してください。", "选择一个文件夹作为幻灯片,或选择一张图像。"],
|
||||
["Choose a folder or an image to show a background.", "Choisissez un dossier ou une image pour afficher un arrière-plan.", "背景を表示するには、フォルダーまたは画像を選択してください。", "选择一个文件夹或一张图像以显示背景。"],
|
||||
["Choose an image", "Choisir une image", "画像を選択", "选择图像"],
|
||||
["Choose an image to change its fit, position, and overlay. Portrait images show in full over a blurred fill by default.", "Choisissez une image pour modifier son ajustement, sa position et son voile. Par défaut, les images en portrait s’affichent en entier sur un fond flou.", "画像を選択すると、サイズ調整、位置、オーバーレイを変更できます。縦長の画像は、既定でぼかした背景の上に全体が表示されます。", "选择一张图像以更改其适应方式、位置和叠加层。默认情况下,纵向图像会完整显示在模糊的填充背景上。"],
|
||||
["Choose folder…", "Choisir un dossier…", "フォルダーを選択…", "选择文件夹…"],
|
||||
["Choose the background folder", "Choisir le dossier de l’arrière-plan", "背景のフォルダーを選択", "选择背景文件夹"],
|
||||
["Could not read the workspace boards: {error}", "Impossible de lire les tableaux de l’espace de travail : {error}", "ワークスペースのボードを読み込めませんでした: {error}", "无法读取工作区看板:{error}"],
|
||||
["Could not save the background settings.", "Impossible d’enregistrer les paramètres de l’arrière-plan.", "背景の設定を保存できませんでした。", "无法保存背景设置。"],
|
||||
["Default appearance restored.", "Apparence par défaut rétablie.", "既定の外観に戻しました。", "已恢复默认外观。"],
|
||||
["Default appearance.", "Apparence par défaut.", "既定の外観です。", "默认外观。"],
|
||||
["File name", "Nom de fichier", "ファイル名", "文件名"],
|
||||
["Find an image", "Rechercher une image", "画像を検索", "查找图像"],
|
||||
["Folder", "Dossier", "フォルダー", "文件夹"],
|
||||
["Full image with blurred fill", "Image entière sur fond flou", "ぼかした背景の上に全体を表示", "完整图像加模糊填充"],
|
||||
["Image appearance saved.", "Apparence de l’image enregistrée.", "画像の外観を保存しました。", "已保存图像外观。"],
|
||||
["Image files", "Fichiers image", "画像ファイル", "图像文件"],
|
||||
["Image fit", "Ajustement de l’image", "画像のサイズ調整", "图像适应方式"],
|
||||
["Image folder", "Dossier d’images", "画像フォルダー", "图像文件夹"],
|
||||
["Image order", "Ordre des images", "画像の順序", "图像顺序"],
|
||||
["Image to change", "Image à modifier", "変更する画像", "要更改的图像"],
|
||||
["Invalid image settings for {name}.", "Paramètres d’image non valides pour {name}.", "{name} の画像設定が無効です。", "{name} 的图像设置无效。"],
|
||||
["Move the overlay left to lighten the image or right to darken it.", "Déplacez le voile vers la gauche pour éclaircir l’image ou vers la droite pour l’assombrir.", "オーバーレイを左に動かすと画像が明るくなり、右に動かすと暗くなります。", "向左移动叠加层可使图像变亮,向右移动可使其变暗。"],
|
||||
["Next background image", "Image d’arrière-plan suivante", "次の背景画像", "下一张背景图像"],
|
||||
["Next image", "Image suivante", "次の画像", "下一张图像"],
|
||||
["No folder selected", "Aucun dossier sélectionné", "フォルダーが選択されていません", "未选择文件夹"],
|
||||
["No matching images.", "Aucune image correspondante.", "一致する画像はありません。", "没有匹配的图像。"],
|
||||
["No readable images in this folder. Check the image files.", "Aucune image lisible dans ce dossier. Vérifiez les fichiers image.", "このフォルダーに読み込める画像がありません。画像ファイルを確認してください。", "此文件夹中没有可读取的图像。请检查图像文件。"],
|
||||
["No supported images in this folder. Add PNG, JPEG, GIF, or WebP files.", "Aucune image prise en charge dans ce dossier. Ajoutez des fichiers PNG, JPEG, GIF ou WebP.", "このフォルダーに対応する画像がありません。PNG、JPEG、GIF、WebP のファイルを追加してください。", "此文件夹中没有受支持的图像。请添加 PNG、JPEG、GIF 或 WebP 文件。"],
|
||||
["None", "Aucune", "なし", "无"],
|
||||
["Overlay", "Voile", "オーバーレイ", "叠加层"],
|
||||
["Overlay of this image", "Voile de cette image", "この画像のオーバーレイ", "此图像的叠加层"],
|
||||
["Overlay percentage of this image", "Pourcentage du voile de cette image", "この画像のオーバーレイの割合", "此图像的叠加层百分比"],
|
||||
["PNG, JPEG, WebP, or GIF, up to 50 MiB. The image stays on this device.", "PNG, JPEG, WebP ou GIF, jusqu’à 50 Mio. L’image reste sur cet appareil.", "PNG、JPEG、WebP、GIF、最大 50 MiB。画像はこのデバイスに保存されます。", "PNG、JPEG、WebP 或 GIF,最大 50 MiB。图像保存在此设备上。"],
|
||||
["Pause background", "Mettre l’arrière-plan en pause", "背景を一時停止", "暂停背景"],
|
||||
["Pause slideshow", "Mettre le diaporama en pause", "スライドショーを一時停止", "暂停幻灯片"],
|
||||
["Per-image appearance", "Apparence par image", "画像ごとの外観", "每张图像的外观"],
|
||||
["Position", "Position", "位置", "位置"],
|
||||
["Position of this image", "Position de cette image", "この画像の位置", "此图像的位置"],
|
||||
["Random", "Aléatoire", "ランダム", "随机"],
|
||||
["Reload image settings", "Recharger les paramètres d’image", "画像の設定を再読み込み", "重新加载图像设置"],
|
||||
["Remove folder", "Retirer le dossier", "フォルダーを解除", "移除文件夹"],
|
||||
["Reset image appearance", "Réinitialiser l’apparence de l’image", "画像の外観をリセット", "重置图像外观"],
|
||||
["Resume slideshow", "Reprendre le diaporama", "スライドショーを再開", "继续幻灯片"],
|
||||
["Save image appearance", "Enregistrer l’apparence de l’image", "画像の外観を保存", "保存图像外观"],
|
||||
["Saved appearance.", "Apparence enregistrée.", "保存された外観です。", "已保存的外观。"],
|
||||
["Seconds per image", "Secondes par image", "画像ごとの秒数", "每张图像的秒数"],
|
||||
["Select where to show the background.", "Sélectionnez où afficher l’arrière-plan.", "背景を表示する場所を選択してください。", "请选择显示背景的位置。"],
|
||||
["Selected image preview", "Aperçu de l’image sélectionnée", "選択した画像のプレビュー", "所选图像的预览"],
|
||||
["Selected image preview: {name}", "Aperçu de l’image sélectionnée : {name}", "選択した画像のプレビュー: {name}", "所选图像的预览:{name}"],
|
||||
["Show a folder of images as a slideshow, or one image, behind the workspace and the boards.", "Affichez un dossier d’images en diaporama, ou une seule image, derrière l’espace de travail et les tableaux.", "ワークスペースとボードの背後に、画像フォルダーをスライドショーとして、または 1 枚の画像を表示します。", "在工作区和看板后方以幻灯片形式显示图像文件夹,或显示一张图像。"],
|
||||
["Show the background in", "Afficher l’arrière-plan dans", "背景を表示する場所", "在以下位置显示背景"],
|
||||
["Slideshow", "Diaporama", "スライドショー", "幻灯片"],
|
||||
["The background changed.", "L’arrière-plan a changé.", "背景が変更されました。", "背景已更改。"],
|
||||
["The blurred image took too long to load.", "Le chargement de l’image floue a pris trop de temps.", "ぼかした画像の読み込みに時間がかかりすぎました。", "模糊图像加载时间过长。"],
|
||||
["The image cannot be displayed.", "Impossible d’afficher l’image.", "画像を表示できません。", "无法显示该图像。"],
|
||||
["The image settings file must use schema 1 and an images object.", "Le fichier des paramètres d’image doit utiliser le schéma 1 et un objet images.", "画像の設定ファイルは、スキーマ 1 と images オブジェクトを使用する必要があります。", "图像设置文件必须使用架构 1 和 images 对象。"],
|
||||
["The image took too long to load.", "Le chargement de l’image a pris trop de temps.", "画像の読み込みに時間がかかりすぎました。", "图像加载时间过长。"],
|
||||
["The saved background image is missing. Choose the image again.", "L’image d’arrière-plan enregistrée est introuvable. Choisissez de nouveau l’image.", "保存された背景画像が見つかりません。画像をもう一度選択してください。", "找不到已保存的背景图像。请重新选择图像。"],
|
||||
["The workspace and new tabs", "L’espace de travail et les nouveaux onglets", "ワークスペースと新しいタブ", "工作区和新标签页"],
|
||||
["The workspace has no boards.", "L’espace de travail ne contient aucun tableau.", "ワークスペースにボードがありません。", "工作区中没有看板。"],
|
||||
["Turn on Project Management to show the background on one board.", "Activez Project Management pour afficher l’arrière-plan sur un tableau.", "1 つのボードに背景を表示するには、Project Management をオンにしてください。", "打开 Project Management 才能在某个看板上显示背景。"],
|
||||
["Unavailable board: {id}", "Tableau indisponible : {id}", "利用できないボード: {id}", "不可用的看板:{id}"],
|
||||
["{count} image.", "{count} image.", "{count} 枚の画像。", "{count} 张图像。"],
|
||||
["{count} images.", "{count} images.", "{count} 枚の画像。", "{count} 张图像。"],
|
||||
["{count} matches. Type more of the name to see other images.", "{count} résultats. Saisissez une plus grande partie du nom pour voir d’autres images.", "{count} 件一致しました。ほかの画像を表示するには、名前をさらに入力してください。", "{count} 个匹配项。请输入更多名称以查看其他图像。"],
|
||||
["{name}: skipped {count} unreadable images.", "{name} : {count} images illisibles ignorées.", "{name}: 読み込めない {count} 枚の画像をスキップしました。", "{name}:已跳过 {count} 张无法读取的图像。"],
|
||||
];
|
||||
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
|
||||
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
||||
|
||||
@@ -88,6 +88,8 @@
|
||||
</header>
|
||||
{#if message}<p class="error" role="alert">{message}</p>{/if}
|
||||
<main class="pages">
|
||||
<!-- A blank browser tab shows the background of the Background feature (src/lib/theme/background.css). -->
|
||||
<div class="workarea-background" aria-hidden="true"></div>
|
||||
{#each $pluginEditors as view (view.key)}
|
||||
{@const position = bounds[view.key]}
|
||||
<!-- svelte-ignore a11y_no_static_element_interactions (Input selects its browser pane.) -->
|
||||
@@ -114,6 +116,7 @@
|
||||
.header :global(.tabs) { flex: 0 1 auto; min-width: 80px; height: 100%; border-bottom: 0; }
|
||||
.window-drag-space { flex: 1; min-width: 120px; align-self: stretch; }
|
||||
.pages { position: relative; flex: 1; min-height: 0; overflow: hidden; }
|
||||
.workarea-background { position: absolute; inset: 0; }
|
||||
.pane { position: absolute; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: hidden; }
|
||||
.pane.inactive { display: none; }
|
||||
.pane.split { border: 1px solid var(--rs-border); }
|
||||
|
||||
@@ -1469,37 +1469,11 @@
|
||||
background: var(--rs-bg);
|
||||
}
|
||||
|
||||
/* The layer styles are in src/lib/theme/background.css. */
|
||||
.workarea-background {
|
||||
position: absolute;
|
||||
inset: var(--rs-titlebar-height) 0 22px;
|
||||
z-index: -1;
|
||||
pointer-events: none;
|
||||
background-color: var(--rs-new-tab-bg, var(--rs-bg));
|
||||
background-image: var(--rs-background-image, var(--rs-new-tab-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));
|
||||
}
|
||||
|
||||
.shell.left-open {
|
||||
|
||||
@@ -1,5 +1,2 @@
|
||||
// The public background types are in the plugin SDK (packages/plugin-sdk/src/backgrounds.ts).
|
||||
import type { BackgroundApi } from "./sdk.ts";
|
||||
export type { BackgroundApi, BackgroundFrame } from "./sdk.ts";
|
||||
|
||||
export type BackgroundFiles = Pick<BackgroundApi, 'chooseFolder' | 'defaultFolder' | 'list' | 'read' | 'readImageSettings' | 'writeImageSettings'>;
|
||||
|
||||
@@ -28,11 +28,16 @@ function checkTarget(target: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Each window retains temporary frames without changing saved appearance settings. */
|
||||
/**
|
||||
* The background frames of one window, for each target. The Background feature (`src/lib/features/background/`) and
|
||||
* plugins set them. The `app` frame sets the custom properties of the body that the workarea background reads.
|
||||
*/
|
||||
export class BackgroundHub {
|
||||
private frames = new Map<string, Map<symbol, BackgroundFrame>>();
|
||||
private listeners = new Set<(target: string) => void>();
|
||||
private restore?: () => void;
|
||||
/** The values that `applyApp` set last. A new frame changes only the properties with a new value. */
|
||||
private applied = new Map<string, string>();
|
||||
private body: () => HTMLElement | undefined;
|
||||
|
||||
constructor(body: () => HTMLElement | undefined = () => typeof document === 'undefined' ? undefined : document.body) {
|
||||
@@ -82,9 +87,14 @@ export class BackgroundHub {
|
||||
|
||||
private applyApp() {
|
||||
const frame = this.get('app');
|
||||
if (!frame) { this.restore?.(); this.restore = undefined; return; }
|
||||
if (!frame) { this.restore?.(); this.restore = undefined; this.applied.clear(); return; }
|
||||
const body = this.body();
|
||||
if (!body) return;
|
||||
const put = (key: typeof properties[number], value: string) => {
|
||||
if (this.applied.get(key) === value) return;
|
||||
this.applied.set(key, value);
|
||||
body.style.setProperty(key, value);
|
||||
};
|
||||
if (!this.restore) {
|
||||
const previous = properties.map(key => [key, body.style.getPropertyValue(key), body.style.getPropertyPriority(key)]);
|
||||
this.restore = () => {
|
||||
@@ -95,28 +105,30 @@ export class BackgroundHub {
|
||||
};
|
||||
}
|
||||
const { overlay, image: currentImage, sizes, positions: layerPositions } = image(frame);
|
||||
body.style.setProperty('--rs-background-overlay', overlay);
|
||||
body.style.setProperty('--rs-background-image', currentImage);
|
||||
body.style.setProperty('--rs-background-position', frame.position);
|
||||
body.style.setProperty('--rs-background-size', frame.size);
|
||||
body.style.setProperty('--rs-background-layer-sizes', sizes);
|
||||
body.style.setProperty('--rs-background-layer-positions', layerPositions);
|
||||
body.style.setProperty('--rs-background-previous-layer-sizes', frame.previous ? image(frame.previous).sizes : sizes);
|
||||
body.style.setProperty('--rs-background-previous-layer-positions', frame.previous ? image(frame.previous).positions : layerPositions);
|
||||
body.style.setProperty('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)');
|
||||
body.style.setProperty('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)');
|
||||
body.style.setProperty('--rs-workarea-surface-opacity', 'var(--rs-surface-opacity, 82%)');
|
||||
body.style.setProperty('--rs-workarea-plugin-bg', 'var(--rs-transparent-plugin-bg, transparent)');
|
||||
body.style.setProperty('--rs-menu-bg', 'var(--rs-image-menu-bg)');
|
||||
body.style.setProperty('--rs-menu-active-bg', 'var(--rs-image-menu-active-bg)');
|
||||
body.style.setProperty('--rs-menu-backdrop', 'var(--rs-image-menu-backdrop)');
|
||||
body.style.setProperty('--rs-background-transition-image', frame.previous ? currentImage : 'none');
|
||||
body.style.setProperty('--rs-background-previous-image', frame.previous ? image(frame.previous).image : 'none');
|
||||
body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position);
|
||||
body.style.setProperty('--rs-background-previous-size', frame.previous?.size ?? frame.size);
|
||||
const previous = frame.previous ? image(frame.previous) : undefined;
|
||||
put('--rs-background-overlay', overlay);
|
||||
put('--rs-background-image', currentImage);
|
||||
put('--rs-background-position', frame.position);
|
||||
put('--rs-background-size', frame.size);
|
||||
put('--rs-background-layer-sizes', sizes);
|
||||
put('--rs-background-layer-positions', layerPositions);
|
||||
put('--rs-background-previous-layer-sizes', previous ? previous.sizes : sizes);
|
||||
put('--rs-background-previous-layer-positions', previous ? previous.positions : layerPositions);
|
||||
put('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)');
|
||||
put('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)');
|
||||
put('--rs-workarea-surface-opacity', 'var(--rs-surface-opacity, 82%)');
|
||||
put('--rs-workarea-plugin-bg', 'var(--rs-transparent-plugin-bg, transparent)');
|
||||
put('--rs-menu-bg', 'var(--rs-image-menu-bg)');
|
||||
put('--rs-menu-active-bg', 'var(--rs-image-menu-active-bg)');
|
||||
put('--rs-menu-backdrop', 'var(--rs-image-menu-backdrop)');
|
||||
put('--rs-background-transition-image', previous ? currentImage : 'none');
|
||||
put('--rs-background-previous-image', previous ? previous.image : 'none');
|
||||
put('--rs-background-previous-position', frame.previous?.position ?? frame.position);
|
||||
put('--rs-background-previous-size', frame.previous?.size ?? frame.size);
|
||||
if (typeof document !== 'undefined') {
|
||||
for (const element of body.querySelectorAll('.workarea-background')) {
|
||||
for (const animation of element.getAnimations()) animation.cancel();
|
||||
// The fade runs on `::after`. Only `subtree` returns the animations of pseudo-elements.
|
||||
for (const animation of element.getAnimations({ subtree: true })) animation.cancel();
|
||||
if (frame.previous && frame.transitionMs && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||
element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: frame.transitionMs, easing: 'ease-in-out', pseudoElement: '::after' });
|
||||
}
|
||||
|
||||
+23
-12
@@ -13,6 +13,7 @@ import { locale } from "../i18n";
|
||||
import { FEATURES, type FeatureEntry } from "../features/catalog";
|
||||
import { FeatureSession } from "../features/session";
|
||||
import { featureSwitches, type FeatureSwitches } from "../features/state";
|
||||
import { LAUNCH_RULES, launchWanted, runsInWindow } from "../features/launch";
|
||||
import type { FeatureContext } from "../features/types";
|
||||
|
||||
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
|
||||
@@ -104,6 +105,7 @@ let queue: Promise<void> = Promise.resolve();
|
||||
export function waitForPluginStartup() { return queue; }
|
||||
let started = false;
|
||||
let browserWindow = false;
|
||||
let settingsWindow = false;
|
||||
let generation = 0;
|
||||
let documentOpenVersion = 0;
|
||||
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
|
||||
@@ -272,14 +274,7 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
|
||||
completionTransport,
|
||||
pty: ptyTransport,
|
||||
files: filesTransport(id),
|
||||
backgrounds: {
|
||||
chooseFolder: () => invoke<string | null>('backgrounds_choose_folder', { id }),
|
||||
defaultFolder: () => invoke<string>('backgrounds_default_folder', { id }),
|
||||
list: folder => invoke<{ name: string }[]>('backgrounds_list', { id, folder }),
|
||||
read: async (folder, name) => Uint8Array.from(atob(await invoke<string>('backgrounds_read', { id, folder, name })), character => character.charCodeAt(0)),
|
||||
readImageSettings: folder => invoke<string | null>('backgrounds_read_image_settings', { id, folder }),
|
||||
writeImageSettings: (folder, contents, expected) => invoke<void>('backgrounds_write_image_settings', { id, folder, contents, expected }),
|
||||
},
|
||||
backgrounds: true,
|
||||
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
||||
workspace: {
|
||||
list: path => workspaceList(path ?? ""), read: workspaceRead,
|
||||
@@ -387,23 +382,38 @@ function featureContext(entry: FeatureEntry): FeatureContext {
|
||||
onWorkspaceChange: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
|
||||
};
|
||||
}
|
||||
/** Start each native feature that is on, and stop each one that is off. The feature code loads later, at first need. */
|
||||
/**
|
||||
* Start each native feature that is on, and stop each one that is off. The feature code loads later, at first need,
|
||||
* or at once when the launch rule of the feature wants it (`src/lib/features/launch.ts`).
|
||||
*/
|
||||
function syncFeatures(switches: FeatureSwitches) {
|
||||
queue = queue.then(async () => {
|
||||
for (const entry of FEATURES) {
|
||||
if (!runsInWindow(entry.id, { browserWindow })) continue;
|
||||
const loaded = sessions.get(entry.owner);
|
||||
if (switches[entry.id] && !loaded) {
|
||||
sessions.set(entry.owner, { hash: "feature", session: new FeatureSession(entry, featureContext(entry)) });
|
||||
publish();
|
||||
} else if (!switches[entry.id] && loaded?.hash === "feature") await stop(entry.owner);
|
||||
}
|
||||
launchFeatures();
|
||||
}).catch(reason => pluginServiceError.set(String(reason)));
|
||||
}
|
||||
/** A browser window starts only the built-in modules for browser windows, no native feature, and no installed plugin. */
|
||||
/** Start the instance of each running feature whose launch rule wants it now. */
|
||||
function launchFeatures() {
|
||||
for (const entry of FEATURES) {
|
||||
const loaded = sessions.get(entry.owner);
|
||||
if (loaded?.hash !== "feature" || !launchWanted(entry.id, { settingsWindow })) continue;
|
||||
const session = loaded.session as FeatureSession;
|
||||
if (!session.started) void session.start().catch(reason => report(entry.owner, reason));
|
||||
}
|
||||
}
|
||||
/** A browser window starts the built-in modules for browser windows and the features with a browser window rule. It loads no installed plugin. */
|
||||
export function startExternalPlugins(options: { browserWindow?: boolean } = {}): () => void {
|
||||
if (!isTauri() || started) return () => {};
|
||||
started = true;
|
||||
browserWindow = options.browserWindow === true;
|
||||
settingsWindow = new URLSearchParams(location.search).get("settingsWindow") === "true";
|
||||
let disposed = false;
|
||||
let off: (() => void) | undefined;
|
||||
void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason)));
|
||||
@@ -415,7 +425,8 @@ export function startExternalPlugins(options: { browserWindow?: boolean } = {}):
|
||||
await activate({ manifest: { schemaVersion: 1, id: builtIn.id, name: builtIn.name, author: "RuneStone", description: `Built-in ${builtIn.name.toLowerCase()}`, version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
|
||||
}).catch(reason => report(builtIn.id, reason));
|
||||
}
|
||||
const offFeatures = browserWindow ? undefined : featureSwitches.subscribe(syncFeatures);
|
||||
const offFeatures = featureSwitches.subscribe(syncFeatures);
|
||||
const offLaunch = Object.values(LAUNCH_RULES).map(rule => rule.subscribe(launchFeatures));
|
||||
// Feature titles follow the interface language.
|
||||
const offLocale = locale.subscribe(() => publish());
|
||||
void refreshPlugins();
|
||||
@@ -423,7 +434,7 @@ export function startExternalPlugins(options: { browserWindow?: boolean } = {}):
|
||||
const focus = () => { void refreshPlugins(); };
|
||||
window.addEventListener("focus", focus);
|
||||
return () => {
|
||||
disposed = true; started = false; generation++; off?.(); offFeatures?.(); offLocale(); window.removeEventListener("focus", focus);
|
||||
disposed = true; started = false; generation++; off?.(); offFeatures(); offLaunch.forEach(stop => stop()); offLocale(); window.removeEventListener("focus", focus);
|
||||
for (const id of [...sessions.keys()]) void stop(id).catch(reason => report(id, reason));
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,12 +4,12 @@ import { registerCompletionInput } from "../completion/input.ts";
|
||||
import { showActionMenu } from "../ui/managedActionMenu.ts";
|
||||
import { backgroundHub } from "./backgrounds.ts";
|
||||
import { serviceHub as defaultServiceHub, type ServiceHub } from "./services.ts";
|
||||
import type { BackgroundFiles } from "./backgroundContracts.ts";
|
||||
import type { Dispose, FilesApi, FilesTransport, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext, PtyApi, PtyOpenOptions, PtySession, PtyTransport } from "./sdk.ts";
|
||||
|
||||
/** The host services that a session gives to its plugin. The host binds them to the plugin ID. */
|
||||
export type SessionServices = Pick<PluginApi, "workspace" | "settings" | "assets"> & {
|
||||
openFile?: PluginApi["openFile"]; backgrounds?: BackgroundFiles;
|
||||
/** True gives the plugin `api.backgrounds`: the background frames of each target. */
|
||||
openFile?: PluginApi["openFile"]; backgrounds?: boolean;
|
||||
completionTransport?: NonNullable<PluginApi["completion"]>["transport"];
|
||||
pty?: PtyTransport; files?: FilesTransport; serviceHub?: ServiceHub;
|
||||
};
|
||||
@@ -70,12 +70,6 @@ export class ExternalSession {
|
||||
services: this.servicesApi(this.services.serviceHub ?? defaultServiceHub),
|
||||
...(this.services.backgrounds ? { backgrounds: {
|
||||
version: 1 as const,
|
||||
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
|
||||
...(this.services.backgrounds.defaultFolder ? { defaultFolder: () => this.backgroundRequest(() => this.services.backgrounds!.defaultFolder!()) } : {}),
|
||||
list: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.list(folder)),
|
||||
read: (folder: string, name: string) => this.backgroundRequest(() => this.services.backgrounds!.read(folder, name)),
|
||||
...(this.services.backgrounds.readImageSettings ? { readImageSettings: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.readImageSettings!(folder)) } : {}),
|
||||
...(this.services.backgrounds.writeImageSettings ? { writeImageSettings: (folder: string, contents: string, expected: string | null) => this.backgroundRequest(() => this.services.backgrounds!.writeImageSettings!(folder, contents, expected)) } : {}),
|
||||
set: (target: string, frame: import('./backgroundContracts.ts').BackgroundFrame | null) => { this.check(); backgroundHub.set(this.backgroundOwner, target, frame); },
|
||||
get: (target: string) => { this.check(); return backgroundHub.get(target); },
|
||||
subscribe: (listener: (target: string) => void) => {
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
|
||||
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features'] as const;
|
||||
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language', 'features', 'background'] as const;
|
||||
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
|
||||
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
|
||||
|
||||
@@ -22,6 +22,7 @@ export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
|
||||
customThemesLegacy: 'runestone.custom-themes.legacy',
|
||||
language: 'runestone.language',
|
||||
features: 'runestone.features',
|
||||
background: 'runestone.background',
|
||||
};
|
||||
|
||||
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
|
||||
|
||||
@@ -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>
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
Reference in New Issue
Block a user