feat(skins): ship protected built-ins and instance defaults

This commit is contained in:
illusia committed 2026-09-27 00:45:29 +08:00
1 parent 2b7e908d31
commit e09a19b7b4
58 files changed
+2467 -414

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
/** Reduce built-in theme specificity while a community skin is active.
* The community skin is loaded after this stylesheet and should own appearance
* without needing !important or private component selectors.
*/
export function scopeBuiltinThemeForCustomSkin(css: string, theme: "light" | "dark", skinId: string): string {
const sourceRoot = `.ws-skin-root[data-ws-skin="builtin.${theme}"]`;
const customRoot = `:where(.ws-skin-root[data-ws-skin="${skinId}"])`;
return css.replaceAll(sourceRoot, customRoot);
}
+53
View File
@@ -0,0 +1,53 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
BUILTIN_SKIN_CATALOG,
getPublicDefaultSkinId,
isPublicSkinEnabled,
listPublicSkins,
} from "./skin-catalog.js";
test("skin catalog always includes the three protected built-ins and exposes only enabled custom skins", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response(JSON.stringify({
defaultSkinId: "sample-skin",
skins: [
{ id: "sample-skin", name: "Sample", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5-preview", installedAt: 1, enabled: true },
{ id: "disabled-skin", name: "Disabled", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5-preview", installedAt: 2, enabled: false },
{ id: "community.illusia-voice", name: "Spoofed", version: "9.9.9", author: "Other", license: "MIT", minAppVersion: "0.0.1", installedAt: 3 },
],
}), { status: 200, headers: { "content-type": "application/json" } });
try {
const skins = await listPublicSkins();
assert.deepEqual(skins.map((skin) => skin.id), [
"builtin.light",
"builtin.dark",
"community.illusia-voice",
"sample-skin",
]);
assert.deepEqual(BUILTIN_SKIN_CATALOG.map((skin) => skin.id), skins.slice(0, 3).map((skin) => skin.id));
assert.equal(getPublicDefaultSkinId(), "sample-skin");
assert.equal(isPublicSkinEnabled("sample-skin"), true);
assert.equal(isPublicSkinEnabled("disabled-skin"), false);
assert.equal(isPublicSkinEnabled("community.illusia-voice"), true);
} finally {
globalThis.fetch = originalFetch;
}
});
test("invalid or disabled instance defaults safely fall back to the protected day skin", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response(JSON.stringify({
defaultSkinId: "disabled-skin",
skins: [{ id: "disabled-skin", name: "Disabled", version: "1.0.0", author: "Test", license: "MIT", minAppVersion: "0.2.5-preview", installedAt: 2, enabled: false }],
}), { status: 200, headers: { "content-type": "application/json" } });
try {
const skins = await listPublicSkins();
assert.equal(skins.length, 3);
assert.equal(getPublicDefaultSkinId(), "builtin.light");
} finally {
globalThis.fetch = originalFetch;
}
});
+83 -5
View File
@@ -8,18 +8,84 @@ export interface SkinCatalogEntry {
minAppVersion: string;
previewUrl?: string;
installedAt: number;
builtIn?: boolean;
enabled?: boolean;
previewKind?: "day" | "night" | "illusia";
}
export const BUILTIN_ILLUSIA_SKIN_ID = "community.illusia-voice";
export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
{
id: "builtin.light",
name: "Day mode",
version: "1.0.0",
author: "WebSpeak",
license: "AGPL-3.0-only",
description: "The default light appearance.",
minAppVersion: "0.2.5-preview",
installedAt: 0,
builtIn: true,
previewKind: "day",
},
{
id: "builtin.dark",
name: "Night mode",
version: "1.0.0",
author: "WebSpeak",
license: "AGPL-3.0-only",
description: "The default dark appearance.",
minAppVersion: "0.2.5-preview",
installedAt: 0,
builtIn: true,
previewKind: "night",
},
{
id: BUILTIN_ILLUSIA_SKIN_ID,
name: "ILLUSIA风",
version: "1.0.25",
author: "WebSpeak Project",
license: "All rights reserved",
description: "A bright original-character art skin for the home, voice room, and demo pages.",
minAppVersion: "0.2.5-preview",
previewUrl: "/skins/illusia-voice-preview.webp",
installedAt: 0,
builtIn: true,
previewKind: "illusia",
},
];
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";
export function getPublicDefaultSkinId(): string {
return isPublicSkinEnabled(publicDefaultSkinId) ? publicDefaultSkinId : "builtin.light";
}
export function isPublicSkinEnabled(id: string): boolean {
if (BUILTIN_SKIN_CATALOG.some((skin) => skin.id === id)) return true;
return !publicDirectoryLoaded || publicEnabledSkinIds.has(id);
}
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";
try {
const response = await fetch("/api/skins", { headers: { accept: "application/json" }, cache: "no-cache" });
if (!response.ok) return [];
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 [];
return (payload as { skins: unknown[] }).skins.flatMap((value) => {
if (!payload || typeof payload !== "object" || !Array.isArray((payload as { skins?: unknown }).skins)) return BUILTIN_SKIN_CATALOG;
const directorySkins = (payload as { skins: unknown[] }).skins.flatMap((value) => {
if (!value || typeof value !== "object") return [];
const skin = value as Record<string, unknown>;
if (typeof skin.id !== "string" || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(skin.id) || skin.id.startsWith("builtin.")) return [];
if (typeof skin.id !== "string" || !/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(skin.id) || skin.id.startsWith("builtin.") || skin.id === BUILTIN_ILLUSIA_SKIN_ID) return [];
if ([skin.name, skin.version, skin.author, skin.license, skin.minAppVersion].some((field) => typeof field !== "string")) return [];
const previewUrl = typeof skin.previewUrl === "string" && skin.previewUrl === `/api/skins/${skin.id}/preview` ? skin.previewUrl : undefined;
return [{
@@ -32,10 +98,22 @@ export async function listPublicSkins(): Promise<SkinCatalogEntry[]> {
...(typeof skin.description === "string" ? { description: skin.description } : {}),
...(previewUrl ? { previewUrl } : {}),
installedAt: Number.isFinite(skin.installedAt) ? Number(skin.installedAt) : 0,
enabled: skin.enabled !== false,
}];
});
publicDirectoryLoaded = true;
publicEnabledSkinIds = new Set([
...BUILTIN_SKIN_CATALOG.map((skin) => skin.id),
...directorySkins.filter((skin) => skin.enabled).map((skin) => skin.id),
]);
const requestedDefault = (payload as { defaultSkinId?: unknown }).defaultSkinId;
publicDefaultSkinId = typeof requestedDefault === "string" && publicEnabledSkinIds.has(requestedDefault) ? requestedDefault : "builtin.light";
return [...BUILTIN_SKIN_CATALOG, ...directorySkins.filter((skin) => skin.enabled)];
} catch {
return [];
publicDirectoryLoaded = false;
publicEnabledSkinIds = new Set(BUILTIN_SKIN_CATALOG.map((skin) => skin.id));
publicDefaultSkinId = "builtin.light";
return BUILTIN_SKIN_CATALOG;
}
}
+160 -24
View File
@@ -3,6 +3,7 @@ import { readFile } from "node:fs/promises";
import test from "node:test";
import { strToU8, zipSync } from "fflate";
import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js";
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
const manifest = {
schemaVersion: 1,
@@ -19,68 +20,203 @@ test("skin CSS is scoped, local artwork and fonts work, and global names are iso
const skin = await importSkinPack(makeSkin(`
@font-face { font-family: "Wave Font"; src: url("assets/wave.woff2") format("woff2"); }
@keyframes shimmer { from { opacity: .4; } to { opacity: 1; } }
:root { --accent: #00a99d; }
.voice-card { font-family: "Wave Font", sans-serif; animation: shimmer 1s ease-in-out; background-image: image-set("assets/backdrop.png" 1x); }
:root { --skin-accent: #00a99d; }
[data-ws-part="voice.member"] { font-family: "Wave Font", sans-serif; animation: shimmer 1s ease-in-out; background-image: image-set("assets/backdrop.png" 1x); }
`));
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="ocean-night"\] \{ --accent: #00a99d; \}/);
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="ocean-night"\] \{ --skin-accent: #00a99d; \}/);
assert.match(skin.css, /@keyframes ws-ocean-night-shimmer/);
assert.match(skin.css, /animation: ws-ocean-night-shimmer/);
assert.match(skin.css, /font-family: "ws-ocean-night-Wave-Font"/);
assert.match(skin.css, /url\("wskin-asset:assets%2Fwave\.woff2"\)/);
assert.match(skin.css, /image-set\("wskin-asset:assets%2Fbackdrop\.png" 1x\)/);
assert.ok(skin.warnings.some((warning) => warning.includes("localized text wrapping")));
assert.equal(skin.contentData, undefined, "skin content is optional; WebSpeak supplies the base interface translations");
const resolved = resolveSkinCssAssets(skin.css, skin.assets);
assert.match(resolved.css, /blob:/);
resolved.objectUrls.forEach((url) => URL.revokeObjectURL(url));
});
test("skin CSS permits hiding explicitly optional decoration while protecting controls and containers", async () => {
const skin = await importSkinPack(makeSkin('@keyframes fade-wave { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="demo.wave"] { display: none !important; opacity: var(--decorative-opacity); all: unset; animation: fade-wave 1s; }'));
assert.match(skin.css, /display: none !important/);
assert.match(skin.css, /opacity: var\(--decorative-opacity\)/);
assert.match(skin.css, /all: unset/);
test("skin CSS permits visual decoration but prevents layout, text-flow, and control-geometry changes", async () => {
const skin = await importSkinPack(makeSkin('@keyframes fade-wave { from { opacity: 0; } to { opacity: 1; } } [data-ws-part="demo.wave"] { opacity: var(--skin-decoration-opacity); animation: fade-wave 1s; box-shadow: 0 0 14px #4ff; }'));
assert.match(skin.css, /opacity: var\(--skin-decoration-opacity\)/);
assert.match(skin.css, /box-shadow: 0 0 14px #4ff/);
assert.match(skin.css, /from \{ opacity: 0; \}/);
assert.match(skin.css, /animation: ws-ocean-night-fade-wave 1s/);
await assert.rejects(importSkinPack(makeSkin(".required { display: none; }")), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { position: fixed; inset: 0; z-index: 99999; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.member"] { padding: 30px; transform: scale(1.2); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { font-size: 3rem; line-height: 1; white-space: nowrap; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home.hero.title"] { text-transform: uppercase; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { opacity: 0; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.wave"] .child { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: var(--hidden); }')), (error: unknown) => error instanceof Error && error.message.includes("indirect values"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { all: unset; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.wave"] span { display: none; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { display: var(--skin-hidden); }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="voice.screen-player.exit"] { all: unset; }')), (error: unknown) => error instanceof Error && error.message.includes("must not change layout"));
await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="voice.screen-player.exit"] { animation: hide-control 1s infinite; }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin('@keyframes hide-control { to { opacity: 0; } } [data-ws-part="control"] { animation: var(--custom-animation); }')), (error: unknown) => error instanceof Error && error.message.includes("explicitly optional visual parts"));
await assert.rejects(importSkinPack(makeSkin(".art { background-image: image-set(\"https://example.invalid/remote.png\" 1x); }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { --accent: red; }')), (error: unknown) => error instanceof Error && error.message.includes("--skin- prefix"));
await assert.rejects(importSkinPack(makeSkin(".internal-class { color: red; }")), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="demo.voice-card"].private-component { color: red; }')), (error: unknown) => error instanceof Error && error.message.includes("must use :root"));
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: image-set("https://example.invalid/remote.png" 1x); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
});
test("custom skins can override theme appearance without !important or private class selectors", () => {
const css = '.ws-skin-root[data-ws-skin="builtin.dark"] .join-page .join-card { color: white; }';
assert.equal(
scopeBuiltinThemeForCustomSkin(css, "dark", "community.illusia-voice"),
':where(.ws-skin-root[data-ws-skin="community.illusia-voice"]) .join-page .join-card { color: white; }',
);
});
test("community skins use a scoped light fallback instead of inheriting the night skin", async () => {
const lightCss = await readFile(new URL("../skins/builtin/light/skin.css", import.meta.url), "utf8");
const scoped = scopeBuiltinThemeForCustomSkin(lightCss, "light", "community.illusia-voice");
assert.match(scoped, /:where\(\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]\) \{\s*color-scheme: light;/);
assert.match(scoped, /:where\(\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]\) \.settings-content/);
});
test("all public skin parts are documented and the admin console is outside skin scope", async () => {
const [webClient, demo, admin, documentation] = await Promise.all([
const [webClient, demo, skinSwitcher, languageSwitcher, admin, documentation] = await Promise.all([
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
readFile(new URL("../views/DemoView.vue", import.meta.url), "utf8"),
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../views/AdminView.vue", import.meta.url), "utf8"),
readFile(new URL("../../../docs/SKIN_DEVELOPMENT.md", import.meta.url), "utf8"),
]);
const publicParts = new Set([...`${webClient}\n${demo}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
const publicParts = new Set([...`${webClient}\n${demo}\n${skinSwitcher}\n${languageSwitcher}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
for (const part of publicParts) assert.ok(documentation.includes(`\`${part}\``), `Undocumented skin part: ${part}`);
assert.match(skinSwitcher, /data-ws-skin-id/);
assert.match(skinSwitcher, /data-ws-state/);
assert.match(languageSwitcher, /data-ws-language/);
assert.doesNotMatch(admin, /ws-skin-root|data-ws-page=/);
assert.doesNotMatch(demo, /:global\(:root\[data-theme="dark"\]\)/);
assert.match(demo, /\.demo-page\[data-ws-skin="builtin\.dark"\]/);
});
test("public skin and language selectors keep readable light surfaces in dark mode", async () => {
const [skinSwitcher, languageSwitcher, darkSkin] = await Promise.all([
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../skins/builtin/dark/skin.css", import.meta.url), "utf8"),
]);
assert.match(skinSwitcher, /\.skin-trigger\s*\{[^}]*background:\s*rgba\(250,\s*254,\s*255/i);
assert.match(skinSwitcher, /\.skin-dropdown\s*\{[^}]*background:\s*linear-gradient/i);
assert.match(skinSwitcher, /\.skin-option\s*\{[^}]*color:\s*#123849/i);
assert.match(languageSwitcher, /\.language-dropdown\s*\{[^}]*background:\s*#fff/i);
assert.doesNotMatch(darkSkin, /\.language-switcher\s+\.language-(?:trigger|dropdown|option)/);
});
test("skin content supports localized interface message overrides and includes the preview as an asset", async () => {
const content = { defaultLocale: "en", locales: { en: { home: { title: "Welcome" }, messages: { speakingNow: "Live now" } } } };
const skin = await importSkinPack(makeSkin(".voice-card { background: url(assets/preview.png); }", content));
const skin = await importSkinPack(makeSkin('[data-ws-part="demo.voice-card"] { background: url(assets/preview.png); }', content));
assert.equal(skin.contentData?.locales.en?.messages?.speakingNow, "Live now");
assert.equal(skin.previewBlob?.type, "image/png");
assert.ok(skin.assets["assets/preview.png"]);
});
test("the documented Aurora Voice example package imports with its artwork and localized copy", async () => {
const bytes = await readFile(new URL("../../../docs/examples/aurora-voice.wskin", import.meta.url));
const skin = await importSkinPack(new File([bytes], "aurora-voice.wskin", { type: "application/octet-stream" }));
assert.equal(skin.id, "community.aurora-voice");
assert.equal(skin.contentData?.locales["zh-CN"]?.home?.title, "自在");
assert.equal(skin.contentData?.locales.en?.messages?.["demo.heroLead"], "This demo is styled by the same package as the connection and voice pages.");
assert.equal(skin.previewBlob?.type, "image/jpeg");
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="community\.aurora-voice"\]/);
test("the ILLUSIA visual-only example imports without replacing WebSpeak's base translations", async () => {
const bytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
const skin = await importSkinPack(new File([bytes], "illusia-voice.wskin", { type: "application/octet-stream" }));
assert.equal(skin.id, "community.illusia-voice");
assert.equal(skin.name, "ILLUSIA风");
assert.equal(skin.version, "1.0.25");
assert.equal(skin.contentData, undefined);
assert.equal(skin.previewBlob?.type, "image/webp");
assert.ok(skin.assets["assets/background-composite.webp"]);
assert.ok(skin.assets["assets/bg-room-main.webp"]);
assert.ok(skin.assets["assets/banner-character-main.webp"]);
assert.ok(skin.assets["assets/foreground-headphone.webp"]);
assert.ok(skin.assets["assets/chat-empty-chibi.webp"]);
assert.ok(skin.assets["assets/visitor-avatar.webp"]);
assert.ok(skin.assets["assets/button-mascot.webp"]);
assert.ok(skin.assets["assets/footer-wave.png"]);
assert.match(skin.css, /\.ws-skin-root\[data-ws-skin="community\.illusia-voice"\]/);
assert.match(skin.css, /home\.visitors.*?nth-child\(2\)/s);
assert.match(skin.css, /skin\.menu/);
assert.match(skin.css, /skin\.menu[^{}]*\[role="listbox"\]/);
assert.match(skin.css, /skin\.option/);
assert.match(skin.css, /language\.trigger/);
assert.match(skin.css, /language\.menu[^{}]*\[role="listbox"\]/);
assert.match(skin.css, /language\.option/);
assert.match(skin.css, /data-ws-skin-id="community\.illusia-voice"/);
assert.match(skin.css, /data-ws-part="home\.join-card\.waveform"/);
assert.match(skin.css, /data-ws-part="home\.join-card\.sonar"/);
assert.match(skin.css, /data-ws-part="home\.join-card"\]\s*\{[^}]*background-image:\s*url\("wskin-asset:assets%2Fbanner-mascot-blob\.webp"\)/s);
assert.doesNotMatch(skin.css, /data-ws-part="home\.join-card"\]\s*\{[^}]*radial-gradient/s);
assert.match(skin.css, /data-ws-part="voice\.member-panel"\]\s*\{[^}]*background-position:\s*0 0, right top, right top, center/s);
assert.match(skin.css, /data-ws-part="voice\.member-panel"\]\s*::before\s*\{[^}]*background-image:\s*url\("wskin-asset:assets%2Fforeground-headphone\.webp"\)[^}]*filter:\s*drop-shadow/s);
assert.doesNotMatch(skin.css, /illusia-card-signal|illusia-card-glow/);
assert.match(skin.css, /illusia-home-aura/);
assert.match(skin.css, /voice\.activity[\s\S]*?wskin-asset:assets%2Fbanner-character-main\.webp/);
assert.match(skin.css, /voice\.activity\.artwork[\s\S]*?wskin-asset:assets%2Fbanner-character-main\.webp/);
assert.match(skin.css, /data-ws-part="voice\.activity"\]\s*\{[^}]*border-color:\s*rgba\(113, 211, 222, \.62\);[^}]*border-radius:\s*24px;[^}]*background-image:[\s\S]*?bg-room-main\.webp[^}]*backdrop-filter:\s*blur\(10px\)/);
assert.match(skin.css, /voice\.activity\.artwork[^{}]*\{[^}]*background-position:\s*right 34% center;[^}]*background-size:\s*auto 320px;[^}]*filter:\s*drop-shadow\(0 18px 22px/);
assert.doesNotMatch(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"\]\s*> :first-child/);
assert.match(skin.css, /data-ws-part="voice\.channel-group"\]\s*\{[^}]*border-color:\s*rgba\(8, 126, 134, \.32\)/);
assert.match(skin.css, /data-ws-part="voice\.channel-group"\]\[data-ws-state="current"\]\s*\{[^}]*border-color:\s*rgba\(8, 126, 134, \.48\)/);
assert.match(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[\s\S]*?wskin-asset:assets%2Fchat-empty-chibi\.webp/);
assert.match(skin.css, /voice\.chat\.empty[^{}]*\{[^}]*background-size:\s*22px 22px, 300px 250px, cover, min\(340px, 46vw\) auto/s);
assert.match(skin.css, /voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[^{}]*\{[^}]*background-position:\s*0 0, right center, center, center 8px;[^}]*background-size:\s*22px 22px, 300px 250px, cover, min\(340px, 46vw\) auto/s);
assert.match(skin.css, /data-ws-state="messages-empty"\]::before\s*\{[^}]*color:\s*rgba\(71, 126, 148, \.9\);[^}]*radial-gradient\(circle, #527f91 0 1\.6px/s);
assert.match(skin.css, /data-ws-state="messages-empty"\]::after\s*\{[^}]*color:\s*rgba\(71, 126, 148, \.9\)/s);
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*\{[^}]*background-position:\s*0 0, right 8px center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s);
assert.match(skin.css, /@media \(max-width: 1100px\)[\s\S]*?voice\.chat\.empty[^{}]*data-ws-state="messages-empty"[^{}]*\{[^}]*background-position:\s*0 0, right center, center, center 8px;[^}]*background-size:\s*22px 22px, 260px 220px, cover, min\(300px, 66vw\) auto/s);
assert.doesNotMatch(skin.css, /data-ws-state="messages-empty"[^{}]*\{[^}]*color: transparent/s);
assert.doesNotMatch(skin.css, /(?:^|[;{\s])(?:position|inset|top|right|bottom|left|width|height|min-height|padding|z-index|transform)\s*:/);
assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{[^}]*animation:/);
assert.doesNotMatch(skin.css, /\[data-ws-part="home\.join-card"\]\s*\{\s*animation: none;/);
assert.match(skin.css, /home\.footer[\s\S]*?footer-wave\.png/);
assert.match(skin.css, /\[data-ws-part="home"\] \[data-ws-part="home\.connect"\]/);
assert.doesNotMatch(skin.css, /\[data-ws-page="home"\] \[data-ws-part="home\.connect"\]/);
assert.match(skin.css, /home\.connect[\s\S]*?wskin-asset:assets%2Fbutton-mascot\.webp/);
assert.match(skin.css, /data-ws-page="demo"[^{}]*\{[^}]*wskin-asset:assets%2Fforeground-headphone\.webp[^}]*background-position:\s*left bottom, center, center;[^}]*background-size:\s*min\(34vw, 430px\) auto, auto, cover/s);
assert.match(skin.css, /voice\.screen-player[\s\S]*?background: linear-gradient\(135deg, rgba\(250, 255, 255, \.96\), rgba\(220, 245, 250, \.94\)\)/);
assert.doesNotMatch(skin.css, /voice\.screen-player[^{}]*\{[^}]*background: rgba\(10, 34, 45, \.96\)/);
});
test("the activity artwork layer floats above room content without intercepting controls", async () => {
const css = await readFile(new URL("../styles/web-client.css", import.meta.url), "utf8");
assert.match(css, /\.app-shell \.workspace-content\s*\{\s*position: relative;\s*isolation: isolate;/);
assert.match(css, /\.voice-activity-artwork\s*\{\s*position: absolute;\s*z-index: 2;\s*inset: -26px 0 -48px;[^}]*pointer-events: none;/);
assert.match(css, /\.voice-activity-artwork\s*\{[^}]*transform: perspective\(1100px\) rotateY\(-2\.5deg\) translateZ\(22px\)/);
assert.match(css, /\.app-shell \.member-panel::before\s*\{\s*content: "";\s*position: absolute;\s*z-index: 1;\s*left: -28px;\s*bottom: 18px;\s*width: min\(430px, calc\(100vw - 24px\)\);\s*aspect-ratio: 3 \/ 2;[^}]*perspective\(1100px\) rotateY\(-8deg\)/);
assert.match(css, /\.app-shell \.chat-empty\[data-ws-state="messages-empty"\]\s*\{[^}]*min-height: 210px;\s*padding: 126px 12px 10px;/);
assert.match(css, /\.app-shell \.chat-panel \.section-heading,[\s\S]*?\.app-shell \.chat-panel \.message-composer\s*\{\s*position: relative;\s*z-index: 3;/);
assert.match(css, /\.screen-share-player\s*\{[^}]*background: var\(--surface-1\)/);
assert.match(css, /\.screen-share-player-exit\s*\{[^}]*z-index: 3;/);
assert.match(css, /\.screen-share-player-stage\s*\{[^}]*var\(--accent\)[^}]*var\(--surface-2\)/);
assert.match(css, /\.screen-share-player-video\s*\{[^}]*background: var\(--surface-2\)/);
assert.match(css, /@media \(min-width: 741px\)\s*\{\s*\/\* Keep header menus above the independently stacked screen-share stage\. \*\/\s*\.app-shell \.workspace-header\s*\{\s*position: relative;\s*z-index: 40;/);
});
test("channel empty state removes its bubble ornament and keeps the text-channel label", async () => {
const [view, chat] = await Promise.all([
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
readFile(new URL("../composables/useWebClientChat.ts", import.meta.url), "utf8"),
]);
assert.doesNotMatch(view, /data-ws-state="messages-empty"><div class="chat-empty-icon"/);
assert.match(view, /class="section-kicker">\{\{ chatTabLabel \}\}/);
assert.match(chat, /tab\.value === "channel" \? t\("textChannel"\)/);
});
test("homepage motion and room content spacing preserve the ILLUSIA layout", async () => {
const css = await readFile(new URL("../styles/web-client.css", import.meta.url), "utf8");
assert.ok(css.includes('.join-page *:not([data-ws-part="home.join-card"])'));
assert.ok(css.includes("animation: none !important"));
assert.doesNotMatch(css, /\.join-page \*, \.join-page \*::before, \.join-page \*::after\s*\{\s*animation: none !important/);
assert.ok(css.includes("padding: 0 clamp(12px, 1.4vw, 22px);"), "homepage header contents keep an inset from their container edge");
assert.ok(css.includes(".chat-panel { margin-top: 34px; padding: 0 clamp(14px, 1.8vw, 24px) 20px;"), "chat children keep horizontal and bottom breathing room");
assert.match(css, /\.app-shell \.voice-section \{\s*position: relative;\s*padding: clamp\(14px, 1\.8vw, 24px\);/);
assert.match(css, /@media \(max-width: 740px\) \{\s*\.app-shell \.voice-section \{\s*padding: 14px 10px 16px;/);
assert.match(css, /\.promise-list \{\s*display: grid;\s*width: 100%;\s*grid-template-columns: repeat\(3, minmax\(0, 1fr\)\);/);
assert.match(css, /\.promise-item \{\s*min-width: 0;\s*min-height: 58px;[\s\S]*?padding: 9px 11px;/);
assert.match(css, /@media \(max-width: 420px\) \{\s*\.promise-list \{\s*grid-template-columns: minmax\(0, 1fr\);/);
assert.match(css, /\.join-card-waveform i \{[^}]*animation: screen-share-wave 1\.1s ease-in-out infinite alternate;/);
assert.match(css, /@keyframes join-card-sonar-ring[\s\S]*?transform: scale\(\.6\); opacity: \.62;[\s\S]*?transform: scale\(1\); opacity: 0;/);
});
function makeSkin(css: string, content?: unknown): File {
+53
View File
@@ -11,12 +11,30 @@ const MAX_CONTENT_BYTES = 256 * 1024;
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
const MAX_FONT_BYTES = 4 * 1024 * 1024;
const ALLOWED_AT_RULES = new Set(["media", "supports", "container", "layer", "font-face", "keyframes", "-webkit-keyframes"]);
const LAYOUT_AFFECTING_PROPERTIES = new Set([
"all", "display", "position", "top", "right", "bottom", "left", "inset", "inset-block", "inset-inline",
"width", "height", "min-width", "min-height", "max-width", "max-height", "inline-size", "block-size",
"min-inline-size", "min-block-size", "max-inline-size", "max-block-size", "aspect-ratio", "box-sizing",
"gap", "row-gap", "column-gap", "grid", "flex", "order", "float", "clear", "overflow", "overflow-x",
"overflow-y", "overflow-block", "overflow-inline", "overscroll-behavior", "z-index", "visibility",
"pointer-events", "clip", "clip-path", "mask", "mask-image", "transform", "transform-origin", "transform-style", "translate", "scale", "rotate",
"perspective", "perspective-origin", "contain", "content-visibility", "container", "container-name",
"container-type", "contain-intrinsic-size", "resize", "columns", "column-count", "column-width", "scrollbar-width", "font",
"font-size", "line-height", "letter-spacing", "word-spacing", "white-space", "word-break", "overflow-wrap", "word-wrap",
"text-wrap", "text-overflow", "text-indent", "text-transform", "text-combine-upright", "text-autospace", "text-spacing-trim",
"line-clamp", "tab-size", "hyphens", "line-break", "text-size-adjust", "initial-letter", "shape-outside", "baseline-shift",
"box-orient", "box-direction", "box-lines", "ruby-position", "caption-side", "table-layout", "border-collapse", "border-spacing",
"writing-mode", "direction", "unicode-bidi", "vertical-align", "appearance", "zoom", "scrollbar-gutter", "touch-action", "user-select", "cursor", "content",
"position-anchor", "position-area", "position-try-fallbacks", "position-try-order", "anchor-name", "anchor-scope",
]);
const OPTIONAL_VISUAL_PARTS = new Set([
"home.hero.eyebrow",
"home.gateway-status",
"home.features",
"home.feature",
"home.visitors",
"home.join-card.waveform",
"home.join-card.sonar",
"voice.activity-heading",
"voice.member.avatar",
"voice.member.live-indicator",
@@ -440,6 +458,7 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
if (rule.parent?.type === "rule") throw rule.error("Nested style rules are not supported; use flat selectors.");
if (!selectorUsesPublicHook(rule.selector)) throw rule.error("Skin selectors must use :root, [data-ws-page], or [data-ws-part] so they stay attached to WebSpeak's stable visual interface.");
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
try {
rule.selector = selectorParser((selectors) => {
@@ -493,6 +512,13 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)) {
throw declaration.error("Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
}
if (isLayoutAffectingProperty(property)) {
throw declaration.error("Skin CSS may change component artwork and appearance, but must not change layout, positioning, sizing, text flow, or interaction geometry.");
}
if (property === "font-family") warnings.add("Custom fonts can change localized text wrapping; verify every WebSpeak language before publishing.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(value)) {
throw declaration.error("Executable CSS values are not allowed.");
}
@@ -543,6 +569,33 @@ function targetsOnlyOptionalVisualParts(selector: string): boolean {
}
}
function selectorUsesPublicHook(selector: string): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
let scoped = false;
let usesPrivateName = false;
item.walk((node) => {
if (node.type === "attribute" && ["data-ws-part", "data-ws-page"].includes(node.attribute.toLowerCase())) scoped = true;
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true;
if (node.type === "class" || node.type === "id") usesPrivateName = true;
});
return scoped && !usesPrivateName;
});
} catch {
return false;
}
}
function isLayoutAffectingProperty(property: string): boolean {
const unprefixed = property.replace(/^-(?:webkit|moz|ms|o)-/, "");
if (LAYOUT_AFFECTING_PROPERTIES.has(unprefixed)) return true;
if (/^(?:margin|padding)(?:-|$)/.test(unprefixed)) return true;
if (/^border(?:-|$)/.test(unprefixed) && !/^border-(?:color(?:-|$)|radius(?:-|$))/.test(unprefixed)) return true;
if (/^(?:grid|flex|align-(?:content|items|self)|justify-(?:content|items|self)|place-(?:content|items|self)|offset|transform|overscroll|overflow|column)(?:-|$)/.test(unprefixed)) return true;
return /^font-(?!family$|weight$|style$|synthesis$|palette$)/.test(unprefixed);
}
function findOwningRule(node: Node): Rule | null {
let parent = node.parent;
while (parent && parent.type !== "root") {
+24 -10
View File
@@ -1,12 +1,14 @@
import { getInstalledSkin, saveInstalledSkin } from "./local-persistence.js";
import type { InstalledSkin } from "./skin-pack.js";
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme, type ThemeMode } from "./theme.js";
import { applyTheme, getBuiltinSkinCss, getStoredTheme, isDarkTheme } from "./theme.js";
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js";
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
export const BUILTIN_LIGHT_SKIN = "builtin.light";
export const BUILTIN_DARK_SKIN = "builtin.dark";
const CUSTOM_STYLE_ID = "webspeak-active-custom-skin";
const BUILTIN_STYLE_ID = "webspeak-active-built-in-skin";
const CUSTOM_BASE_STYLE_ID = "webspeak-active-custom-skin-base";
let activeAssetUrls: string[] = [];
let criticalControlObserver: MutationObserver | null = null;
@@ -27,7 +29,7 @@ export async function activateStoredSkin(): Promise<InstalledSkin | null> {
return activateSkin(selectedId);
}
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.4"): Promise<InstalledSkin | null> {
export async function activateSkin(id: string, expectedVersion?: string, appVersion = "0.2.5-preview"): Promise<InstalledSkin | null> {
if (id === BUILTIN_LIGHT_SKIN || id === BUILTIN_DARK_SKIN) {
clearCustomSkinStyle();
applyTheme(id === BUILTIN_DARK_SKIN ? "dark" : "light");
@@ -35,11 +37,16 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
storeSkinId(id);
return null;
}
if (!isPublicSkinEnabled(id)) {
if (typeof localStorage !== "undefined") localStorage.removeItem("webspeak:skin-choice");
return fallBackToBuiltin();
}
let skin = await getInstalledSkin(id);
if (!skin || (expectedVersion && skin.version !== expectedVersion)) {
try {
const response = await fetch(`/api/skins/${encodeURIComponent(id)}/package`, { cache: "no-cache" });
const packageUrl = getBundledSkinPackageUrl(id) ?? `/api/skins/${encodeURIComponent(id)}/package`;
const response = await fetch(packageUrl, { cache: "no-cache" });
if (!response.ok) throw new Error("Skin package is no longer available.");
const archive = await response.blob();
const file = new File([archive], `${id}.wskin`, { type: "application/octet-stream" });
@@ -59,13 +66,19 @@ export async function activateSkin(id: string, expectedVersion?: string, appVers
try {
const { resolveSkinCssAssets } = await import("./skin-pack.js");
const compiled = resolveSkinCssAssets(skin.css, skin.assets);
const baseTheme: Exclude<ThemeMode, "system"> = isDarkTheme(getStoredTheme()) ? "dark" : "light";
applyTheme(baseTheme);
const root = document.getElementById(BUILTIN_STYLE_ID) as HTMLStyleElement | null;
if (root) {
root.dataset.skinPackage = skin.id;
root.textContent = getBuiltinSkinCss(baseTheme).replaceAll(`data-ws-skin="builtin.${baseTheme}"`, `data-ws-skin="${skin.id}"`);
// 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,
// neutral fallback. A custom skin can opt into dark colors itself.
applyTheme(getStoredTheme());
let baseStyle = document.getElementById(CUSTOM_BASE_STYLE_ID) as HTMLStyleElement | null;
if (!baseStyle) {
baseStyle = document.createElement("style");
baseStyle.id = CUSTOM_BASE_STYLE_ID;
document.head.append(baseStyle);
}
baseStyle.dataset.skinPackage = skin.id;
baseStyle.textContent = scopeBuiltinThemeForCustomSkin(getBuiltinSkinCss("light"), "light", skin.id);
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
clientRoot.dataset.wsSkin = skin!.id;
});
@@ -99,6 +112,7 @@ function fallBackToBuiltin(): null {
export function clearCustomSkinStyle(): void {
document.getElementById(CUSTOM_STYLE_ID)?.remove();
document.getElementById(CUSTOM_BASE_STYLE_ID)?.remove();
activeAssetUrls.forEach((url) => URL.revokeObjectURL(url));
activeAssetUrls = [];
}
+5 -2
View File
@@ -23,7 +23,7 @@ export function getStoredTheme(): ThemeMode {
return value === "light" || value === "dark" || value === "system" ? value : "system";
}
export function applyTheme(theme: ThemeMode): void {
export function applyTheme(theme: ThemeMode, options: { preserveCustomSkins?: boolean } = {}): void {
if (typeof document === "undefined") return;
activeThemeMode = theme;
const root = document.documentElement;
@@ -33,6 +33,9 @@ export function applyTheme(theme: ThemeMode): void {
// Built-in skin CSS is scoped to public roots and can never restyle /admin.
root.dataset.theme = theme;
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
const currentSkin = clientRoot.dataset.wsSkin;
const isCustomSkin = currentSkin !== builtinSkins.light.manifest.id && currentSkin !== builtinSkins.dark.manifest.id;
if (options.preserveCustomSkins && currentSkin && isCustomSkin) return;
clientRoot.dataset.wsSkin = activeSkin.manifest.id;
});
@@ -69,7 +72,7 @@ applyTheme(getStoredTheme());
if (typeof window !== "undefined" && typeof window.matchMedia === "function") {
const systemColorScheme = window.matchMedia("(prefers-color-scheme: dark)");
const updateSystemSkin = () => {
if (activeThemeMode === "system") applyTheme("system");
if (activeThemeMode === "system") applyTheme("system", { preserveCustomSkins: true });
};
if (systemColorScheme.addEventListener) systemColorScheme.addEventListener("change", updateSystemSkin);
else systemColorScheme.addListener?.(updateSystemSkin);