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

+104
View File
@@ -0,0 +1,104 @@
import { onScopeDispose, ref, shallowRef, type Ref } from "vue";
import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
import { BUILTIN_SKIN_CATALOG, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, clearCustomSkinStyle, getStoredSkinId } from "../services/skin-runtime.js";
import { createSkinOperation } from "../services/skin-operation.js";
import { applyTheme, getStoredTheme, isDarkTheme, saveTheme } from "../services/theme.js";
import type { InstalledSkin } from "../services/skin-pack.js";
interface PublicSkinOptions {
activeSkin?: Ref<InstalledSkin | null>;
themeMode?: Ref<"light" | "dark">;
appVersion?: () => string;
timeoutMs?: number;
}
const readChoice = () => { try { return localStorage.getItem("webspeak:skin-choice"); } catch { return null; } };
const builtin = (id: string) => id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN;
const fallbackId = () => isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
/** One page owns initialization, choices and their late responses, including persistence. */
export function usePublicSkin(options: PublicSkinOptions = {}) {
const activeSkin = options.activeSkin ?? shallowRef<InstalledSkin | null>(null);
const stored = getStoredSkinId();
const activeSkinId = ref(stored ?? fallbackId());
const skinReady = ref(Boolean(stored && builtin(stored)));
const installedSkins = ref<InstalledSkin[]>([]);
const catalogSkins = ref<SkinCatalogEntry[]>([...BUILTIN_SKIN_CATALOG]);
let current: ReturnType<typeof createSkinOperation> | undefined;
let disposed = false;
const owns = (operation: ReturnType<typeof createSkinOperation>) => !disposed && current === operation;
function cancel() { current?.cancel(); current = undefined; }
function begin() {
cancel();
return current = createSkinOperation({ timeoutMs: options.timeoutMs });
}
onScopeDispose(() => { disposed = true; cancel(); });
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true) {
operation.check();
const entry = catalogSkins.value.find(skin => skin.id === id);
const skin = await operation.wait(activateSkin(id, entry?.version, options.appVersion?.(), { signal: operation.signal }));
if (!owns(operation)) return;
activeSkin.value = skin;
activeSkinId.value = skin?.id ?? (builtin(id) ? id : fallbackId());
const mode = activeSkinId.value === BUILTIN_LIGHT_SKIN ? "light"
: activeSkinId.value === BUILTIN_DARK_SKIN ? "dark" : isDarkTheme(getStoredTheme()) ? "dark" : "light";
if (options.themeMode) options.themeMode.value = mode;
if (persist) void saveLocalPreferences({ schemaVersion: 1, skinId: activeSkinId.value,
...(options.themeMode ? { theme: mode } : {}) }, operation.signal).catch(() => undefined);
}
async function recover(error: unknown, operation: ReturnType<typeof createSkinOperation>) {
if (!owns(operation) || (error as { name?: string })?.name === "AbortError") return;
// Retire every stage of the old operation before installing a fallback.
operation.cancel();
const fallback = begin();
try { await apply(fallbackId(), fallback, false); }
catch { /* A newer selection or page can retire the fallback as well. */ }
finally { if (owns(fallback)) skinReady.value = true; fallback.finish(); }
}
async function initialize() {
if (disposed) return;
const operation = begin();
try {
const [preferences, installed, available] = await operation.wait(Promise.all([
loadLocalPreferences(), listInstalledSkins(), listPublicSkins({ signal: operation.signal }),
]));
installedSkins.value = installed;
catalogSkins.value = available;
if (options.themeMode && !localStorage.getItem("webspeak:theme")) {
if (preferences.theme) options.themeMode.value = isDarkTheme(preferences.theme) ? "dark" : "light";
saveTheme(options.themeMode.value);
}
// Only an explicit user choice overrides the instance default.
const choice = readChoice();
await apply(choice && isPublicSkinEnabled(choice) ? choice : getPublicDefaultSkinId(), operation);
} catch (error) { await recover(error, operation); }
finally { if (owns(operation)) skinReady.value = true; operation.finish(); }
}
async function select(id: string) {
if (disposed) return;
const operation = begin();
try {
try { localStorage.setItem("webspeak:skin-choice", id); } catch { /* Optional storage. */ }
await apply(id, operation);
} catch (error) { await recover(error, operation); }
finally { if (owns(operation)) skinReady.value = true; operation.finish(); }
}
async function reset() {
if (disposed) return;
const operation = begin();
clearCustomSkinStyle();
activeSkin.value = null;
installedSkins.value = [];
catalogSkins.value = [...BUILTIN_SKIN_CATALOG];
const mode = isDarkTheme("system") ? "dark" : "light";
if (options.themeMode) options.themeMode.value = mode;
applyTheme(mode);
activeSkinId.value = mode === "dark" ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
skinReady.value = true;
try { catalogSkins.value = await operation.wait(listPublicSkins({ signal: operation.signal })); }
catch { /* Reset remains usable even if refreshing the optional catalog fails. */ }
finally { operation.finish(); }
}
return { activeSkin, activeSkinId, skinReady, installedSkins, catalogSkins, initialize, select, cancel, reset };
}
@@ -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";
}
+8 -52
View File
@@ -32,15 +32,14 @@
</template>
<script setup lang="ts">
import { computed, onMounted, ref, shallowRef } from "vue";
import { computed, onMounted, ref } from "vue";
import Icon from "../components/Icon.vue";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
import SkinSwitcher, { type SkinOption } from "../components/SkinSwitcher.vue";
import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "../services/local-persistence.js";
import { BUILTIN_ILLUSIA_SKIN_ID, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, getStoredSkinId } from "../services/skin-runtime.js";
import type { InstalledSkin } from "../services/skin-pack.js";
import { getStoredTheme, isDarkTheme } from "../services/theme.js";
import { saveLocalPreferences } from "../services/local-persistence.js";
import { BUILTIN_ILLUSIA_SKIN_ID, isPublicSkinEnabled } from "../services/skin-catalog.js";
import { BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN } from "../services/skin-runtime.js";
import { usePublicSkin } from "../composables/usePublicSkin.js";
type Language = "zh" | "en" | "de" | "ru" | "ja";
const illusiaSkinLabels: Record<Language, string> = { zh: "ILLUSIA 风", en: "ILLUSIA style", de: "ILLUSIA-Stil", ru: "Стиль ILLUSIA", ja: "ILLUSIA スタイル" };
@@ -49,12 +48,8 @@ type Tab = "channel" | "server";
const storedLanguage = localStorage.getItem("webspeak:language");
const language = ref<Language>(storedLanguage === "en" || storedLanguage === "de" || storedLanguage === "ru" || storedLanguage === "ja" ? storedLanguage : "zh");
const baseCopy = computed(() => language.value === "zh" ? zh : language.value === "de" ? de : language.value === "ru" ? ru : language.value === "ja" ? ja : en);
const activeSkin = shallowRef<InstalledSkin | null>(null);
const storedSkinId = getStoredSkinId();
const activeSkinId = ref(storedSkinId ?? (isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN));
const skinReady = ref(storedSkinId === BUILTIN_LIGHT_SKIN || storedSkinId === BUILTIN_DARK_SKIN);
const installedSkins = ref<InstalledSkin[]>([]);
const catalogSkins = ref<SkinCatalogEntry[]>([]);
const { activeSkin, activeSkinId, skinReady, installedSkins, catalogSkins,
select: onSkinChange, initialize: initializeSkin } = usePublicSkin();
const skinOptions = computed<SkinOption[]>(() => [
...catalogSkins.value.map((skin) => ({
value: skin.id,
@@ -103,46 +98,7 @@ const selectedChannel = computed(() => channels.find((channel) => channel.id ===
const visibleMessages = computed(() => activeTab.value === "channel" ? messages.value : []);
function persistLanguage() { localStorage.setItem("webspeak:language", language.value); void saveLocalPreferences({ schemaVersion: 1, language: language.value }); }
async function onSkinChange(skinId: string) {
localStorage.setItem("webspeak:skin-choice", skinId);
const catalogSkin = catalogSkins.value.find((skin) => skin.id === skinId);
activeSkin.value = await activateSkin(skinId, catalogSkin?.version);
activeSkinId.value = getStoredSkinId() ?? skinId;
void saveLocalPreferences({ schemaVersion: 1, skinId: activeSkinId.value });
}
onMounted(async () => {
const catalogPromise = listPublicSkins().catch(() => []);
try {
const [preferences, installed, available] = await Promise.all([loadLocalPreferences(), listInstalledSkins(), catalogPromise]);
installedSkins.value = installed;
catalogSkins.value = available;
// Only a deliberate choice should override the instance default. The active
// skin and local preference also contain automatically applied defaults.
const savedSkinId = localStorage.getItem("webspeak:skin-choice");
const selectedId = savedSkinId && isPublicSkinEnabled(savedSkinId) ? savedSkinId : getPublicDefaultSkinId();
const selectedSkin = available.find((skin) => skin.id === selectedId);
activeSkinId.value = selectedId;
activeSkin.value = await activateSkin(selectedId, selectedSkin?.version);
activeSkinId.value = getStoredSkinId() ?? selectedId;
} catch {
activeSkin.value = null;
activeSkinId.value = isDarkTheme(getStoredTheme()) ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
await activateSkin(activeSkinId.value).catch(() => undefined);
} finally {
skinReady.value = true;
}
void catalogPromise.then(async (available) => {
catalogSkins.value = available;
const selected = available.find((skin) => skin.id === activeSkinId.value);
const installed = installedSkins.value.find((skin) => skin.id === activeSkinId.value);
if (!selected || !installed || installed.version === selected.version) return;
activeSkin.value = await activateSkin(selected.id, selected.version);
if (getStoredSkinId() !== selected.id) return;
activeSkinId.value = getStoredSkinId() ?? selected.id;
installedSkins.value = await listInstalledSkins();
}).catch(() => undefined);
});
onMounted(() => { void initializeSkin(); });
function selectChannel(id: string) { selectedChannelId.value = id; activeTab.value = "channel"; }
function toggleSpeaking() { speakingId.value = speakingId.value ? "" : selectedChannel.value.members[0]?.id ?? ""; }
function messageText(message: DemoMessage): string { return language.value === "zh" ? message.zhText ?? message.text : language.value === "ru" ? message.ruText ?? message.enText ?? message.text : language.value === "ja" ? message.jaText ?? message.enText ?? message.text : message.enText ?? message.text; }
+8 -84
View File
@@ -389,6 +389,7 @@ import { computed, onMounted, onUnmounted, reactive, ref, shallowRef, watch } fr
import Icon from "../components/Icon.vue";
import WebClientHeader from "../components/web-client/WebClientHeader.vue";
import IdentityImportDialog from "../components/web-client/IdentityImportDialog.vue";
import { usePublicSkin } from "../composables/usePublicSkin.js";
import { useWebClientIdentity } from "../composables/useWebClientIdentity.js";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
import SkinSwitcher, { type SkinOption } from "../components/SkinSwitcher.vue";
@@ -404,10 +405,10 @@ import { useWebClientI18n } from "../composables/useWebClientI18n.js";
import { useWebClientPublicConfig } from "../composables/useWebClientPublicConfig.js";
import { useWebClientServerHistory } from "../composables/useWebClientServerHistory.js";
import { getInitialLanguage, type Language } from "../i18n/web-client.js";
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, listInstalledSkins, loadLocalPreferences, loadStoredIdentity, removeStoredIdentity, saveLocalPreferences, saveStoredIdentity } from "../services/local-persistence.js";
import { clearLocalData as clearStoredLocalData, isLocalPersistenceAvailable, loadLocalPreferences, loadStoredIdentity, removeStoredIdentity, saveLocalPreferences, saveStoredIdentity } from "../services/local-persistence.js";
import type { InstalledSkin, SkinHomeCopy } from "../services/skin-pack.js";
import { getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, clearCustomSkinStyle, getStoredSkinId } from "../services/skin-runtime.js";
import { isPublicSkinEnabled } from "../services/skin-catalog.js";
import { BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN } from "../services/skin-runtime.js";
import { applyTheme, getStoredTheme, isDarkTheme, saveTheme, type ThemeMode } from "../services/theme.js";
import { DEFAULT_TEAM_SPEAK_PORT, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
@@ -585,11 +586,8 @@ function resolveSkinMode(theme: ThemeMode): SkinMode {
const themeMode = ref<SkinMode>(resolveSkinMode(getStoredTheme()));
applyTheme(themeMode.value);
if (localStorage.getItem("webspeak:theme") === "system") saveTheme(themeMode.value);
const storedSkinId = getStoredSkinId();
const activeSkinId = ref(storedSkinId ?? (themeMode.value === "dark" ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN));
const skinReady = ref(storedSkinId === BUILTIN_LIGHT_SKIN || storedSkinId === BUILTIN_DARK_SKIN);
const installedSkins = ref<InstalledSkin[]>([]);
const catalogSkins = ref<SkinCatalogEntry[]>([]);
const publicSkin = usePublicSkin({ activeSkin, themeMode, appVersion: () => appVersion.value });
const { activeSkinId, skinReady, installedSkins, catalogSkins, select: onSkinChange, initialize: initializeSkin } = publicSkin;
const skinOptions = computed<SkinOption[]>(() => [
...catalogSkins.value.map((skin) => ({
value: skin.id,
@@ -685,75 +683,6 @@ function persistLanguage() {
void saveLocalPreferences({ schemaVersion: 1, language: language.value });
}
async function onSkinChange(skinId: string) {
localStorage.setItem("webspeak:skin-choice", skinId);
activeSkinId.value = skinId;
const catalogSkin = catalogSkins.value.find((skin) => skin.id === skinId);
activeSkin.value = await activateSkin(skinId, catalogSkin?.version, appVersion.value);
activeSkinId.value = getStoredSkinId() ?? skinId;
if (skinId === BUILTIN_LIGHT_SKIN) themeMode.value = "light";
else if (skinId === BUILTIN_DARK_SKIN) themeMode.value = "dark";
else themeMode.value = resolveSkinMode(getStoredTheme());
void saveLocalPreferences({ schemaVersion: 1, theme: themeMode.value, skinId: activeSkinId.value });
}
async function initializeSkin(): Promise<void> {
const catalogPromise = listPublicSkins().catch(() => []);
try {
const [preferences, skins, availableSkins] = await Promise.all([loadLocalPreferences(), listInstalledSkins(), catalogPromise]);
installedSkins.value = skins;
catalogSkins.value = availableSkins;
if (!localStorage.getItem("webspeak:theme")) {
if (preferences.theme === "system" || preferences.theme === "light" || preferences.theme === "dark") {
themeMode.value = resolveSkinMode(preferences.theme);
}
saveTheme(themeMode.value);
}
// Only a deliberate choice should override the instance default. The active
// skin and local preference also contain automatically applied defaults.
const savedSkinId = localStorage.getItem("webspeak:skin-choice");
const preferredSkinId = savedSkinId && isPublicSkinEnabled(savedSkinId)
? savedSkinId
: getPublicDefaultSkinId();
const preferredSkin = availableSkins.find((skin) => skin.id === preferredSkinId);
activeSkinId.value = preferredSkinId;
// Apply the locally cached package (or fetch it if absent) before revealing
// the page. The network catalog/version check must not block the first paint.
activeSkin.value = await activateSkin(preferredSkinId, preferredSkin?.version, appVersion.value);
activeSkinId.value = getStoredSkinId() ?? preferredSkinId;
if (activeSkinId.value === BUILTIN_LIGHT_SKIN) themeMode.value = "light";
else if (activeSkinId.value === BUILTIN_DARK_SKIN) themeMode.value = "dark";
else themeMode.value = resolveSkinMode(getStoredTheme());
void saveLocalPreferences({ schemaVersion: 1, theme: themeMode.value, skinId: activeSkinId.value });
} catch {
// Storage or package loading can fail on restricted browsers. Do not leave
// the application hidden, and restore a usable built-in palette instead.
activeSkin.value = null;
activeSkinId.value = themeMode.value === "dark" ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
try {
await activateSkin(activeSkinId.value, undefined, appVersion.value);
} catch {
applyTheme(themeMode.value);
}
} finally {
// The active skin's CSS and asset URLs are installed before this becomes
// visible, so the built-in day/night palette is never shown in between.
skinReady.value = true;
}
void catalogPromise.then(async (availableSkins) => {
catalogSkins.value = availableSkins;
const selectedSkin = availableSkins.find((skin) => skin.id === activeSkinId.value);
const installedSkin = installedSkins.value.find((skin) => skin.id === activeSkinId.value);
if (!selectedSkin || !installedSkin || installedSkin.version === selectedSkin.version) return;
const updatedSkin = await activateSkin(selectedSkin.id, selectedSkin.version, appVersion.value);
if (getStoredSkinId() !== selectedSkin.id) return;
activeSkin.value = updatedSkin;
activeSkinId.value = getStoredSkinId() ?? selectedSkin.id;
installedSkins.value = await listInstalledSkins();
}).catch(() => undefined);
}
const screenShareIndicatorBars = [5, 10, 7, 12, 8, 10];
const {
playerElement: screenSharePlayerEl,
@@ -1032,15 +961,10 @@ function doShare() {
async function clearBrowserData(): Promise<void> {
if (!window.confirm(t("clearLocalDataConfirm"))) return;
resetIdentityOperations();
publicSkin.cancel();
await clearStoredLocalData();
for (const key of ["webspeak:nickname", "webspeak:language", "webspeak:theme", "webspeak:active-skin", "webspeak:skin-choice", "webspeak:input-device", "webspeak:output-device", "webspeak:remember-identity"]) localStorage.removeItem(key);
clearCustomSkinStyle();
activeSkin.value = null;
installedSkins.value = [];
catalogSkins.value = await listPublicSkins();
themeMode.value = resolveSkinMode("system");
applyTheme(themeMode.value);
activeSkinId.value = themeMode.value === "dark" ? BUILTIN_DARK_SKIN : BUILTIN_LIGHT_SKIN;
await publicSkin.reset();
identityMaterial.value = "";
rememberIdentity.value = false;
clearServerHistory();