Something went wrong. Try again.
Rewild Your Web forked from me.webbeef.org/browser.html
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251// SPDX-License-Identifier: AGPL-3.0-or-later
/** * Vault-backed wallpapers, multi-device. * * Images live in the shared `wallpapers` folder, one resource per image, * synced like anything else. The *choice* is per-device: this device keeps * a `current-wallpaper` record in its device folder (see device_store.js) * whose content is the chosen wallpaper's id. Devices never fight over a * shared `current` tag, and two devices can pick the same image (the vault * deduplicates identical bytes). * * Fallback when this device has no pointer: the shell's bundled default. * * The manager answers "what is current" with a blob URL and re-reads through * both folders' `onchange`, so the ambient layer follows selections made * anywhere, including another page. Repaints are keyed on the wallpaper * id, not the blob URL: a change that does not move the selection costs two * small metadata reads, not an image fetch (and its pinned bitmap). */
import { deviceStore } from "./vault/device_store.js";
const COLLECTION = "wallpapers";const POINTER_KEY = "current-wallpaper";
/// The bundled default wallpaper's URL. When no wallpaper is stored in the/// vault the shell paints it directly (no object URL needed; it does not/// move between page and device).export const DEFAULT_WALLPAPER_URL = "beaver://homescreen/resources/wallpapers/adrien-olichon-hEjbjw9PpHE-unsplash.jpg";
const DEFAULT_BACKGROUND = `url(${DEFAULT_WALLPAPER_URL}) center/cover no-repeat`;
export class WallpaperManager { constructor() { this._collection = null; this._currentWallpaperId = undefined; // undefined: never resolved this._currentUrl = null; // object URL of the current image this._currentBlob = null; // the image itself, for MessagePort handoff this._bgCache = new Map(); // wallpaper id -> object URL background this._listeners = new Set(); }
/** The wallpapers pool, or null when there is no vault. */ async _coll() { if (!navigator.vault) { return null; } if (!this._collection) { this._collection = await navigator.vault.open(COLLECTION); this._collection.onchange = () => this._refreshCurrent(); } return this._collection; }
/** This device's folder, or null when the vault has no device id. */ async _device() { const folder = await deviceStore.folder(); if (folder) { folder.onchange = () => this._refreshCurrent(); } return folder; }
/** * The effective current wallpaper id: this device's pointer when it names * an existing pool resource (a dangling one is none), else null. */ async _currentId() { const coll = await this._coll(); if (!coll) { return null; } if (!(await this._device())) { return null; } const pointer = await deviceStore.getText(POINTER_KEY); if (!pointer) { return null; } const id = pointer.trim(); return (await coll.meta(id)) ? id : null; }
/** * Called when the current wallpaper might have changed. Repaints only * when the wallpaper *id* moved: object URLs are minted per call, so * comparing them would fetch and re-decode the same image on every * onchange. Revokes the replaced object URL, which is why listeners must * repaint on notify. */ async _refreshCurrent() { const id = await this._currentId(); if (id === this._currentWallpaperId) { return; } this._currentWallpaperId = id; const url = await this._fetchCurrentUrl(id); if (this._currentUrl && this._currentUrl.startsWith("blob:")) { URL.revokeObjectURL(this._currentUrl); } this._currentUrl = url; const bg = url ? `url(${url}) center/cover no-repeat` : DEFAULT_BACKGROUND; for (const listener of this._listeners) { listener(bg); } }
async _fetchCurrentUrl(id) { if (!id) { this._currentBlob = null; return null; } const blob = await (await this._coll()).get(id); this._currentBlob = blob; return blob ? URL.createObjectURL(blob) : null; }
/** CSS background shorthand of the current wallpaper, or the default's. */ async currentBackground() { if (this._currentUrl) { return `url(${this._currentUrl}) center/cover no-repeat`; } await this._refreshCurrent(); return this._currentUrl ? `url(${this._currentUrl}) center/cover no-repeat` : DEFAULT_BACKGROUND; }
/** All wallpapers: `{id, title, current}`; no bytes. */ async list() { const coll = await this._coll(); if (!coll) { return []; } const [currentId, entries] = await Promise.all([ this._currentId(), coll.list({ limit: 1000 }), ]); return entries.map((e) => ({ id: e.id, title: e.meta.title || e.meta.name || e.id, current: e.id === currentId, })); }
/** * CSS background shorthand for one pool wallpaper, or null (no vault, or * no such resource). For per-desk references. Object URLs are cached per * id: re-fetching would re-decode and pin another bitmap (the image * cache never evicts). Misses are not cached, so a wallpaper that * arrives later (sync) still resolves. */ async backgroundFor(id) { if (this._bgCache.has(id)) { return this._bgCache.get(id); } const coll = await this._coll(); if (!coll) { return null; } const blob = await coll.get(id); if (!blob) { return null; } const bg = `url(${URL.createObjectURL(blob)}) center/cover no-repeat`; this._bgCache.set(id, bg); return bg; }
/** * Fetch a web image and store it. With `select` (the default) also makes * it this device's current wallpaper; pass `select: false` when the * caller references it itself (a desk's own wallpaper, ...). * * Fetched from this page's context — the system page is privileged, so * cross-origin image fetches work; `data:` never needs a network round * trip either way. */ async addFromUrl(url, { select = true } = {}) { const response = await fetch(url); if (!response.ok) { throw new Error(`fetch ${url}: ${response.status}`); } const blob = await response.blob(); const filename = (() => { try { const path = new URL(url).pathname; return decodeURIComponent(path.split("/").filter(Boolean).pop() || ""); } catch { return ""; } })(); return this.addFromBlob(blob, filename || null, { select }); }
/** * Store an image. Returns its resource id. * Re-adding identical bytes is cheap: content-addressed writes of identical * representations are no-op commits in the vault. */ async addFromBlob(blob, filename = null, { select = true } = {}) { const coll = await this._coll(); if (!coll) { throw new Error("no vault"); } // The vault mints the id; the filename (when known) is the name, inline. const id = await coll.create(blob, filename ? { name: filename } : {}); if (select) { await this.select(id); } return id; }
/** Make `id` this device's wallpaper: write this device's pointer. */ async select(id) { const coll = await this._coll(); if (!coll) { return; } if (!(await coll.meta(id))) { throw new Error(`wallpaper ${id} does not exist`); } if (!(await deviceStore.putText(POINTER_KEY, id))) { console.warn("no vault device id: wallpaper selection not saved"); return; } // The write is the change: refresh now rather than only when the vault's // change event loops back to this page (which it also will; the refresh // is idempotent, by id identity). await this._refreshCurrent(); }
/** The current image itself, for callers that pass it on (MessagePort). */ currentBlob() { return this._currentBlob; }
/** Register `fn(url)` for repaints; also used to hand the first paint. */ onChange(fn) { this._listeners.add(fn); if (this._currentUrl) { fn(this._currentUrl); } return () => this._listeners.delete(fn); }}
export const wallpaperManager = new WallpaperManager();