mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat(skin): add v3 declarative plugin components
This commit is contained in:
1 parent
02441410a0
commit
eabc78f36a
30 files changed
+2483
-308
No files matched your search
@@ -0,0 +1,236 @@
|
||||
import { computed, defineComponent, Fragment, h, onUnmounted, reactive, ref, Teleport, watch, type PropType, type VNodeChild } from "vue";
|
||||
import {
|
||||
SKIN_PLUGIN_PERMISSIONS,
|
||||
parseSkinPluginDocument,
|
||||
type SkinPluginActionDefinition,
|
||||
type SkinPluginComponent,
|
||||
type SkinPluginDocument,
|
||||
type SkinPluginNode,
|
||||
} from "../../../src/shared/skin-plugin.js";
|
||||
import { approveSkinPluginComponents, getMissingSkinPluginApprovals, isSkinPluginComponentApproved, revokeSkinPluginApprovals } from "../services/skin-plugin-approval.js";
|
||||
|
||||
type Scalar = string | number | boolean;
|
||||
type SafeContext = Record<string, unknown>;
|
||||
type HostAction = (args: Record<string, Scalar>, component: SkinPluginComponent) => void | Promise<void>;
|
||||
|
||||
const eventProps: Record<string, string> = {
|
||||
click: "onClick", dblclick: "onDblclick", change: "onChange", input: "onInput", submit: "onSubmit", keydown: "onKeydown",
|
||||
};
|
||||
|
||||
export default defineComponent({
|
||||
name: "SkinPluginOutlet",
|
||||
props: {
|
||||
skinId: { type: String, required: true },
|
||||
skinVersion: { type: String, required: true },
|
||||
document: { type: Object as PropType<SkinPluginDocument>, required: true },
|
||||
page: { type: String as PropType<"home" | "voice" | "demo">, required: true },
|
||||
data: { type: Object as PropType<SafeContext>, required: true },
|
||||
assets: { type: Object as PropType<Record<string, Blob>>, required: true },
|
||||
actions: { type: Object as PropType<Record<string, HostAction>>, required: true },
|
||||
},
|
||||
setup(props) {
|
||||
const denied = ref(false);
|
||||
const manageOpen = ref(false);
|
||||
const refresh = ref(0);
|
||||
const stateByComponent = reactive<Record<string, Record<string, Scalar>>>({});
|
||||
const objectUrls = new Map<string, string>();
|
||||
const validatedDocument = computed(() => {
|
||||
try { return parseSkinPluginDocument(props.document); }
|
||||
catch { return { schemaVersion: 1 as const, components: [] }; }
|
||||
});
|
||||
const matchingComponents = computed(() => validatedDocument.value.components.filter((component) => component.page === props.page));
|
||||
const pendingApproval = computed(() => {
|
||||
refresh.value;
|
||||
return denied.value ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
|
||||
});
|
||||
const accessComponents = computed(() => pendingApproval.value.length
|
||||
? pendingApproval.value
|
||||
: matchingComponents.value.filter((component) => component.permissions.length > 0));
|
||||
const activeComponents = computed(() => {
|
||||
refresh.value;
|
||||
return matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component));
|
||||
});
|
||||
|
||||
watch(() => [props.skinId, props.skinVersion, props.document, props.page], () => { denied.value = false; refresh.value += 1; }, { immediate: true });
|
||||
|
||||
function localState(component: SkinPluginComponent): Record<string, Scalar> {
|
||||
const key = `${props.skinId}/${component.id}`;
|
||||
if (!stateByComponent[key]) stateByComponent[key] = { ...(component.state ?? {}) };
|
||||
return stateByComponent[key];
|
||||
}
|
||||
|
||||
function permissionLabel(permission: string): string {
|
||||
return SKIN_PLUGIN_PERMISSIONS[permission as keyof typeof SKIN_PLUGIN_PERMISSIONS]?.description ?? permission;
|
||||
}
|
||||
|
||||
function resolvePath(path: string, context: SafeContext, state: Record<string, Scalar>): unknown {
|
||||
const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, "");
|
||||
const parts = normalized.split(".");
|
||||
let value: unknown = parts[0] === "state" ? state : context;
|
||||
const start = parts[0] === "state" ? 1 : 0;
|
||||
for (let index = start; index < parts.length; index += 1) {
|
||||
if (!value || typeof value !== "object" || !Object.prototype.hasOwnProperty.call(value, parts[index])) return undefined;
|
||||
value = (value as Record<string, unknown>)[parts[index]];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function interpolate(value: string, context: SafeContext, state: Record<string, Scalar>): string {
|
||||
return value.replace(/\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g, (_match, path: string) => {
|
||||
const resolved = resolvePath(path, context, state);
|
||||
return typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" ? String(resolved) : "";
|
||||
});
|
||||
}
|
||||
|
||||
function resolveActionArgs(definition: SkinPluginActionDefinition, context: SafeContext, state: Record<string, Scalar>): Record<string, Scalar> {
|
||||
const args: Record<string, Scalar> = {};
|
||||
for (const [key, value] of Object.entries(definition.args)) {
|
||||
if (typeof value !== "string") { args[key] = value; continue; }
|
||||
const exact = /^\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}$/.exec(value);
|
||||
const resolved = exact ? resolvePath(exact[1], context, state) : interpolate(value, context, state);
|
||||
if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean") args[key] = resolved;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function dispatch(component: SkinPluginComponent, actionId: string, context: SafeContext, state: Record<string, Scalar>): void {
|
||||
const definition = component.actions[actionId];
|
||||
if (!definition || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
|
||||
const args = resolveActionArgs(definition, context, state);
|
||||
if (definition.type === "ui.setState") {
|
||||
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && "value" in args) state[args.key] = args.value;
|
||||
return;
|
||||
}
|
||||
const handler = props.actions[definition.type];
|
||||
if (handler) void Promise.resolve(handler(args, component)).catch(() => undefined);
|
||||
}
|
||||
|
||||
function assetUrl(path: string): string | undefined {
|
||||
const current = props.assets[path];
|
||||
if (!(current instanceof Blob)) return undefined;
|
||||
let url = objectUrls.get(path);
|
||||
if (!url) { url = URL.createObjectURL(current); objectUrls.set(path, url); }
|
||||
return url;
|
||||
}
|
||||
|
||||
function renderNode(component: SkinPluginComponent, node: SkinPluginNode, context: SafeContext, state: Record<string, Scalar>, skipRepeat = false): VNodeChild {
|
||||
if (!node.tag) return interpolate(node.text ?? "", context, state);
|
||||
if (!skipRepeat && node.repeat) {
|
||||
const values = resolvePath(node.repeat.path, context, state);
|
||||
if (!Array.isArray(values)) return null;
|
||||
return h(Fragment, null, values.slice(0, 100).map((value) => renderNode(component, node, { ...context, [node.repeat!.as]: value }, state, true)));
|
||||
}
|
||||
if (node.when) {
|
||||
const value = resolvePath(node.when.path, context, state);
|
||||
if (node.when.equals !== undefined ? value !== node.when.equals : !value) return null;
|
||||
}
|
||||
const attrs: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(node.attributes ?? {})) {
|
||||
attrs[key === "viewbox" ? "viewBox" : key] = typeof value === "string" ? interpolate(value, context, state) : value;
|
||||
}
|
||||
if (node.asset) {
|
||||
const url = assetUrl(node.asset);
|
||||
if (url) attrs.src = url;
|
||||
}
|
||||
if (node.className || attrs.class) {
|
||||
attrs.class = ["ws-plugin-node", node.className, attrs.class].filter(Boolean).join(" ");
|
||||
} else attrs.class = "ws-plugin-node";
|
||||
attrs["data-ws-plugin-part"] = node.part ? `${component.id}.${node.part}` : component.id;
|
||||
if (node.bindValue) attrs.value = state[node.bindValue];
|
||||
|
||||
for (const [eventName, actionId] of Object.entries(node.events ?? {})) {
|
||||
const propName = eventProps[eventName];
|
||||
if (!propName) continue;
|
||||
attrs[propName] = (event: Event) => {
|
||||
if (!event.isTrusted) return;
|
||||
if (eventName === "keydown" && event instanceof KeyboardEvent && event.key !== "Enter" && event.key !== " ") return;
|
||||
if (node.bindValue && eventName === "input" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)) {
|
||||
state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value;
|
||||
} else if (node.bindValue && eventName === "change" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLSelectElement || event.target instanceof HTMLTextAreaElement)) {
|
||||
state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value;
|
||||
}
|
||||
if (eventName === "submit") event.preventDefault();
|
||||
dispatch(component, actionId, context, state);
|
||||
};
|
||||
}
|
||||
if (node.bindValue && !node.events?.input && !node.events?.change) {
|
||||
attrs[node.tag === "input" ? "onInput" : "onChange"] = (event: Event) => {
|
||||
if (!event.isTrusted) return;
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLInputElement) state[node.bindValue!] = target.type === "checkbox" ? target.checked : target.value;
|
||||
else if (target instanceof HTMLTextAreaElement) state[node.bindValue!] = target.value;
|
||||
else if (target instanceof HTMLSelectElement) state[node.bindValue!] = target.value;
|
||||
};
|
||||
}
|
||||
if (node.tag === "form" && !node.events?.submit) attrs.onSubmit = (event: Event) => event.preventDefault();
|
||||
const children = (node.children ?? []).map((child) => renderNode(component, child, context, state));
|
||||
return h(node.tag, attrs, children);
|
||||
}
|
||||
|
||||
function accept(): void {
|
||||
approveSkinPluginComponents(props.skinId, props.skinVersion, pendingApproval.value);
|
||||
denied.value = false;
|
||||
manageOpen.value = false;
|
||||
refresh.value += 1;
|
||||
}
|
||||
|
||||
function openAccessManager(): void {
|
||||
denied.value = false;
|
||||
manageOpen.value = true;
|
||||
}
|
||||
|
||||
function closeOrDisable(): void {
|
||||
if (pendingApproval.value.length) denied.value = true;
|
||||
manageOpen.value = false;
|
||||
}
|
||||
|
||||
function revokeAll(): void {
|
||||
revokeSkinPluginApprovals(props.skinId);
|
||||
denied.value = true;
|
||||
manageOpen.value = false;
|
||||
refresh.value += 1;
|
||||
}
|
||||
|
||||
onUnmounted(() => { objectUrls.forEach((url) => URL.revokeObjectURL(url)); objectUrls.clear(); });
|
||||
|
||||
return () => {
|
||||
const nodes: VNodeChild[] = activeComponents.value.map((component) => h("div", {
|
||||
key: `${props.skinId}:${component.id}`,
|
||||
class: "ws-plugin-component",
|
||||
"data-ws-plugin-component": component.id,
|
||||
"data-ws-plugin-name": component.name,
|
||||
"data-ws-plugin-part": component.id,
|
||||
"aria-label": component.accessibleName,
|
||||
}, [renderNode(component, component.root, props.data, localState(component))]));
|
||||
const hasPermissions = matchingComponents.value.some((component) => component.permissions.length > 0);
|
||||
const showConsent = pendingApproval.value.length > 0 || manageOpen.value;
|
||||
const accessToggle = hasPermissions ? h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-access-toggle",
|
||||
"aria-label": "管理皮肤组件权限 / Manage skin component access",
|
||||
onClick: openAccessManager,
|
||||
}, "权限 / Access")]) : null;
|
||||
if (!showConsent) return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : [])]);
|
||||
|
||||
const requested = accessComponents.value;
|
||||
const hasMissing = pendingApproval.value.length > 0;
|
||||
const consent = h(Teleport, { to: "body" }, [h("div", { class: "ws-plugin-consent-backdrop", "data-ws-plugin-consent": "true" }, [
|
||||
h("section", { class: "ws-plugin-consent", role: "dialog", "aria-modal": "true", "aria-labelledby": "ws-plugin-consent-title" }, [
|
||||
h("h2", { id: "ws-plugin-consent-title" }, "皮肤组件权限 / Skin component access"),
|
||||
h("p", null, "此皮肤包含会读取公开语音界面数据或请求宿主动作的组件。只有你批准的组件才会启用。/ This skin requests limited access for its components. Only approved components will run."),
|
||||
...requested.map((component) => h("div", { class: "ws-plugin-consent-item", key: component.id }, [
|
||||
h("strong", null, component.name),
|
||||
h("ul", null, component.permissions.map((permission) => h("li", { key: permission }, permissionLabel(permission)))),
|
||||
])),
|
||||
h("p", { class: "ws-plugin-consent-note" }, "组件不能运行脚本、访问浏览器存储、读取连接地址/密码或控制麦克风。/ Components cannot run code, access storage or credentials, or control the microphone."),
|
||||
h("div", { class: "ws-plugin-consent-actions" }, [
|
||||
...(hasMissing ? [h("button", { type: "button", class: "secondary", onClick: closeOrDisable }, "暂不启用 / Keep disabled")]
|
||||
: [h("button", { type: "button", class: "secondary", onClick: revokeAll }, "撤销全部授权 / Revoke all access")]),
|
||||
h("button", { type: "button", class: "primary", onClick: hasMissing ? accept : () => { manageOpen.value = false; } }, hasMissing ? "批准所列权限 / Approve listed access" : "关闭 / Close"),
|
||||
]),
|
||||
]),
|
||||
])]);
|
||||
return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : []), consent]);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -32,10 +32,10 @@ export const BUILTIN_SKIN_CATALOG: SkinCatalogEntry[] = [
|
||||
{
|
||||
id: BUILTIN_ILLUSIA_SKIN_ID,
|
||||
name: "ILLUSIA风",
|
||||
version: "1.0.29",
|
||||
version: "2.0.0",
|
||||
author: "WebSpeak Project",
|
||||
license: "All rights reserved",
|
||||
description: "A bright original-character art skin for the home, voice room, and demo pages.",
|
||||
description: "A bright original-character art skin with a safe declarative live-channel badge.",
|
||||
minAppVersion: "0.2.7-preview",
|
||||
previewUrl: "/skins/illusia-voice-preview.webp",
|
||||
installedAt: 0,
|
||||
|
||||
@@ -4,6 +4,7 @@ import test from "node:test";
|
||||
import { strToU8, zipSync } from "fflate";
|
||||
import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js";
|
||||
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
|
||||
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
|
||||
const manifest = {
|
||||
schemaVersion: 1,
|
||||
@@ -127,18 +128,19 @@ test("skin content supports localized interface message overrides and includes t
|
||||
assert.ok(skin.assets["assets/preview.png"]);
|
||||
});
|
||||
|
||||
test("the ILLUSIA v2 example and bundled package import without replacing WebSpeak's base translations", async () => {
|
||||
test("the ILLUSIA v3 example and bundled package import without replacing WebSpeak's base translations", async () => {
|
||||
const exampleBytes = await readFile(new URL("../../../docs/examples/illusia-voice.wskin", import.meta.url));
|
||||
const bundledBytes = await readFile(new URL("../../public/skins/illusia-voice.wskin", import.meta.url));
|
||||
assert.deepEqual(bundledBytes, exampleBytes);
|
||||
const skin = await importSkinPack(new File([exampleBytes], "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.29");
|
||||
assert.equal(skin.schemaVersion, 2);
|
||||
assert.equal(skin.packageType, "layout-skin");
|
||||
assert.deepEqual(skin.permissions, []);
|
||||
assert.deepEqual(skin.layoutData, { schemaVersion: 1, pages: {} });
|
||||
assert.equal(skin.version, "2.0.0");
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
assert.equal(skin.packageType, "open-skin");
|
||||
assert.equal(skin.layoutData, undefined);
|
||||
assert.equal(skin.pluginData?.components[0].id, "illusia-now-playing");
|
||||
assert.deepEqual(skin.pluginData?.components[0].permissions, ["session.status.read"]);
|
||||
assert.equal(skin.minAppVersion, "0.2.7-preview");
|
||||
assert.equal(skin.contentData, undefined);
|
||||
assert.equal(skin.previewBlob?.type, "image/webp");
|
||||
@@ -160,6 +162,7 @@ test("the ILLUSIA v2 example and bundled package import without replacing WebSpe
|
||||
assert.match(skin.css, /language\.option/);
|
||||
assert.match(skin.css, /data-ws-skin-id="community\.illusia-voice"/);
|
||||
assert.match(skin.css, /data-ws-part="voice\.favorite-servers\.rail"/);
|
||||
assert.match(skin.css, /data-ws-plugin-part="illusia-now-playing\.channel-name"/);
|
||||
assert.match(skin.css, /data-ws-part="home\.server-history\.item"/);
|
||||
assert.match(skin.css, /data-ws-part="home\.server-history\.favorite-toggle"\]\[data-ws-state="saved"\]/);
|
||||
assert.match(skin.css, /data-ws-part="voice\.favorite-servers\.favorite-toggle"\]\[data-ws-state="saved"\]/);
|
||||
@@ -191,7 +194,8 @@ test("the ILLUSIA v2 example and bundled package import without replacing WebSpe
|
||||
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.match(skin.css, /illusia-now-playing[^{}]*\{[^}]*position:\s*fixed/);
|
||||
assert.match(skin.css, /illusia-now-playing[^{}]*\{[^}]*background-image:[^;]*assets%2Fbanner-mascot-blob\.webp/);
|
||||
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/);
|
||||
@@ -289,6 +293,54 @@ test("schema version 2 skin packages load only validated declarative layouts wit
|
||||
);
|
||||
});
|
||||
|
||||
test("schema version 3 supports arbitrary public layouts and validated declarative plugin components", async () => {
|
||||
const components = {
|
||||
schemaVersion: 1,
|
||||
components: [{
|
||||
id: "channel-list",
|
||||
name: "Channel list",
|
||||
page: "voice",
|
||||
accessibleName: "TeamSpeak channels",
|
||||
permissions: ["session.channels.read", "session.channel.join"],
|
||||
actions: { join: { type: "voice.joinChannel", args: { channelId: "{{channel.id}}" } } },
|
||||
root: {
|
||||
tag: "nav",
|
||||
repeat: { path: "session.channels", as: "channel" },
|
||||
children: [{ tag: "button", part: "row", events: { dblclick: "join" }, children: [{ text: "{{channel.name}}" }] }],
|
||||
},
|
||||
}],
|
||||
};
|
||||
const skin = await importSkinPack(makeSkinV3(components, `
|
||||
[data-ws-part="voice.channel-group"] { display: none; }
|
||||
.channel-row[data-ws-plugin-part="channel-list.row"] { position: fixed; inset: 10px; width: 240px; order: 1; }
|
||||
`));
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
assert.equal(skin.packageType, "open-skin");
|
||||
assert.equal(skin.pluginData?.components[0].id, "channel-list");
|
||||
assert.equal(skin.pluginData?.components[0].root.children?.[0].events?.dblclick, "join");
|
||||
assert.match(skin.css, /position: fixed/);
|
||||
assert.match(skin.css, /display: none/);
|
||||
assert.ok(skin.warnings.some((warning) => warning.includes("hides an interface part")));
|
||||
|
||||
const unsafe = structuredClone(components) as typeof components;
|
||||
unsafe.components[0].permissions = ["network.fetch"];
|
||||
await assert.rejects(importSkinPack(makeSkinV3(unsafe, "[data-ws-part=app] { color: red; }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_INVALID");
|
||||
await assert.rejects(importSkinPack(makeSkinV3({ schemaVersion: 1, components: [] }, "[data-ws-part=app] { color: red; }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_INVALID");
|
||||
const missingAsset = structuredClone(components) as unknown as SkinPluginDocument;
|
||||
missingAsset.components[0].root = { tag: "img", asset: "assets/missing.webp" };
|
||||
await assert.rejects(importSkinPack(makeSkinV3(missingAsset, "[data-ws-part=app] { color: red; }")), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_PLUGIN_ASSET_INVALID");
|
||||
});
|
||||
|
||||
test("the distributable KAAK v3 package validates end to end", async () => {
|
||||
const archive = await readFile(new URL("../../../docs/examples/kaak-voice.wskin", import.meta.url));
|
||||
const file = new File([archive], "kaak-voice.wskin", { type: "application/octet-stream" });
|
||||
const skin = await importSkinPack(file);
|
||||
assert.equal(skin.id, "community.kaak-voice");
|
||||
assert.equal(skin.schemaVersion, 3);
|
||||
assert.equal(skin.pluginData?.components[0].id, "kaak-room-sidebar");
|
||||
assert.ok(skin.css.includes('data-ws-plugin-part="kaak-room-sidebar.channel-row"'));
|
||||
});
|
||||
|
||||
function makeSkinV2(layout: unknown, manifestChanges: Record<string, unknown> = {}): File {
|
||||
const packageFiles: Record<string, Uint8Array> = {
|
||||
"manifest.json": strToU8(JSON.stringify({
|
||||
@@ -305,3 +357,14 @@ function makeSkinV2(layout: unknown, manifestChanges: Record<string, unknown> =
|
||||
const bytes = zipSync(packageFiles);
|
||||
return new File([bytes.slice().buffer as ArrayBuffer], "skin-v2.wskin", { type: "application/octet-stream" });
|
||||
}
|
||||
|
||||
function makeSkinV3(components: unknown, css: string, assets: Record<string, Uint8Array> = {}): File {
|
||||
const packageFiles: Record<string, Uint8Array> = {
|
||||
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 3, packageType: "open-skin", components: "components.json" })),
|
||||
"skin.css": strToU8(css),
|
||||
"components.json": strToU8(JSON.stringify(components)),
|
||||
...assets,
|
||||
};
|
||||
const bytes = zipSync(packageFiles);
|
||||
return new File([bytes.slice().buffer as ArrayBuffer], "skin-v3.wskin", { type: "application/octet-stream" });
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import selectorParser from "postcss-selector-parser";
|
||||
import valueParser from "postcss-value-parser";
|
||||
import { unzipSync } from "fflate";
|
||||
import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js";
|
||||
import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
|
||||
const MAX_ARCHIVE_BYTES = 20 * 1024 * 1024;
|
||||
const MAX_EXPANDED_BYTES = 50 * 1024 * 1024;
|
||||
@@ -52,8 +53,8 @@ const ZIP_EOCD = 0x06054b50;
|
||||
const ZIP_CENTRAL_FILE = 0x02014b50;
|
||||
|
||||
export interface SkinManifest {
|
||||
schemaVersion: 1 | 2;
|
||||
packageType?: "layout-skin";
|
||||
schemaVersion: 1 | 2 | 3;
|
||||
packageType?: "layout-skin" | "open-skin";
|
||||
id: string;
|
||||
name: string;
|
||||
version: string;
|
||||
@@ -64,6 +65,7 @@ export interface SkinManifest {
|
||||
layout?: string;
|
||||
permissions?: [];
|
||||
content?: string;
|
||||
components?: string;
|
||||
minAppVersion: string;
|
||||
preview?: string;
|
||||
}
|
||||
@@ -94,6 +96,7 @@ export interface InstalledSkin extends SkinManifest {
|
||||
assets: Record<string, Blob>;
|
||||
contentData?: SkinContent;
|
||||
layoutData?: SkinLayoutDocument;
|
||||
pluginData?: SkinPluginDocument;
|
||||
previewBlob?: Blob;
|
||||
warnings: string[];
|
||||
installedAt: number;
|
||||
@@ -153,7 +156,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
|
||||
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
|
||||
for (const [path, bytes] of files) {
|
||||
if (["manifest.json", manifest.entry, manifest.layout, manifest.content].includes(path)) continue;
|
||||
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components].includes(path)) continue;
|
||||
const mimeType = assetMimeType(path);
|
||||
if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED");
|
||||
if (mimeType.startsWith("font/") && bytes.byteLength > MAX_FONT_BYTES) throw new SkinPackError("Fonts must be smaller than 4 MiB.", "SKIN_FONT_SIZE");
|
||||
@@ -168,6 +171,17 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
contentData = parseContent(contentBytes);
|
||||
}
|
||||
|
||||
let pluginData: SkinPluginDocument | undefined;
|
||||
if (manifest.components) {
|
||||
const componentsBytes = files.get(manifest.components);
|
||||
if (!componentsBytes || componentsBytes.byteLength > MAX_CONTENT_BYTES) throw new SkinPackError("components.json is missing or exceeds 256 KiB.", "SKIN_PLUGIN_SIZE");
|
||||
try { pluginData = parseSkinPluginJson(decoder.decode(componentsBytes)); }
|
||||
catch (error) { throw new SkinPackError("components.json is invalid: " + (error instanceof Error ? error.message : "unknown plugin error"), "SKIN_PLUGIN_INVALID"); }
|
||||
for (const assetPath of listSkinPluginAssetPaths(pluginData)) {
|
||||
if (!assets[assetPath]?.type.startsWith("image/")) throw new SkinPackError(`Component image asset is missing or unsupported: ${assetPath}`, "SKIN_PLUGIN_ASSET_INVALID");
|
||||
}
|
||||
}
|
||||
|
||||
let layoutData: SkinLayoutDocument | undefined;
|
||||
if (manifest.layout) {
|
||||
const layoutBytes = files.get(manifest.layout);
|
||||
@@ -186,8 +200,8 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
|
||||
previewBlob = new Blob([previewBytes], { type: previewMime });
|
||||
}
|
||||
|
||||
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets);
|
||||
return { ...manifest, css: compiled.css, assets, contentData, layoutData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
|
||||
const compiled = compileSkinCss(decoder.decode(cssBytes), manifest.id, assets, manifest.schemaVersion);
|
||||
return { ...manifest, css: compiled.css, assets, contentData, layoutData, pluginData, previewBlob, warnings: compiled.warnings, installedAt: Date.now() };
|
||||
}
|
||||
|
||||
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
|
||||
@@ -333,9 +347,10 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new SkinPackError("manifest.json must be an object.", "SKIN_MANIFEST_INVALID");
|
||||
const raw = value as Record<string, unknown>;
|
||||
const schemaVersion = raw.schemaVersion;
|
||||
if (schemaVersion !== 1 && schemaVersion !== 2) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion === 2) {
|
||||
if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
|
||||
if (schemaVersion >= 2) {
|
||||
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
|
||||
if (schemaVersion === 3) { fields.delete("permissions"); fields.add("components"); }
|
||||
const unknown = Object.keys(raw).find((key) => !fields.has(key));
|
||||
if (unknown) throw new SkinPackError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
|
||||
}
|
||||
@@ -348,28 +363,32 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
if (schemaVersion === 2 && (raw.packageType !== "layout-skin" || !Array.isArray(raw.permissions) || raw.permissions.length !== 0)) {
|
||||
throw new SkinPackError("Layout skin packages must declare the layout-skin type and no executable permissions.", "SKIN_PERMISSION_INVALID");
|
||||
}
|
||||
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined)) {
|
||||
if (schemaVersion === 3 && raw.packageType !== "open-skin") {
|
||||
throw new SkinPackError("Version 3 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID");
|
||||
}
|
||||
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined || raw.components !== undefined)) {
|
||||
throw new SkinPackError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION");
|
||||
}
|
||||
const id = stringField("id", 80)!;
|
||||
if (!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(id) || id.startsWith("builtin.")) throw new SkinPackError("Skin IDs must be unique lowercase IDs and cannot use the reserved builtin. prefix.", "SKIN_ID_INVALID");
|
||||
const entry = stringField("entry", 120)!;
|
||||
const layout = schemaVersion === 2 ? stringField("layout", 120)! : undefined;
|
||||
const layout = schemaVersion >= 2 ? stringField("layout", 120, schemaVersion === 2)! : undefined;
|
||||
const components = schemaVersion === 3 ? stringField("components", 120)! : undefined;
|
||||
const content = stringField("content", 120, false);
|
||||
const preview = stringField("preview", 120, false);
|
||||
for (const path of [entry, layout, content, preview].filter((item): item is string => Boolean(item))) {
|
||||
for (const path of [entry, layout, content, components, preview].filter((item): item is string => Boolean(item))) {
|
||||
if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID");
|
||||
}
|
||||
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
|
||||
const version = stringField("version", 32)!;
|
||||
const minAppVersion = stringField("minAppVersion", 32)!;
|
||||
if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
|
||||
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, or plugin components path is invalid.", "SKIN_MANIFEST_INVALID");
|
||||
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
|
||||
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
|
||||
return {
|
||||
schemaVersion,
|
||||
...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : {}),
|
||||
...(schemaVersion === 2 ? { packageType: "layout-skin" as const, permissions: [] as [] } : schemaVersion === 3 ? { packageType: "open-skin" as const } : {}),
|
||||
id,
|
||||
name: stringField("name", 80)!,
|
||||
version,
|
||||
@@ -379,6 +398,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
|
||||
entry,
|
||||
layout,
|
||||
content,
|
||||
components,
|
||||
minAppVersion,
|
||||
preview,
|
||||
};
|
||||
@@ -438,7 +458,7 @@ function parseContent(bytes: Uint8Array): SkinContent {
|
||||
return { defaultLocale: root.defaultLocale, locales };
|
||||
}
|
||||
|
||||
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>): { css: string; warnings: string[] } {
|
||||
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>, schemaVersion: SkinManifest["schemaVersion"]): { css: string; warnings: string[] } {
|
||||
const size = new TextEncoder().encode(source).byteLength;
|
||||
if (!size || size > MAX_CSS_BYTES) throw new SkinPackError("The CSS entry must be between 1 byte and 512 KiB.", "SKIN_CSS_SIZE");
|
||||
let root: postcss.Root;
|
||||
@@ -486,7 +506,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 (!selectorUsesPublicHook(rule.selector, schemaVersion === 3)) throw rule.error("Skin selectors must use :root, [data-ws-page], [data-ws-part], or [data-ws-plugin-part] so they stay attached to WebSpeak's stable visual interface.");
|
||||
if (targetsOnlyOptionalVisualParts(rule.selector)) hideableRules.add(rule);
|
||||
try {
|
||||
rule.selector = selectorParser((selectors) => {
|
||||
@@ -543,7 +563,7 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
|
||||
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)) {
|
||||
if (schemaVersion < 3 && 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.");
|
||||
@@ -551,7 +571,7 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
|
||||
throw declaration.error("Executable CSS values are not allowed.");
|
||||
}
|
||||
const compactValue = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment").map((node) => node.value ?? "").join("").toLowerCase();
|
||||
if (["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) {
|
||||
if (schemaVersion < 3 && ["display", "visibility", "opacity", "pointer-events", "clip-path", "mask", "mask-image"].includes(property) && /\b(?:var|attr)\s*\(/i.test(value)) {
|
||||
if (!canHideTarget) throw declaration.error("Visibility and interaction styles can only use indirect values on explicitly optional visual parts.");
|
||||
}
|
||||
const removesVisual = property === "all"
|
||||
@@ -561,15 +581,16 @@ function compileSkinCss(source: string, id: string, assets: Record<string, Blob>
|
||||
|| (property === "pointer-events" && compactValue === "none")
|
||||
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|
||||
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
|
||||
if (removesVisual && !canHideTarget) {
|
||||
if (removesVisual && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be hidden or reset; required controls and their containers must remain available.");
|
||||
}
|
||||
const visuallyRemoves = (property === "transform" && /scale(?:3d)?\(\s*0(?:\s*[,)]|\s*\))/i.test(value))
|
||||
|| (property === "clip-path" && /inset\(\s*50%/i.test(value))
|
||||
|| (property === "filter" && /(?:opacity|brightness)\(\s*0(?:%|\s*[,)]|\s*\))/i.test(value));
|
||||
if (visuallyRemoves && !canHideTarget) {
|
||||
if (visuallyRemoves && !canHideTarget && schemaVersion < 3) {
|
||||
throw declaration.error("Only explicitly optional visual parts may be visually removed.");
|
||||
}
|
||||
if (schemaVersion === 3 && removesVisual) warnings.add("This open skin hides an interface part; keep a usable path to essential voice and recovery controls.");
|
||||
if (/\bz-index\s*:\s*(?:[1-9]\d{4,}|-\d{4,})\b/i.test(`${property}:${value}`) || (property === "position" && value === "fixed")) warnings.add("Fixed positioning or extreme stacking may cover important controls; check the preview on desktop and mobile.");
|
||||
const withScopedNames = rewriteScopedNames(value, property, keyframeNames, fontFamilyNames);
|
||||
declaration.value = rewriteAssetUrls(withScopedNames, (assetPath) => {
|
||||
@@ -597,16 +618,16 @@ function targetsOnlyOptionalVisualParts(selector: string): boolean {
|
||||
}
|
||||
}
|
||||
|
||||
function selectorUsesPublicHook(selector: string): boolean {
|
||||
function selectorUsesPublicHook(selector: string, allowCustomClasses = false): 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 === "attribute" && ["data-ws-part", "data-ws-page", ...(allowCustomClasses ? ["data-ws-plugin-part"] : [])].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;
|
||||
if (!allowCustomClasses && (node.type === "class" || node.type === "id")) usesPrivateName = true;
|
||||
});
|
||||
return scoped && !usesPrivateName;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
createSkinPluginApproval,
|
||||
isSkinPluginPermissionApproved,
|
||||
type SkinPluginApproval,
|
||||
type SkinPluginComponent,
|
||||
type SkinPluginDocument,
|
||||
} from "../../../src/shared/skin-plugin.js";
|
||||
|
||||
const STORAGE_KEY = "webspeak:skin-plugin-approvals";
|
||||
interface ApprovalStore { schemaVersion: 1; grants: Record<string, SkinPluginApproval> }
|
||||
|
||||
function approvalKey(skinId: string, skinVersion: string, component: SkinPluginComponent): string {
|
||||
return `${skinId}@${skinVersion}/${component.page}/${component.id}`;
|
||||
}
|
||||
|
||||
function readStore(): ApprovalStore {
|
||||
try {
|
||||
const raw: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null");
|
||||
if (!raw || typeof raw !== "object" || (raw as Record<string, unknown>).schemaVersion !== 1
|
||||
|| !(raw as Record<string, unknown>).grants || typeof (raw as Record<string, unknown>).grants !== "object") {
|
||||
return { schemaVersion: 1, grants: {} };
|
||||
}
|
||||
return raw as ApprovalStore;
|
||||
} catch {
|
||||
return { schemaVersion: 1, grants: {} };
|
||||
}
|
||||
}
|
||||
|
||||
function writeStore(store: ApprovalStore): void {
|
||||
try { localStorage.setItem(STORAGE_KEY, JSON.stringify(store)); } catch { /* Approval persistence is optional. */ }
|
||||
}
|
||||
|
||||
export function getMissingSkinPluginApprovals(skinId: string, skinVersion: string, document: SkinPluginDocument): SkinPluginComponent[] {
|
||||
const grants = readStore().grants;
|
||||
return document.components.filter((component) => component.permissions.some((permission) =>
|
||||
!isSkinPluginPermissionApproved(grants[approvalKey(skinId, skinVersion, component)], approvalKey(skinId, skinVersion, component), permission)));
|
||||
}
|
||||
|
||||
export function isSkinPluginComponentApproved(skinId: string, skinVersion: string, component: SkinPluginComponent): boolean {
|
||||
if (!component.permissions.length) return true;
|
||||
const pluginId = approvalKey(skinId, skinVersion, component);
|
||||
const grant = readStore().grants[pluginId];
|
||||
return component.permissions.every((permission) => isSkinPluginPermissionApproved(grant, pluginId, permission));
|
||||
}
|
||||
|
||||
export function approveSkinPluginComponents(skinId: string, skinVersion: string, components: readonly SkinPluginComponent[]): void {
|
||||
const store = readStore();
|
||||
for (const component of components) {
|
||||
const pluginId = approvalKey(skinId, skinVersion, component);
|
||||
store.grants[pluginId] = createSkinPluginApproval(pluginId, component.permissions);
|
||||
}
|
||||
writeStore(store);
|
||||
}
|
||||
|
||||
export function revokeSkinPluginApprovals(skinId: string): void {
|
||||
const store = readStore();
|
||||
for (const key of Object.keys(store.grants)) if (key.startsWith(`${skinId}@`)) delete store.grants[key];
|
||||
writeStore(store);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
.ws-plugin-consent-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 2147483647;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 20px;
|
||||
background: rgba(8, 12, 18, .76);
|
||||
color: #f7fbff;
|
||||
font: 14px/1.55 Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.ws-plugin-access-toggle {
|
||||
position: fixed;
|
||||
right: 12px;
|
||||
bottom: 12px;
|
||||
z-index: 2147483000;
|
||||
min-height: 34px;
|
||||
padding: 0 12px;
|
||||
border: 1px solid #8197ac;
|
||||
border-radius: 999px;
|
||||
color: #f7fbff;
|
||||
background: #182331eF;
|
||||
box-shadow: 0 4px 18px #0006;
|
||||
font: 12px/1.2 Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ws-plugin-access-toggle:focus-visible { outline: 3px solid #fbbf24; outline-offset: 3px; }
|
||||
|
||||
.ws-plugin-consent {
|
||||
width: min(640px, 100%);
|
||||
max-height: min(86vh, 800px);
|
||||
overflow-y: auto;
|
||||
padding: 24px;
|
||||
border: 1px solid rgba(165, 196, 220, .38);
|
||||
border-radius: 16px;
|
||||
background: #151d28;
|
||||
box-shadow: 0 28px 90px #0009;
|
||||
}
|
||||
|
||||
.ws-plugin-consent h2 { margin: 0 0 10px; font-size: 20px; }
|
||||
.ws-plugin-consent p { margin: 0 0 16px; color: #c0ccd8; }
|
||||
.ws-plugin-consent-item { margin: 12px 0; padding: 12px 14px; border-radius: 10px; background: #202c39; }
|
||||
.ws-plugin-consent-item ul { margin: 7px 0 0; padding-left: 20px; color: #c7d5e1; }
|
||||
.ws-plugin-consent-note { margin-top: 18px !important; font-size: 12px; }
|
||||
.ws-plugin-consent-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; }
|
||||
.ws-plugin-consent-actions button { min-height: 40px; padding: 0 14px; border-radius: 8px; font: inherit; cursor: pointer; }
|
||||
.ws-plugin-consent-actions .secondary { color: #e3eaf1; background: #303c49; }
|
||||
.ws-plugin-consent-actions .primary { color: #fff; background: #2563eb; font-weight: 700; }
|
||||
.ws-plugin-consent-actions button:focus-visible { outline: 3px solid #fbbf24; outline-offset: 3px; }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.ws-plugin-consent { padding: 18px; }
|
||||
.ws-plugin-consent-actions { flex-direction: column-reverse; }
|
||||
.ws-plugin-consent-actions button { width: 100%; }
|
||||
}
|
||||
@@ -1,5 +1,15 @@
|
||||
<template>
|
||||
<div :class="['demo-page', 'ws-skin-root', { 'skin-initializing': !skinReady }]" :lang="language" data-ws-part="app" data-ws-page="demo">
|
||||
<SkinPluginOutlet
|
||||
v-if="activeSkin?.pluginData"
|
||||
:skin-id="activeSkin.id"
|
||||
:skin-version="activeSkin.version"
|
||||
:document="activeSkin.pluginData"
|
||||
page="demo"
|
||||
:data="skinPluginContext"
|
||||
:assets="activeSkin.assets"
|
||||
:actions="skinPluginActions"
|
||||
/>
|
||||
<header class="demo-header" data-ws-part="demo.header">
|
||||
<div class="demo-brand" data-ws-part="demo.brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
|
||||
<div class="demo-tools" data-ws-part="demo.header-tools"><span class="demo-badge" data-ws-part="demo.badge">{{ copy.demoBadge }}</span><SkinSwitcher v-model="activeSkinId" data-ws-part="demo.skin-switcher" :menu-label="copy.skinSelector" :options="skinOptions" @change="onSkinChange" /><LanguageSwitcher v-model="language" data-ws-part="demo.language-switcher" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/" data-ws-part="demo.home-link">{{ copy.back }}</a></div>
|
||||
@@ -53,6 +63,8 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import "../styles/skin-plugin.css";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
|
||||
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
|
||||
import SkinSwitcher, { type SkinOption } from "../components/SkinSwitcher.vue";
|
||||
@@ -125,6 +137,35 @@ function toggleSpeaking() { speakingId.value = speakingId.value ? "" : selectedC
|
||||
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; }
|
||||
function sendMessage() { const text = draft.value.trim(); if (!text) return; messages.value.push({ id: Date.now(), author: "illusia", time: "now", text, mine: true }); draft.value = ""; }
|
||||
function avatarStyle(name: string) { let hash = 0; for (const char of name) hash = char.charCodeAt(0) + ((hash << 5) - hash); const colors = ["#168f83", "#7b9ed0", "#b99070", "#8b78b9"]; return { background: colors[Math.abs(hash) % colors.length] }; }
|
||||
|
||||
const skinPluginContext = computed(() => ({
|
||||
session: {
|
||||
status: { connected: true, connecting: false, channelId: selectedChannel.value.id, channelName: selectedChannel.value.name, userName: "illusia" },
|
||||
channels: channels.map((channel, depth) => ({ id: channel.id, name: channel.name, parentId: "", depth, memberCount: channel.members.length, current: channel.id === selectedChannel.value.id })),
|
||||
members: selectedChannel.value.members.map((member) => ({
|
||||
id: member.id,
|
||||
name: member.name,
|
||||
channelId: selectedChannel.value.id,
|
||||
status: member.id === speakingId.value ? "speaking" : "online",
|
||||
speaking: member.id === speakingId.value,
|
||||
self: member.id === "illusia",
|
||||
})),
|
||||
},
|
||||
favorites: { items: [] },
|
||||
chat: { messages: visibleMessages.value.map((message) => ({ id: String(message.id), author: message.author, text: messageText(message), time: message.time, kind: message.mine ? "self" : "message", channelId: selectedChannel.value.id })) },
|
||||
}));
|
||||
|
||||
const skinPluginActions = {
|
||||
"voice.joinChannel": (args: Record<string, string | number | boolean>) => {
|
||||
if (typeof args.channelId === "string" && channels.some((channel) => channel.id === args.channelId)) selectChannel(args.channelId);
|
||||
},
|
||||
"favorites.switch": (_args: Record<string, string | number | boolean>) => undefined,
|
||||
"chat.sendMessage": (args: Record<string, string | number | boolean>) => {
|
||||
if (typeof args.text !== "string" || args.text.length > 1000) return;
|
||||
draft.value = args.text;
|
||||
sendMessage();
|
||||
},
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
|
||||
@@ -11,6 +11,16 @@
|
||||
data-ws-part="app"
|
||||
:data-ws-page="showVoiceShell ? 'voice' : 'home'"
|
||||
>
|
||||
<SkinPluginOutlet
|
||||
v-if="activeSkin?.pluginData"
|
||||
:skin-id="activeSkin.id"
|
||||
:skin-version="activeSkin.version"
|
||||
:document="activeSkin.pluginData"
|
||||
:page="showVoiceShell ? 'voice' : 'home'"
|
||||
:data="skinPluginContext"
|
||||
:assets="activeSkin.assets"
|
||||
:actions="skinPluginActions"
|
||||
/>
|
||||
<!-- Connection / welcome screen -->
|
||||
<section
|
||||
v-if="!showVoiceShell"
|
||||
@@ -916,6 +926,7 @@
|
||||
import { observeMobileViewport } from "../services/mobile-viewport.js";
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
|
||||
import VoiceMemberCards from "../components/web-client/VoiceMemberCards.vue";
|
||||
import VoicePerformancePanel from "../components/web-client/VoicePerformancePanel.vue";
|
||||
@@ -1446,6 +1457,82 @@ async function submitFavoriteServerDraft(draft: FavoriteServerDraft): Promise<vo
|
||||
|
||||
const visiblePokes = computed(() => pokeNotifications.slice(-3));
|
||||
|
||||
const opaqueFavoriteTokenById = new Map<string, string>();
|
||||
const skinPluginFavoriteTargets = new Map<string, QuickServer>();
|
||||
const skinPluginFavorites = computed(() => {
|
||||
const targets = quickServers.value.filter((server) => server.isFavorite);
|
||||
const activeIds = new Set(targets.map((server) => server.id));
|
||||
for (const id of opaqueFavoriteTokenById.keys()) if (!activeIds.has(id)) opaqueFavoriteTokenById.delete(id);
|
||||
skinPluginFavoriteTargets.clear();
|
||||
return targets.map((server) => {
|
||||
let token = opaqueFavoriteTokenById.get(server.id);
|
||||
if (!token) {
|
||||
token = globalThis.crypto?.randomUUID?.() ?? `favorite-${Math.random().toString(36).slice(2)}`;
|
||||
opaqueFavoriteTokenById.set(server.id, token);
|
||||
}
|
||||
skinPluginFavoriteTargets.set(token, server);
|
||||
return { id: token, label: server.label, current: isQuickServerTarget(server), kind: "favorite" };
|
||||
});
|
||||
});
|
||||
|
||||
const skinPluginContext = computed(() => ({
|
||||
session: {
|
||||
status: {
|
||||
connected: voiceState.connected,
|
||||
connecting: voiceState.connecting,
|
||||
channelId: currentChannel.value?.id ?? "",
|
||||
channelName: currentChannelName.value,
|
||||
userName: nickname.value,
|
||||
},
|
||||
channels: channelTree.value.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
parentId: item.parentID,
|
||||
depth: item.depth,
|
||||
memberCount: item.members.length,
|
||||
current: item.id === currentChannel.value?.id,
|
||||
})),
|
||||
members: memberChannels.value.flatMap((item) => item.members.map((member) => ({
|
||||
id: String(member.id),
|
||||
name: member.nickname,
|
||||
channelId: item.id,
|
||||
status: member.away ? "away" : member.inputMuted ? "muted" : speakingIds.has(member.id) ? "speaking" : "online",
|
||||
speaking: speakingIds.has(member.id),
|
||||
self: member.id === voiceState.tsClientId,
|
||||
}))),
|
||||
},
|
||||
favorites: { items: skinPluginFavorites.value },
|
||||
chat: {
|
||||
messages: chat.visibleMessages.value.filter((message) => message.scope === "channel").map((message) => ({
|
||||
id: message.id,
|
||||
author: message.invokerName,
|
||||
text: message.message,
|
||||
time: new Date(message.timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
|
||||
kind: message.isSelf ? "self" : "message",
|
||||
channelId: message.targetId ?? currentChannel.value?.id ?? "",
|
||||
})),
|
||||
},
|
||||
}));
|
||||
|
||||
const skinPluginActions = {
|
||||
"voice.joinChannel": (args: Record<string, string | number | boolean>) => {
|
||||
if (!voiceState.connected || typeof args.channelId !== "string") return;
|
||||
const target = channelTree.value.find((item) => item.id === args.channelId);
|
||||
if (target && target.id !== currentChannel.value?.id) selectChannel(target);
|
||||
},
|
||||
"favorites.switch": (args: Record<string, string | number | boolean>) => {
|
||||
if (accessMode.value !== "open" || typeof args.favoriteId !== "string") return;
|
||||
const target = skinPluginFavoriteTargets.get(args.favoriteId);
|
||||
if (target?.isFavorite) connectQuickServer(target);
|
||||
},
|
||||
"chat.sendMessage": (args: Record<string, string | number | boolean>) => {
|
||||
if (!voiceState.connected || typeof args.text !== "string" || !currentChannel.value?.id) return;
|
||||
const text = args.text.trim();
|
||||
if (!text || text.length > 1000 || text.includes("\u0000")) return;
|
||||
void sendTextMessage(text, currentChannel.value.id);
|
||||
},
|
||||
};
|
||||
|
||||
watch(() => pokeNotifications.length, (length, previousLength) => {
|
||||
const latest = pokeNotifications[length - 1];
|
||||
if (!latest || length <= previousLength) return;
|
||||
@@ -1657,3 +1744,5 @@ function resolveSkinMessages(skin: InstalledSkin | null, locale: Language): Reco
|
||||
<style scoped src="../styles/web-client.css"></style>
|
||||
|
||||
<style scoped src="../styles/web-client-mobile.css"></style>
|
||||
|
||||
<style src="../styles/skin-plugin.css"></style>
|
||||
Reference in new issue
Block a user