fix: bind skin loading to the current page and choice

This commit is contained in:
illusia committed 2026-10-01 17:00:05 +08:00
1 parent 15e22d3099
commit 9dfded0fb7
13 files changed
+639 -195

No files matched your search

@@ -0,0 +1,81 @@
import assert from "node:assert/strict";
import { before, after, beforeEach, test } from "node:test";
import { setImmediate as nextTurn } from "node:timers/promises";
import { loadLocalPreferences, saveInstalledSkin, saveLocalPreferences } from "./local-persistence.js";
import type { InstalledSkin } from "./skin-pack.js";
// Control IndexedDB's request and transaction completion separately. These tests
// exercise the public storage APIs, including cancellation before opening the DB.
const descriptor = Object.getOwnPropertyDescriptor(globalThis, "indexedDB");
let opening: any;
let transactions: Transaction[] = [];
class Transaction {
oncomplete?: () => void; onerror?: () => void; onabort?: () => void;
getRequest: any; putRequest: any; written: unknown; aborted = false;
objectStore() { return {
get: () => this.getRequest = {},
put: (value: unknown) => { this.written = value; return this.putRequest = {}; },
}; }
abort() { this.aborted = true; this.onabort?.(); }
read(value: unknown) { this.getRequest.result = value; this.getRequest.onsuccess(); }
writtenSuccessfully() { this.putRequest.onsuccess(); }
commit() { assert.equal(this.aborted, false); this.oncomplete?.(); }
}
const database = { transaction: () => { const tx = new Transaction(); transactions.push(tx); return tx; } };
const sample = { id: "sample.a", css: "", assets: {} } as InstalledSkin;
before(() => Object.defineProperty(globalThis, "indexedDB", { configurable: true, value: {
open: () => opening = { result: database },
} }));
beforeEach(() => { transactions = []; });
after(() => {
if (descriptor) Object.defineProperty(globalThis, "indexedDB", descriptor);
else Reflect.deleteProperty(globalThis, "indexedDB");
});
test("cancelling a skin while IndexedDB opens prevents the delayed write", async () => {
const owner = new AbortController();
const pending = saveInstalledSkin(sample, owner.signal);
const rejected = assert.rejects(pending, { name: "AbortError" });
owner.abort(); opening.onsuccess();
await rejected;
assert.equal(transactions.length, 0);
});
test("a successful request is not reported as durable until its transaction commits", async () => {
let settled = false;
const pending = saveInstalledSkin(sample).then(() => { settled = true; });
await nextTurn(); const tx = transactions[0];
tx.writtenSuccessfully(); await nextTurn();
assert.equal(settled, false);
tx.commit(); await pending;
assert.equal(settled, true);
});
test("retiring a skin aborts its outstanding write transaction", async () => {
const owner = new AbortController();
const pending = saveInstalledSkin(sample, owner.signal);
const rejected = assert.rejects(pending, { name: "AbortError" });
await nextTurn(); const tx = transactions[0];
tx.writtenSuccessfully(); owner.abort(); await rejected;
assert.equal(tx.aborted, true);
});
test("skin preferences merge current unrelated fields in the same transaction", async () => {
const pending = saveLocalPreferences({ schemaVersion: 1, skinId: "builtin.dark" });
await nextTurn(); assert.equal(transactions.length, 1);
const tx = transactions[0];
tx.read({ schemaVersion: 1, language: "de", inputGain: 0.5, volumesByUid: { member: 0.2 } });
assert.deepEqual(tx.written, { id: "singleton", schemaVersion: 1, language: "de", inputGain: 0.5, skinId: "builtin.dark", volumesByUid: { member: 0.2 } });
tx.writtenSuccessfully(); tx.commit(); await pending;
});
test("cancelling a pending preference merge aborts it without blocking the caller", async () => {
const owner = new AbortController();
const pending = saveLocalPreferences({ schemaVersion: 1, skinId: "sample.a" }, owner.signal);
await nextTurn(); const tx = transactions[0];
owner.abort(); await pending;
assert.equal(tx.aborted, true);
assert.equal(tx.written, undefined);
});
test("storage read success still returns its original data after transaction completion", async () => {
const pending = loadLocalPreferences();
await nextTurn(); const tx = transactions[0];
tx.read({ schemaVersion: 1, skinId: "builtin.dark" }); tx.commit();
assert.deepEqual(await pending, { schemaVersion: 1, skinId: "builtin.dark", volumesByUid: {} });
});
+27 -16
View File
@@ -82,12 +82,22 @@ function openDatabase(): Promise<IDBDatabase> {
return databasePromise!;
}
async function request<T>(storeName: string, mode: IDBTransactionMode, action: (store: IDBObjectStore, resolve: (value: T) => void, reject: (reason?: unknown) => void) => void): Promise<T> {
async function request<T>(storeName: string, mode: IDBTransactionMode, action: (store: IDBObjectStore, resolve: (value: T) => void, reject: (reason?: unknown) => void) => void, signal?: AbortSignal): Promise<T> {
signal?.throwIfAborted();
const database = await openDatabase();
signal?.throwIfAborted();
return new Promise<T>((resolve, reject) => {
const transaction = database.transaction(storeName, mode);
action(transaction.objectStore(storeName), resolve, reject);
transaction.onerror = () => reject(transaction.error ?? new Error("Local storage transaction failed"));
let result: T;
const abort = () => { try { transaction.abort(); } catch { /* Already completed. */ } };
const cleanup = () => signal?.removeEventListener("abort", abort);
const fail = (error: unknown) => { cleanup(); reject(error); };
transaction.oncomplete = () => { cleanup(); resolve(result); };
transaction.onerror = () => fail(transaction.error ?? new Error("Local storage transaction failed"));
transaction.onabort = () => fail(signal?.reason ?? transaction.error ?? new Error("Local storage transaction aborted"));
signal?.addEventListener("abort", abort, { once: true });
try { action(transaction.objectStore(storeName), value => { result = value; }, fail); }
catch (error) { abort(); fail(error); }
});
}
@@ -150,19 +160,20 @@ export async function loadLocalPreferences(): Promise<LocalPreferences> {
}
}
export async function saveLocalPreferences(preferences: LocalPreferences): Promise<void> {
export async function saveLocalPreferences(preferences: LocalPreferences, signal?: AbortSignal): Promise<void> {
try {
const existing = await loadLocalPreferences();
await request("preferences", "readwrite", (store, resolve, reject) => {
const put = store.put({
...existing,
...preferences,
volumesByUid: { ...existing.volumesByUid, ...preferences.volumesByUid },
id: PREFERENCES_KEY,
});
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
// Read and merge in one transaction so unrelated concurrent settings survive.
const get = store.get(PREFERENCES_KEY);
get.onerror = () => reject(get.error);
get.onsuccess = () => {
const existing = get.result?.schemaVersion === 1 ? get.result as LocalPreferences : {} as Partial<LocalPreferences>;
const put = store.put({ ...existing, ...preferences,
volumesByUid: { ...existing.volumesByUid, ...preferences.volumesByUid }, id: PREFERENCES_KEY });
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
};
}, signal);
} catch {
// Local preference persistence is optional and never blocks joining.
}
@@ -193,12 +204,12 @@ export async function getInstalledSkin(id: string): Promise<InstalledSkin | null
}
}
export async function saveInstalledSkin(skin: InstalledSkin): Promise<void> {
export async function saveInstalledSkin(skin: InstalledSkin, signal?: AbortSignal): Promise<void> {
await request("skins", "readwrite", (store, resolve, reject) => {
const put = store.put(skin);
put.onsuccess = () => resolve(undefined);
put.onerror = () => reject(put.error);
});
}, signal);
}
export async function removeInstalledSkin(id: string): Promise<void> {
+15 -8
View File
@@ -1,4 +1,5 @@
import type { SkinCatalogEntry } from "../../../src/shared/skin-catalog.js";
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
export type { SkinCatalogEntry } from "../../../src/shared/skin-catalog.js";
export const BUILTIN_ILLUSIA_SKIN_ID = "community.illusia-voice";
@@ -47,6 +48,7 @@ const BUILTIN_ILLUSIA_PACKAGE_URL = "/skins/illusia-voice.wskin";
let publicDirectoryLoaded = false;
let publicEnabledSkinIds = new Set<string>(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
let publicDefaultSkinId = "builtin.light";
let pendingDirectory: ReturnType<typeof createSkinOperation> | null = null;
export function getPublicDefaultSkinId(): string {
return isPublicSkinEnabled(publicDefaultSkinId) ? publicDefaultSkinId : "builtin.light";
@@ -61,15 +63,16 @@ export function getBundledSkinPackageUrl(id: string): string | null {
return id === BUILTIN_ILLUSIA_SKIN_ID ? BUILTIN_ILLUSIA_PACKAGE_URL : null;
}
export async function listPublicSkins(): Promise<SkinCatalogEntry[]> {
publicDirectoryLoaded = false;
publicEnabledSkinIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
publicDefaultSkinId = "builtin.light";
export async function listPublicSkins(options: SkinLoadOptions = {}): Promise<SkinCatalogEntry[]> {
options.signal?.throwIfAborted();
pendingDirectory?.cancel();
const operation = createSkinOperation(options);
pendingDirectory = operation;
try {
const response = await fetch("/api/skins", { headers: { accept: "application/json" }, cache: "no-cache" });
if (!response.ok) return BUILTIN_SKIN_CATALOG;
const payload: unknown = await response.json();
if (!payload || typeof payload !== "object" || !Array.isArray((payload as { skins?: unknown }).skins)) return BUILTIN_SKIN_CATALOG;
const response = await operation.wait(fetch("/api/skins", { headers: { accept: "application/json" }, cache: "no-cache", signal: operation.signal }));
if (!response.ok) throw new Error("Skin directory unavailable");
const payload: unknown = await operation.wait(response.json());
if (!payload || typeof payload !== "object" || !Array.isArray((payload as { skins?: unknown }).skins)) throw new Error("Invalid skin directory");
const directorySkins = (payload as { skins: unknown[] }).skins.flatMap((value) => {
if (!value || typeof value !== "object") return [];
const skin = value as Record<string, unknown>;
@@ -98,9 +101,13 @@ export async function listPublicSkins(): Promise<SkinCatalogEntry[]> {
publicDefaultSkinId = typeof requestedDefault === "string" && publicEnabledSkinIds.has(requestedDefault) ? requestedDefault : "builtin.light";
return [...BUILTIN_SKIN_CATALOG, ...directorySkins.filter((skin) => skin.enabled)];
} catch {
operation.check();
publicDirectoryLoaded = false;
publicEnabledSkinIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
publicDefaultSkinId = "builtin.light";
return BUILTIN_SKIN_CATALOG;
} finally {
operation.finish();
if (pendingDirectory === operation) pendingDirectory = null;
}
}
+38
View File
@@ -0,0 +1,38 @@
export const SKIN_LOAD_TIMEOUT_MS = 8_000;
export interface SkinLoadOptions {
signal?: AbortSignal;
timeoutMs?: number;
}
/** A deadline also covers non-abortable storage, parsing and response readers. */
export function createSkinOperation({ signal: parent, timeoutMs = SKIN_LOAD_TIMEOUT_MS }: SkinLoadOptions = {}) {
const controller = new AbortController();
const { signal } = controller;
const cancel = () => controller.abort(new DOMException("Skin operation cancelled", "AbortError"));
const parentAborted = () => controller.abort(parent?.reason);
let timer: ReturnType<typeof setTimeout> | undefined;
const finish = () => {
if (timer !== undefined) clearTimeout(timer);
timer = undefined;
parent?.removeEventListener("abort", parentAborted);
};
signal.addEventListener("abort", finish, { once: true });
if (parent?.aborted) parentAborted();
else {
parent?.addEventListener("abort", parentAborted, { once: true });
timer = setTimeout(() => controller.abort(new DOMException("Skin loading timed out", "TimeoutError")), timeoutMs);
}
function check() { signal.throwIfAborted(); }
async function wait<T>(value: PromiseLike<T>): Promise<T> {
// Attach a rejection handler even when cancellation happened just before wait.
return new Promise<T>((resolve, reject) => {
const aborted = () => reject(signal.reason);
const done = () => signal.removeEventListener("abort", aborted);
signal.addEventListener("abort", aborted, { once: true });
Promise.resolve(value).then(result => { done(); signal.aborted ? reject(signal.reason) : resolve(result); }, error => { done(); reject(error); });
if (signal.aborted) { done(); aborted(); }
});
}
return { signal, check, wait, cancel, finish };
}
+45 -12
View File
@@ -3,6 +3,7 @@ import type { InstalledSkin } from "./skin-pack.js";
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
export const BUILTIN_LIGHT_SKIN = "builtin.light";
@@ -12,13 +13,16 @@ const CUSTOM_BASE_STYLE_ID = "webspeak-active-custom-skin-base";
let activeAssetUrls: string[] = [];
let criticalControlObserver: MutationObserver | null = null;
let pendingActivation: ReturnType<typeof createSkinOperation> | null = null;
export function getStoredSkinId(): string | null {
return typeof localStorage === "undefined" ? null : localStorage.getItem(ACTIVE_SKIN_KEY);
try { return typeof localStorage === "undefined" ? null : localStorage.getItem(ACTIVE_SKIN_KEY); }
catch { return null; }
}
export function storeSkinId(id: string): void {
if (typeof localStorage !== "undefined") localStorage.setItem(ACTIVE_SKIN_KEY, id);
try { if (typeof localStorage !== "undefined") localStorage.setItem(ACTIVE_SKIN_KEY, id); }
catch { /* Storage is optional; the current page can still use the skin. */ }
}
export async function activateStoredSkin(): Promise<InstalledSkin | null> {
@@ -29,9 +33,25 @@ export async function activateStoredSkin(): Promise<InstalledSkin | null> {
return activateSkin(selectedId);
}
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.5-preview"): Promise<InstalledSkin | null> {
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.5-preview", options: SkinLoadOptions = {}): Promise<InstalledSkin | null> {
// An already retired page must not cancel a newer page's activation.
options.signal?.throwIfAborted();
pendingActivation?.cancel();
const operation = createSkinOperation(options);
pendingActivation = operation;
try {
return await prepareAndActivate(id, expectedVersion, appVersion, operation);
} finally {
operation.finish();
if (pendingActivation === operation) pendingActivation = null;
}
}
async function prepareAndActivate(id: string, expectedVersion: string | undefined, appVersion: string,
operation: ReturnType<typeof createSkinOperation>): Promise<InstalledSkin | null> {
operation.check();
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
clearCustomSkinStyle();
removeCustomSkinStyle();
applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light");
markCoreControls();
storeSkinId(id);
@@ -42,30 +62,34 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
return fallBackToBuiltin();
}
let skin = await getInstalledSkin(id);
let skin = await operation.wait(getInstalledSkin(id));
if (!skin || (expectedVersion && skin.version !== expectedVersion)) {
try {
const packageUrl = getBundledSkinPackageUrl(id) ?? `/api/skins/${encodeURIComponent(id)}/package`;
const response = await fetch(packageUrl, { cache: "no-cache" });
const response = await operation.wait(fetch(packageUrl, { cache: "no-cache", signal: operation.signal }));
if (!response.ok) throw new Error("Skin package is no longer available.");
const archive = await response.blob();
const archive = await operation.wait(response.blob());
const file = new File([archive], `${id}.wskin`, { type: "application/octet-stream" });
const { importSkinPack } = await import("./skin-pack.js");
const downloaded = await importSkinPack(file);
const { importSkinPack } = await operation.wait(import("./skin-pack.js"));
const downloaded = await operation.wait(importSkinPack(file));
if (downloaded.id !== id) throw new Error("Skin package ID does not match its catalog entry.");
if (expectedVersion && downloaded.version !== expectedVersion) throw new Error("Skin package version does not match its catalog entry.");
skin = downloaded;
await saveInstalledSkin(downloaded).catch(() => undefined);
await operation.wait(saveInstalledSkin(downloaded, operation.signal).catch(() => undefined));
} catch {
operation.check();
if (!skin) return fallBackToBuiltin();
}
}
if (!isVersionCompatible(appVersion, skin.minAppVersion)) return fallBackToBuiltin();
let candidateUrls: string[] = [];
try {
const { resolveSkinCssAssets } = await import("./skin-pack.js");
const { resolveSkinCssAssets } = await operation.wait(import("./skin-pack.js"));
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
candidateUrls = compiled.objectUrls;
operation.check();
// A community skin is a complete appearance choice, not an overlay on the
// previously selected day/night skin. Keep the document theme (used by the
// independent admin appearance) but give unstyled public parts a light,
@@ -94,23 +118,32 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
style.textContent = compiled.css;
const previousAssetUrls = activeAssetUrls;
activeAssetUrls = compiled.objectUrls;
candidateUrls = [];
previousAssetUrls.forEach((url) => URL.revokeObjectURL(url));
storeSkinId(id);
return skin;
} catch {
candidateUrls.forEach((url) => URL.revokeObjectURL(url));
operation.check();
return fallBackToBuiltin();
}
}
function fallBackToBuiltin(): null {
const fallback = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
clearCustomSkinStyle();
removeCustomSkinStyle();
applyTheme(fallback === BUILTIN_DARK_SKIN ? "dark" : "light");
storeSkinId(fallback);
return null;
}
export function clearCustomSkinStyle(): void {
pendingActivation?.cancel();
pendingActivation = null;
removeCustomSkinStyle();
}
function removeCustomSkinStyle(): void {
document.getElementById(CUSTOM_STYLE_ID)?.remove();
document.getElementById(CUSTOM_BASE_STYLE_ID)?.remove();
activeAssetUrls.forEach((url) => URL.revokeObjectURL(url));
+3 -1
View File
@@ -19,7 +19,9 @@ export function getBuiltinSkinCss(theme: Exclude<ThemeMode, "system">): string {
}
export function getStoredTheme(): ThemeMode {
const value = typeof localStorage === "undefined" ? "" : localStorage.getItem(THEME_KEY);
let value: string | null = null;
try { value = typeof localStorage === "undefined" ? null : localStorage.getItem(THEME_KEY); }
catch { /* A restricted browser still has a usable system theme. */ }
return value === "light" || value === "dark" || value === "system" ? value : "system";
}