Files
RuneStone/src/lib/plugins/backgrounds.ts
T
2026-11-03 00:23:07 -07:00

143 lines
7.4 KiB
TypeScript

import type { BackgroundFrame } from './backgroundContracts.ts';
const positions = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'];
const properties = ['--rs-background-overlay', '--rs-background-image', '--rs-background-position', '--rs-background-size', '--rs-background-layer-sizes', '--rs-background-layer-positions', '--rs-background-previous-layer-sizes', '--rs-background-previous-layer-positions', '--rs-background-previous-image', '--rs-background-previous-position', '--rs-background-previous-size', '--rs-background-transition-image', '--rs-workarea-sidebar-bg', '--rs-workarea-editor-bg', '--rs-workarea-surface-opacity', '--rs-workarea-plugin-bg', '--rs-menu-bg', '--rs-menu-active-bg', '--rs-menu-backdrop', '--rs-hover-bg'] as const;
function validImage(frame: BackgroundFrame) {
return frame && typeof frame.url === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.url)
&& Number.isFinite(frame.overlay) && frame.overlay >= -1 && frame.overlay <= 1
&& (frame.blurredUrl === undefined || (typeof frame.blurredUrl === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.blurredUrl)))
&& positions.includes(frame.position) && ['cover', 'contain', 'auto'].includes(frame.size);
}
function image(frame: BackgroundFrame) {
const shade = frame.overlay < 0 ? '255,255,255' : '0,0,0';
const overlay = `linear-gradient(rgba(${shade},${Math.abs(frame.overlay)}),rgba(${shade},${Math.abs(frame.overlay)}))`;
return { overlay, image: `${overlay}, url("${frame.url}")${frame.blurredUrl ? `, url("${frame.blurredUrl}")` : ''}`,
sizes: `100% 100%, ${frame.size}${frame.blurredUrl ? ', cover' : ''}`,
positions: `center, ${frame.position}${frame.blurredUrl ? ', center' : ''}` };
}
function copy(frame: BackgroundFrame): BackgroundFrame {
return { ...frame, ...(frame.previous ? { previous: { ...frame.previous } } : {}) };
}
function checkTarget(target: string) {
if (target !== 'app' && target !== '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.test(target)) {
throw new Error('Invalid background target.');
}
}
/**
* The background frames of one window, for each target. The Background feature (`src/lib/features/background/`) sets
* them, and Project Management reads the board targets. 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) {
this.body = body;
}
get(target: string): BackgroundFrame | null {
checkTarget(target);
const frame = [...(this.frames.get(target)?.values() ?? [])].at(-1);
return frame ? copy(frame) : null;
}
set(owner: symbol, target: string, frame: BackgroundFrame | null) {
checkTarget(target);
if (frame !== null && (!validImage(frame)
|| (frame.previous !== undefined && (!validImage(frame.previous) || 'previous' in frame.previous || 'transitionMs' in frame.previous))
|| (frame.transitionMs !== undefined && (!Number.isFinite(frame.transitionMs) || frame.transitionMs < 0 || frame.transitionMs > 5000)))) {
throw new Error('Invalid background frame. Use a blob URL and an overlay from -1 to 1.');
}
const owners = this.frames.get(target) ?? new Map<symbol, BackgroundFrame>();
const removed = owners.delete(owner);
if (frame) owners.set(owner, copy(frame));
if (owners.size) this.frames.set(target, owners);
else this.frames.delete(target);
if (frame || removed) this.changed(target);
}
removeOwner(owner: symbol) {
for (const [target, owners] of this.frames) {
if (!owners.delete(owner)) continue;
if (!owners.size) this.frames.delete(target);
this.changed(target);
}
}
subscribe(listener: (target: string) => void): () => void {
this.listeners.add(listener);
return () => { this.listeners.delete(listener); };
}
private changed(target: string) {
if (target === 'app') this.applyApp();
for (const listener of [...this.listeners]) {
try { listener(target); } catch { /* A subscriber must not prevent cleanup or other subscribers. */ }
}
}
private applyApp() {
const frame = this.get('app');
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 = () => {
for (const [key, value, priority] of previous) {
if (value) body.style.setProperty(key, value, priority);
else body.style.removeProperty(key);
}
};
}
const { overlay, image: currentImage, sizes, positions: layerPositions } = image(frame);
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-hover-bg', 'var(--rs-image-hover-bg)');
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')) {
// 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' });
}
}
}
}
}
export const backgroundHub = new BackgroundHub();