feat(skins): complete visual component CRUD authoring

This commit is contained in:
illusia committed 2026-10-10 15:53:51 +08:00
1 parent 3fd8e76a98
commit f2e5695bb6
30 files changed
+1858 -511

No files matched your search

+35 -12
View File
@@ -1,7 +1,8 @@
<template>
<Teleport to="body">
<div v-if="editor.available.value" class="skin-layout-editor" data-ws-layout-editor>
<div v-if="editor.available.value" ref="editorRoot" class="skin-layout-editor" data-ws-layout-editor @keydown.esc.stop.prevent="editor.setOpen(false)">
<button
ref="triggerButton"
class="skin-layout-trigger"
type="button"
:aria-expanded="editor.isOpen.value"
@@ -25,7 +26,7 @@
<h2>{{ editor.labels.value.title }}</h2>
<p>{{ editor.labels.value.hint }}</p>
</div>
<button type="button" class="skin-layout-close" :aria-label="editor.labels.value.close" @click="editor.setOpen(false)">×</button>
<button ref="closeButton" type="button" class="skin-layout-close" :aria-label="editor.labels.value.close" @click="editor.setOpen(false)">×</button>
</header>
<label class="skin-layout-toggle">
@@ -135,11 +136,21 @@
</template>
<script setup lang="ts">
import { ref } from "vue";
import { nextTick, ref, watch } from "vue";
import { useSkinLayoutEditor } from "../composables/useSkinLayoutEditor.js";
import { promoteHostEditorToTopLayer } from "../services/host-editor-top-layer.js";
const editor = useSkinLayoutEditor();
const editorRoot = ref<HTMLElement | null>(null);
const importInput = ref<HTMLInputElement | null>(null);
const triggerButton = ref<HTMLButtonElement | null>(null);
const closeButton = ref<HTMLButtonElement | null>(null);
watch(editorRoot, promoteHostEditorToTopLayer, { flush: "post" });
watch(editor.isOpen, async (isOpen) => {
await nextTick();
(isOpen ? closeButton.value : triggerButton.value)?.focus();
});
async function onImport(event: Event): Promise<void> {
const input = event.target as HTMLInputElement;
@@ -151,10 +162,22 @@ async function onImport(event: Event): Promise<void> {
<style scoped>
.skin-layout-editor {
position: fixed;
z-index: 2147483000;
inset: auto;
z-index: 2147483647;
top: auto;
left: auto;
right: 14px;
bottom: 14px;
width: auto;
height: auto;
max-width: none;
max-height: none;
overflow: visible;
margin: 0;
padding: 0;
border: 0;
color: #172033;
background: transparent;
font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif;
}
@@ -199,28 +222,28 @@ async function onImport(event: Event): Promise<void> {
.skin-layout-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.skin-layout-heading h2 { margin: 0; font-size: 16px; }
.skin-layout-heading p { margin: 5px 0 0; color: #475569; font-size: 12px; }
.skin-layout-close { width: 32px; height: 32px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 22px !important; cursor: pointer; }
.skin-layout-toggle { display: flex; align-items: center; gap: 8px; min-height: 38px; }
.skin-layout-close { width: 44px; height: 44px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 22px !important; cursor: pointer; }
.skin-layout-toggle { display: flex; align-items: center; gap: 8px; min-height: 44px; }
.skin-layout-field { display: grid; gap: 6px; }
.skin-layout-field > span,
.skin-layout-range label,
.skin-layout-colors span { color: #475569; font-size: 12px; }
.skin-layout-field input[type="search"],
.skin-layout-field select { width: 100%; min-height: 36px; padding: 6px 9px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #fff; }
.skin-layout-field select { width: 100%; min-height: 44px; padding: 6px 9px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #fff; }
.skin-layout-range { display: grid; gap: 3px; }
.skin-layout-range label { display: flex; justify-content: space-between; gap: 8px; }
.skin-layout-range output { color: #172033; font-variant-numeric: tabular-nums; }
.skin-layout-range input { width: 100%; accent-color: #4f46e5; }
.skin-layout-range input { width: 100%; min-height: 44px; accent-color: #4f46e5; }
.skin-layout-colors { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
.skin-layout-colors label { display: grid; gap: 4px; }
.skin-layout-colors input { width: 100%; height: 34px; padding: 2px; border: 1px solid #cbd5e1; border-radius: 7px; background: #fff; }
.skin-layout-colors input { width: 100%; height: 44px; padding: 2px; border: 1px solid #cbd5e1; border-radius: 7px; background: #fff; }
.skin-layout-actions { display: flex; flex-wrap: wrap; gap: 7px; }
.skin-layout-actions button { min-height: 36px; padding: 0 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; cursor: pointer; }
.skin-layout-actions button { min-height: 44px; padding: 0 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; cursor: pointer; }
.skin-layout-actions button:disabled { opacity: .5; cursor: not-allowed; }
.skin-layout-file { display: none; }
.skin-layout-status { margin: 0; color: #4338ca; }
.skin-layout-warning { margin: 0; padding: 8px 10px; border: 1px solid #fcd34d; border-radius: 8px; color: #854d0e; background: #fffbeb; }
.skin-layout-warning button { min-height: 32px; margin-top: 6px; padding: 0 9px; border: 1px solid #d97706; border-radius: 7px; color: #78350f; background: #fff; cursor: pointer; }
.skin-layout-warning button { min-height: 44px; margin-top: 6px; padding: 0 9px; border: 1px solid #d97706; border-radius: 7px; color: #78350f; background: #fff; cursor: pointer; }
.skin-layout-context { margin: 0; color: #64748b; font-size: 11px; overflow-wrap: anywhere; }
.skin-layout-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
.skin-layout-focus-list { display: grid; gap: 6px; max-height: 220px; overflow: auto; margin: 0; padding: 0; list-style: none; }
@@ -233,7 +256,7 @@ async function onImport(event: Event): Promise<void> {
.skin-layout-focus-name { flex: 1; }
.skin-layout-focus-name small, .skin-layout-focus-size small { color: #475569; font-size: 10px; }
.skin-layout-focus-size { flex: 0 0 auto; text-align: right; }
.skin-layout-focus-overlay { position: fixed; z-index: 2147482999; inset: 0; pointer-events: none; }
.skin-layout-focus-overlay { position: fixed; z-index: 2147483647; inset: 0; pointer-events: none; }
.skin-layout-focus-marker { position: fixed; box-sizing: border-box; display: grid; place-items: start; padding: 0 2px; border: 2px solid #15803d; border-radius: 3px; color: #fff; background: #15803d40; font: 700 11px/16px ui-sans-serif, system-ui, sans-serif; }
.skin-layout-focus-marker.is-small { border-color: #b91c1c; background: #b91c1c40; }
+124 -78
View File
@@ -1,83 +1,94 @@
<template>
<div v-if="skinId" class="skin-plugin-editor" data-ws-plugin-editor>
<button ref="triggerButton" class="skin-plugin-trigger" type="button" aria-controls="skin-plugin-panel" :aria-expanded="open" @click="open = !open" @keydown.esc.stop.prevent="open = false">
{{ english ? "Components" : "组件结构" }}
</button>
<section v-if="open" id="skin-plugin-panel" class="skin-plugin-panel" role="dialog" aria-modal="false" tabindex="-1" :aria-label="english ? 'Skin component editor' : '皮肤组件编辑器'" @keydown.esc.stop.prevent="open = false">
<header class="skin-plugin-heading">
<div>
<h2>{{ english ? "Skin components" : "皮肤组件" }}</h2>
<p>{{ english ? "Edits are local to this skin version and use the same permission and markup checks as packages." : "修改保存在本机当前皮肤版本中,并继续使用皮肤包相同的权限和标记校验。" }}</p>
</div>
<button ref="closeButton" type="button" class="skin-plugin-close" :aria-label="english ? 'Close' : '关闭'" @click="open = false">×</button>
</header>
<Teleport to="body">
<div v-if="skinId" ref="editorRoot" class="skin-plugin-editor" data-ws-plugin-editor>
<button ref="triggerButton" class="skin-plugin-trigger" type="button" aria-controls="skin-plugin-panel" :aria-expanded="open" @click="open = !open" @keydown.esc.stop.prevent="open = false">
{{ english ? "Components" : "组件结构" }}
</button>
<section v-if="open" id="skin-plugin-panel" class="skin-plugin-panel" role="dialog" aria-modal="false" tabindex="-1" :aria-label="english ? 'Skin component editor' : '皮肤组件编辑器'" @keydown.esc.stop.prevent="open = false">
<header class="skin-plugin-heading">
<div>
<h2>{{ english ? "Skin components" : "皮肤组件" }}</h2>
<p>{{ english ? "Edits are local to this skin version and use the same permission and markup checks as packages." : "修改保存在本机当前皮肤版本中,并继续使用皮肤包相同的权限和标记校验。" }}</p>
</div>
<button ref="closeButton" type="button" class="skin-plugin-close" :aria-label="english ? 'Close' : '关闭'" @click="open = false">×</button>
</header>
<div class="skin-plugin-actions">
<button type="button" :disabled="draftDirty || storageInvalid" @click="createComponent">{{ english ? "Add component" : "新增组件" }}</button>
<button type="button" :disabled="!canUndo || draftDirty || storageInvalid" @click="undo">{{ english ? "Undo" : "撤销" }}</button>
<button type="button" :disabled="!canRedo || draftDirty || storageInvalid" @click="redo">{{ english ? "Redo" : "重做" }}</button>
</div>
<label class="skin-plugin-label">
<span>{{ english ? "Components" : "组件列表" }}</span>
<select :value="selectedComponentId" :disabled="draftDirty || storageInvalid" @change="selectComponent(($event.target as HTMLSelectElement).value)">
<option value="">{{ english ? "Select a component" : "选择组件" }}</option>
<option v-for="component in document.components" :key="component.id" :value="component.id">{{ component.name }} · {{ component.page }} · {{ component.id }}</option>
</select>
</label>
<p v-if="!selectedComponent" class="skin-plugin-empty">{{ english ? "No skin components yet. Add one to begin." : "当前皮肤还没有自定义组件,可以从新增组件开始。" }}</p>
<template v-if="selectedComponent">
<div class="skin-plugin-actions">
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(-1)" :aria-label="english ? 'Move component up' : '组件上移'" @click="moveComponent(-1)">↑</button>
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(1)" :aria-label="english ? 'Move component down' : '组件下移'" @click="moveComponent(1)">↓</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="duplicateComponent">{{ english ? "Duplicate component" : "复制组件" }}</button>
<button type="button" class="is-danger" :disabled="draftDirty || storageInvalid" @click="deleteComponent">{{ english ? "Delete component" : "删除组件" }}</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="createComponent">{{ english ? "Add component" : "新增组件" }}</button>
<button type="button" :disabled="!canUndo || draftDirty || storageInvalid" @click="undo">{{ english ? "Undo" : "撤销" }}</button>
<button type="button" :disabled="!canRedo || draftDirty || storageInvalid" @click="redo">{{ english ? "Redo" : "重做" }}</button>
</div>
<label class="skin-plugin-label">
<span>{{ english ? "Component tree" : "组件树" }}</span>
<select :value="selectedPathKey" :disabled="draftDirty || storageInvalid" @change="selectPath(($event.target as HTMLSelectElement).value)">
<option v-for="row in nodeRows" :key="row.key" :value="row.key" :style="{ paddingInlineStart: (row.depth * 12) + 'px' }">{{ row.label }}</option>
<span>{{ english ? "Components" : "组件列表" }}</span>
<select :value="selectedComponentId" :disabled="draftDirty || storageInvalid" @change="selectComponent(($event.target as HTMLSelectElement).value)">
<option value="">{{ english ? "Select a component" : "选择组件" }}</option>
<option v-for="component in document.components" :key="component.id" :value="component.id">{{ component.name }} · {{ component.page }} · {{ component.id }}</option>
</select>
</label>
<div class="skin-plugin-actions">
<button type="button" :disabled="!canAddChild || draftDirty || storageInvalid" @click="addChild">{{ english ? "Add child" : "添加子节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="addSibling">{{ english ? "Add sibling" : "添加同级节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="duplicateNode">{{ english ? "Duplicate node" : "复制节点" }}</button>
<button type="button" :disabled="!selectedPath.length || !canMove(-1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node up' : '节点上移'" @click="moveNode(-1)">↑</button>
<button type="button" :disabled="!selectedPath.length || !canMove(1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node down' : '节点下移'" @click="moveNode(1)">↓</button>
<button type="button" class="is-danger" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="deleteNode">{{ english ? "Delete node" : "删除节点" }}</button>
</div>
<p v-if="!selectedComponent" class="skin-plugin-empty">{{ english ? "No skin components yet. Add one to begin." : "当前皮肤还没有自定义组件,可以从新增组件开始。" }}</p>
<template v-if="selectedComponent">
<div class="skin-plugin-actions">
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(-1)" :aria-label="english ? 'Move component up' : '组件上移'" @click="moveComponent(-1)">↑</button>
<button type="button" :disabled="draftDirty || storageInvalid || !canMoveComponent(1)" :aria-label="english ? 'Move component down' : '组件下移'" @click="moveComponent(1)">↓</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="duplicateComponent">{{ english ? "Duplicate component" : "复制组件" }}</button>
<button type="button" class="is-danger" :disabled="draftDirty || storageInvalid" @click="deleteComponent">{{ english ? "Delete component" : "删除组件" }}</button>
</div>
<label class="skin-plugin-label skin-plugin-json-label">
<span>{{ editorTarget === "component" ? (english ? "Component definition" : "组件定义") : (english ? "Node definition" : "节点定义") }}</span>
<small>{{ english ? "JSON edits are validated before they are saved or rendered." : "JSON 修改会先经过 schema、权限和安全校验,再保存和渲染。" }}</small>
<textarea v-model="draftJson" :disabled="storageInvalid" spellcheck="false" :aria-label="english ? 'Component or node JSON' : '组件或节点 JSON'"></textarea>
</label>
<div class="skin-plugin-actions">
<button type="button" class="is-primary" :disabled="storageInvalid" @click="applyDraft">{{ english ? "Apply definition" : "应用定义" }}</button>
<button type="button" @click="resetDraft">{{ english ? "Discard draft" : "放弃草稿" }}</button>
</div>
</template>
<label class="skin-plugin-label">
<span>{{ english ? "Component tree" : "组件树" }}</span>
<select :value="selectedPathKey" :disabled="draftDirty || storageInvalid" @change="selectPath(($event.target as HTMLSelectElement).value)">
<option value="">{{ english ? "Select a node to edit" : "选择节点进行编辑" }}</option>
<option v-for="row in nodeRows" :key="row.key" :value="row.key" :style="{ paddingInlineStart: (row.depth * 12) + 'px' }">{{ row.label }}</option>
</select>
</label>
<div class="skin-plugin-actions skin-plugin-file-actions">
<button type="button" @click="exportDocument">{{ english ? "Export components.json" : "导出 components.json" }}</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="importInput?.click()">{{ english ? "Import components.json" : "导入 components.json" }}</button>
<button type="button" :disabled="!hasLocalEdits || draftDirty" @click="resetAll">{{ english ? "Reset local edits" : "清除本地修改" }}</button>
<input ref="importInput" class="skin-plugin-file" type="file" accept="application/json,.json" @change="importDocument" />
</div>
<p v-if="errorMessage" class="skin-plugin-error" role="alert">{{ errorMessage }}</p>
<p v-else-if="draftDirty" class="skin-plugin-status" role="status">{{ english ? "Unapplied draft. Apply it or discard it before other edits." : "有尚未应用的草稿;请先应用或放弃,再进行其他修改。" }}</p>
<p v-else-if="statusMessage" class="skin-plugin-status" role="status">{{ statusMessage }}</p>
<p class="skin-plugin-context">{{ skinId }}@{{ skinVersion }}</p>
</section>
</div>
<label class="skin-plugin-label">
<span>{{ english ? "New node type" : "新增节点类型" }}</span>
<select :value="newNodeType" :disabled="draftDirty || storageInvalid" :aria-label="english ? 'New node type' : '新增节点类型'" @change="newNodeType = ($event.target as HTMLSelectElement).value">
<option value="text">{{ english ? "Text node" : "文本节点" }}</option>
<option v-for="tag in allowedElementTags" :key="tag" :value="tag">{{ "<" + tag + ">" }}</option>
</select>
</label>
<div class="skin-plugin-actions">
<button type="button" :disabled="!canAddChild || draftDirty || storageInvalid" @click="addChild">{{ english ? "Add child" : "添加子节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="addSibling">{{ english ? "Add sibling" : "添加同级节点" }}</button>
<button type="button" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="duplicateNode">{{ english ? "Duplicate node" : "复制节点" }}</button>
<button type="button" :disabled="!selectedPath.length || !canMove(-1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node up' : '节点上移'" @click="moveNode(-1)">↑</button>
<button type="button" :disabled="!selectedPath.length || !canMove(1) || draftDirty || storageInvalid" :aria-label="english ? 'Move node down' : '节点下移'" @click="moveNode(1)">↓</button>
<button type="button" class="is-danger" :disabled="!selectedPath.length || draftDirty || storageInvalid" @click="deleteNode">{{ english ? "Delete node" : "删除节点" }}</button>
</div>
<label class="skin-plugin-label skin-plugin-json-label">
<span>{{ editorTarget === "component" ? (english ? "Component definition" : "组件定义") : (english ? "Node definition" : "节点定义") }}</span>
<small>{{ english ? "JSON edits are validated before they are saved or rendered." : "JSON 修改会先经过 schema、权限和安全校验,再保存和渲染。" }}</small>
<textarea v-model="draftJson" :disabled="storageInvalid" spellcheck="false" :aria-label="english ? 'Component or node JSON' : '组件或节点 JSON'"></textarea>
</label>
<div class="skin-plugin-actions">
<button type="button" class="is-primary" :disabled="storageInvalid" @click="applyDraft">{{ english ? "Apply definition" : "应用定义" }}</button>
<button type="button" @click="resetDraft">{{ english ? "Discard draft" : "放弃草稿" }}</button>
</div>
</template>
<div class="skin-plugin-actions skin-plugin-file-actions">
<button type="button" @click="exportDocument">{{ english ? "Export components.json" : "导出 components.json" }}</button>
<button type="button" :disabled="draftDirty || storageInvalid" @click="importInput?.click()">{{ english ? "Import components.json" : "导入 components.json" }}</button>
<button type="button" :disabled="!hasLocalEdits || draftDirty" @click="resetAll">{{ english ? "Reset local edits" : "清除本地修改" }}</button>
<input ref="importInput" class="skin-plugin-file" type="file" accept="application/json,.json" @change="importDocument" />
</div>
<p v-if="errorMessage" class="skin-plugin-error" role="alert">{{ errorMessage }}</p>
<p v-else-if="draftDirty" class="skin-plugin-status" role="status">{{ english ? "Unapplied draft. Apply it or discard it before other edits." : "有尚未应用的草稿;请先应用或放弃,再进行其他修改。" }}</p>
<p v-else-if="statusMessage" class="skin-plugin-status" role="status">{{ statusMessage }}</p>
<p class="skin-plugin-context">{{ skinId }}@{{ skinVersion }}</p>
</section>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import {
addSkinPluginComponent,
addSkinPluginNode,
@@ -92,7 +103,7 @@ import {
replaceSkinPluginComponent,
replaceSkinPluginNode,
} from "../../../src/shared/skin-plugin-editor.js";
import type { SkinPluginComponent, SkinPluginDocument, SkinPluginNode } from "../../../src/shared/skin-plugin.js";
import { SKIN_PLUGIN_ALLOWED_ELEMENTS, type SkinPluginComponent, type SkinPluginDocument, type SkinPluginNode } from "../../../src/shared/skin-plugin.js";
import {
clearSkinPluginAuthoringDocument,
exportSkinPluginAuthoringDocument,
@@ -101,6 +112,7 @@ import {
loadSkinPluginAuthoringDocument,
saveSkinPluginAuthoringDocument,
} from "../services/skin-plugin-authoring.js";
import { promoteHostEditorToTopLayer } from "../services/host-editor-top-layer.js";
const props = defineProps<{
skinId: string;
@@ -113,17 +125,19 @@ const emit = defineEmits<{ updated: [] }>();
type NodeRow = { key: string; label: string; depth: number };
const emptyDocument: SkinPluginDocument = { schemaVersion: 3, components: [] };
const allowedElementTags = SKIN_PLUGIN_ALLOWED_ELEMENTS;
const voidNodeTags = new Set(["br", "circle", "hr", "img", "input", "line", "path", "polyline", "rect", "wbr"]);
const svgContainerTags = new Set(["svg", "g"]);
const open = ref(false);
const document = ref<SkinPluginDocument>(emptyDocument);
const selectedComponentId = ref("");
const selectedPath = ref<number[]>([]);
const editorTarget = ref<"component" | "node">("component");
const newNodeType = ref("div");
const draftJson = ref("");
const errorMessage = ref("");
const statusMessage = ref("");
const importInput = ref<HTMLInputElement | null>(null);
const editorRoot = ref<HTMLElement | null>(null);
const triggerButton = ref<HTMLButtonElement | null>(null);
const closeButton = ref<HTMLButtonElement | null>(null);
const history = ref<SkinPluginDocument[]>([]);
@@ -134,7 +148,9 @@ const english = computed(() => (props.lang ?? "").toLowerCase().startsWith("en")
const selectedComponent = computed(() => document.value.components.find((component) => component.id === selectedComponentId.value) ?? null);
const selectedNode = computed(() => selectedComponent.value ? getSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value) : null);
const canAddChild = computed(() => Boolean(selectedNode.value?.tag && !voidNodeTags.has(selectedNode.value.tag)));
const selectedPathKey = computed(() => selectedPath.value.join("."));
const selectedPathKey = computed(() => editorTarget.value === "node"
? (selectedPath.value.length ? selectedPath.value.join(".") : "root")
: "");
const canUndo = computed(() => historyIndex.value > 0);
const canRedo = computed(() => historyIndex.value >= 0 && historyIndex.value < history.value.length - 1);
const canMoveComponent = (direction: -1 | 1) => {
@@ -153,7 +169,7 @@ const nodeRows = computed<NodeRow[]>(() => {
const visit = (node: SkinPluginNode, path: number[], depth: number) => {
const name = node.widget ? "widget: " + node.widget : node.tag ? "<" + node.tag + ">" : "text: " + (node.text ?? "").slice(0, 42);
const label = (path.length ? path.map((index) => index + 1).join(".") : "root") + " · " + name;
rows.push({ key: path.join("."), label, depth });
rows.push({ key: path.length ? path.join(".") : "root", label, depth });
node.children?.forEach((child, index) => visit(child, [...path, index], depth + 1));
};
visit(component.root, [], 0);
@@ -191,6 +207,17 @@ function message(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function createNodeDefinition(): SkinPluginNode {
const type = newNodeType.value;
if (type === "text") return { text: english.value ? "New content" : "新建内容" };
if (!SKIN_PLUGIN_ALLOWED_ELEMENTS.some((tag) => tag === type)) throw new Error("Choose a supported safe node type.");
const node: SkinPluginNode = { tag: type };
if (type === "img") node.attributes = { alt: english.value ? "Skin image" : "皮肤图片" };
if (type === "svg") node.children = [{ tag: "g" }];
else if (type !== "g" && !voidNodeTags.has(type)) node.children = [{ text: english.value ? "New content" : "新建内容" }];
return node;
}
function snapshot<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
@@ -234,8 +261,13 @@ function selectComponent(id: string): void {
}
function selectPath(key: string): void {
selectedPath.value = key ? key.split(".").map(Number) : [];
editorTarget.value = "node";
if (!key) {
selectedPath.value = [];
editorTarget.value = "component";
} else {
selectedPath.value = key === "root" ? [] : key.split(".").map(Number);
editorTarget.value = "node";
}
resetDraft();
}
@@ -327,9 +359,8 @@ function addChild(): void {
if (!selectedNode.value?.tag || voidNodeTags.has(selectedNode.value.tag)) return;
const parent = selectedPath.value;
const childIndex = selectedNode.value.children?.length ?? 0;
const tag = svgContainerTags.has(selectedNode.value.tag) ? "g" : "div";
try {
const next = addSkinPluginNode(document.value, selectedComponentId.value, parent, { tag, children: [{ text: english.value ? "New content" : "新建内容" }] });
const next = addSkinPluginNode(document.value, selectedComponentId.value, parent, createNodeDefinition());
if (!save(next)) return;
selectedPath.value = [...parent, childIndex];
editorTarget.value = "node";
@@ -341,9 +372,9 @@ function addSibling(): void {
if (!selectedPath.value.length) return;
const path = [...selectedPath.value];
const parent = getSkinPluginNode(document.value, selectedComponentId.value, path.slice(0, -1));
const tag = parent.tag && svgContainerTags.has(parent.tag) ? "g" : "span";
try {
const next = addSkinPluginNodeSibling(document.value, selectedComponentId.value, path, { tag, children: [{ text: english.value ? "New content" : "新建内容" }] });
if (!parent.tag) throw new Error("Only element nodes can contain siblings.");
const next = addSkinPluginNodeSibling(document.value, selectedComponentId.value, path, createNodeDefinition());
if (!save(next)) return;
path[path.length - 1] += 1;
selectedPath.value = path;
@@ -477,6 +508,9 @@ async function importDocument(event: Event): Promise<void> {
watch(() => [props.skinId, props.skinVersion, props.baseDocument] as const, loadDocument, { immediate: true });
watch(() => [selectedComponentId.value, selectedPathKey.value, editorTarget.value] as const, resetDraft);
onMounted(() => {
promoteHostEditorToTopLayer(editorRoot.value);
});
watch(open, async (isOpen) => {
await nextTick();
const target = isOpen ? closeButton.value : triggerButton.value;
@@ -485,7 +519,7 @@ watch(open, async (isOpen) => {
</script>
<style scoped>
.skin-plugin-editor { position: fixed; z-index: 2147482998; right: 14px; bottom: 72px; color: #172033; font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif; }
.skin-plugin-editor { position: fixed; inset: auto; z-index: 2147483647; top: auto; left: auto; right: 14px; bottom: 72px; width: auto; height: auto; max-width: none; max-height: none; overflow: visible; margin: 0; padding: 0; border: 0; color: #172033; background: transparent; font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif; }
.skin-plugin-editor button, .skin-plugin-editor select, .skin-plugin-editor textarea { font: inherit; }
.skin-plugin-trigger { min-height: 44px; padding: 0 14px; border: 1px solid #cbd5e1; border-radius: 999px; color: #fff; background: #4f46e5; box-shadow: 0 5px 22px #0f172a55; cursor: pointer; }
.skin-plugin-panel { position: absolute; right: 0; bottom: 50px; display: grid; gap: 10px; width: min(460px, calc(100vw - 24px)); max-height: min(82vh, 820px); overflow: auto; padding: 14px; border: 1px solid #cbd5e1; border-radius: 15px; background: #fff; box-shadow: 0 18px 60px #0f172a44; }
@@ -508,5 +542,17 @@ watch(open, async (isOpen) => {
.skin-plugin-status { color: #4338ca; }
.skin-plugin-context { color: #64748b; font-size: 10px; }
.skin-plugin-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
@media (max-width: 520px) { .skin-plugin-editor { right: 10px; bottom: 62px; } .skin-plugin-panel { max-height: 76vh; } }
@media (max-width: 520px) {
.skin-plugin-editor { right: max(10px, env(safe-area-inset-right)); bottom: calc(10px + env(safe-area-inset-bottom)); }
.skin-plugin-panel {
box-sizing: border-box;
width: min(460px, calc(100vw - 20px - env(safe-area-inset-left) - env(safe-area-inset-right)));
max-height: min(76vh, 620px);
}
}
@supports (height: 100dvh) {
@media (max-width: 520px) {
.skin-plugin-panel { max-height: min(620px, calc(100dvh - 76px - env(safe-area-inset-top) - env(safe-area-inset-bottom))); }
}
}
</style>
+27 -3
View File
@@ -4,6 +4,7 @@ import {
SKIN_PLUGIN_PERMISSIONS,
SKIN_PLUGIN_RENDER_NODE_LIMIT,
SKIN_PLUGIN_REPEAT_LIMIT,
listSkinPluginAssetPaths,
parseSkinPluginDocument,
type SkinPluginActionDefinition,
type SkinPluginComponent,
@@ -120,12 +121,35 @@ export default defineComponent({
refresh.value += 1;
}, { immediate: true });
watch(() => [props.skinId, props.skinVersion, props.assets] as const, () => assetUrls.clear());
watch(renderedComponents, (components) => {
assetUrls.retain(listSkinPluginAssetPaths({ schemaVersion: 3, components }));
const activeStateKeys = new Set(components.map(componentStateKey));
for (const key of Object.keys(stateByComponent)) {
if (!activeStateKeys.has(key)) delete stateByComponent[key];
}
}, { immediate: true });
watch(activeSurface, (surface) => emit("surface-change", Boolean(surface)), { immediate: true, flush: "sync" });
function componentStateKey(component: SkinPluginComponent): string {
return JSON.stringify([props.skinId, props.skinVersion, props.componentNamespace, component.id]);
}
function localState(component: SkinPluginComponent): Record<string, Scalar> {
const key = `${props.skinId}/${component.id}`;
if (!stateByComponent[key]) stateByComponent[key] = { ...(component.state ?? {}) };
return stateByComponent[key];
const key = componentStateKey(component);
const defaults = component.state ?? {};
let state = stateByComponent[key];
if (!state) {
state = { ...defaults };
stateByComponent[key] = state;
return state;
}
for (const stateKey of Object.keys(state)) {
if (!Object.hasOwn(defaults, stateKey)) delete state[stateKey];
}
for (const [stateKey, value] of Object.entries(defaults)) {
if (!Object.hasOwn(state, stateKey) || typeof state[stateKey] !== typeof value) state[stateKey] = value;
}
return state;
}
function permissionLabel(permission: string): string {
@@ -0,0 +1,40 @@
import assert from "node:assert/strict";
import test from "node:test";
import { promoteHostEditorToTopLayer } from "./host-editor-top-layer.js";
test("host editors use Popover API top layer when it is available", () => {
const attributes = new Map<string, string>();
let showCount = 0;
const element = {
showPopover() { showCount += 1; },
matches(selector: string) { return selector === ":popover-open" && showCount > 0; },
setAttribute(name: string, value: string) { attributes.set(name, value); },
removeAttribute(name: string) { attributes.delete(name); },
} as unknown as HTMLElement;
promoteHostEditorToTopLayer(element);
promoteHostEditorToTopLayer(element);
assert.equal(attributes.get("popover"), "manual");
assert.equal(showCount, 1, "repeated ref notifications do not reopen an already visible popover");
});
test("host editors keep their ordinary positioning when Popover API is unavailable or fails", () => {
let showCount = 0;
const unsupported = {
setAttribute() { throw new Error("must not add unsupported popover attributes"); },
} as unknown as HTMLElement;
const failingAttributes = new Map<string, string>();
const failing = {
showPopover() { showCount += 1; throw new Error("browser denied popover"); },
setAttribute(name: string, value: string) { failingAttributes.set(name, value); },
removeAttribute(name: string) { failingAttributes.delete(name); },
} as unknown as HTMLElement;
promoteHostEditorToTopLayer(unsupported);
promoteHostEditorToTopLayer(null);
promoteHostEditorToTopLayer(failing);
assert.equal(showCount, 1);
assert.equal(failingAttributes.has("popover"), false, "a failed top-layer promotion leaves the CSS fallback visible");
});
+15
View File
@@ -0,0 +1,15 @@
export function promoteHostEditorToTopLayer(element: HTMLElement | null): void {
const popover = element as (HTMLElement & {
showPopover?: () => void;
matches?: (selectors: string) => boolean;
}) | null;
if (!popover || typeof popover.showPopover !== "function") return;
try {
if (popover.matches?.(":popover-open")) return;
popover.setAttribute("popover", "manual");
popover.showPopover();
} catch {
popover.removeAttribute("popover");
}
}
@@ -350,6 +350,12 @@ test("generated UI rejects executable elements, event handlers, and network/navi
expectOutputError(generatedOutput("runtime-ui", { tag: "div", attributes: { "data-ws-part": "spoofed" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
});
test("generated UI cannot create browser top-layer popovers that cover host controls", () => {
expectOutputError(generatedOutput("runtime-ui", { tag: "div", attributes: { popover: "manual" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
expectOutputError(generatedOutput("runtime-ui", { tag: "button", attributes: { popovertarget: "host-editor" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
expectOutputError(generatedOutput("runtime-ui", { tag: "button", attributes: { popovertargetaction: "show" } }), "SKIN_EXTENSION_UI_ATTRIBUTE_INVALID");
});
test("generated UI enforces component and per-node child limits", () => {
const tooManyComponents = JSON.stringify({
schemaVersion: 4,
@@ -6,7 +6,7 @@ import {
} from "./skin-extension-wasm-ui-loop.js";
import type { SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
function uiOutput(count: number): string {
function uiOutput(count: number, handlerId = "increment"): string {
return JSON.stringify({
schemaVersion: 5,
components: [{
@@ -15,7 +15,7 @@ function uiOutput(count: number): string {
page: "voice",
accessibleName: "Local counter",
state: { count },
root: { tag: "button", events: { click: "increment" }, children: [{ text: String(count) }] },
root: { tag: "button", events: { click: handlerId }, children: [{ text: String(count) }] },
}],
});
}
@@ -76,6 +76,30 @@ test("runtime data refresh reruns the guest without fabricating a user event", a
loop.close();
});
test("host-rejected UI output does not replace the callback document", async () => {
const jobs: SkinExtensionUiInput[] = [];
const rejectedOutput = uiOutput(1, "unaccepted");
const loop = createSkinExtensionWasmUiLoopPrototype({
createRun(input) {
jobs.push(input);
return {
result: Promise.resolve({ uiOutput: input.event ? rejectedOutput : uiOutput(0) }),
close: () => undefined,
};
},
onOutput(output) {
if (output === rejectedOutput) throw new Error("Host rejected the generated document.");
},
});
assert.equal(await loop.start(), true);
assert.equal(await loop.dispatch(clickInput(0)), false);
assert.equal(loop.output, uiOutput(0));
assert.equal(await loop.dispatch(clickInput(1, "unaccepted")), false);
assert.equal(jobs.length, 2, "callbacks from a host-rejected document must not be accepted");
loop.close();
});
test("Wasm UI callback queue is bounded and close cancels active and waiting work", async () => {
let rejectActive!: (error: Error) => void;
let held = false;
@@ -74,13 +74,13 @@ export function createSkinExtensionWasmUiLoopPrototype(options: SkinExtensionWas
activeRun = run;
const result = await run.result;
if (closed || activeRun !== run) return false;
lastState = { ...input.state };
if (result.uiOutput !== null) {
const nextDocument = options.parseOutput?.(result.uiOutput) ?? parseSkinExtensionUiOutput(result.uiOutput);
await options.onOutput?.(result.uiOutput, nextDocument, input);
output = result.uiOutput;
document = nextDocument;
await options.onOutput?.(output, nextDocument, input);
}
lastState = { ...input.state };
return true;
} catch (error) {
if (!closed) report(error);
+4
View File
@@ -48,6 +48,7 @@ test("skin CSS permits visual decoration but prevents layout, text-flow, and con
assert.match(skin.css, /animation: ws-ocean-night-fade-wave 1s/);
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"] { d\\69splay: 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"));
@@ -62,6 +63,9 @@ test("skin CSS permits visual decoration but prevents layout, text-flow, and con
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");
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: u\\72l("https://example.invalid/escaped.png"); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
await assert.rejects(importSkinPack(makeSkin('[data-ws-part="home"] { background-image: u\\72l(h\\74 tps\\3a //example.invalid/escaped-scheme.png); }')), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_EXTERNAL_RESOURCE");
await assert.rejects(importSkinPack(makeSkin('@font-face { font-family: "Local Font"; src: l\\6f cal("Arial"); } [data-ws-part="home"] { color: teal; }')), (error: unknown) => error instanceof Error && error.message.includes("local() is not allowed"));
});
test("custom skins can override theme appearance without !important or private class selectors", () => {
+10 -342
View File
@@ -1,7 +1,6 @@
import postcss, { type AtRule, type Declaration, type Node, type Rule } from "postcss";
import selectorParser from "postcss-selector-parser";
import valueParser from "postcss-value-parser";
import { unzipSync } from "fflate";
import { compileSkinCss as compileSharedSkinCss, rewriteSkinCssAssets, SkinCssValidationError } from "../../../src/shared/skin-css.js";
import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js";
import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { validateSkinExtensionWasmBytes, validateSkinExtensionWasmImportsAndExports } from "./skin-extension-wasm-policy.js";
@@ -21,43 +20,6 @@ const MAX_CSS_BYTES = 512 * 1024;
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",
"voice.member-row.avatar",
"voice.screen-player.viewer-avatar",
"voice.screen-player.live",
"demo.badge",
"demo.wave",
"demo.avatar",
"demo.member-status",
"demo.note",
]);
const ZIP_EOCD = 0x06054b50;
const ZIP_CENTRAL_FILE = 0x02014b50;
@@ -303,17 +265,14 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
export function resolveSkinCssAssets(css: string, assets: Record<string, Blob>): { css: string; objectUrls: string[] } {
const objectUrls: string[] = [];
try {
const root = postcss.parse(css, { from: undefined });
root.walkDecls((declaration) => {
declaration.value = rewriteAssetUrls(declaration.value, (assetPath) => {
const rewritten = rewriteSkinCssAssets(css, (assetPath) => {
const blob = assets[assetPath];
if (!blob) throw new SkinPackError(`Skin asset is missing: ${assetPath}`, "SKIN_ASSET_MISSING");
const url = URL.createObjectURL(blob);
objectUrls.push(url);
return url;
});
});
return { css: root.toString(), objectUrls };
return { css: rewritten, objectUrls };
} catch (error) {
objectUrls.forEach((url) => URL.revokeObjectURL(url));
throw error;
@@ -561,306 +520,15 @@ function parseContent(bytes: Uint8Array): SkinContent {
}
function compileSkinCss(source: string, id: string, assets: Record<string, Blob>, schemaVersion: SkinManifest["schemaVersion"], pluginId?: string): { 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;
try { root = postcss.parse(source, { from: undefined }); }
catch (error) { throw new SkinPackError(`The CSS file could not be parsed: ${(error as Error).message}`, "SKIN_CSS_INVALID"); }
const skinScope = `.ws-skin-root[data-ws-skin="${id}"]`;
const scope = pluginId
? `${skinScope} .ws-plugin-component[data-ws-runtime-plugin="${pluginId}"]`
: skinScope;
const namespace = `ws-${id.replace(/[^a-z0-9_-]/gi, "-")}${pluginId ? `-${pluginId}` : ""}`;
const scopeNodes = selectorParser().astSync(scope).first!.nodes.map((node) => node.clone());
const warnings = new Set<string>();
const keyframeNames = new Map<string, string>();
const fontFamilyNames = new Map<string, string>();
const hideableRules = new WeakSet<Rule>();
let nodeCount = 0;
root.walk((node) => {
nodeCount += 1;
if (nodeCount > 12000) throw new SkinPackError("The CSS file contains too many rules.", "SKIN_CSS_COMPLEXITY");
});
root.walkAtRules((rule: AtRule) => {
const name = rule.name.toLowerCase();
if (!ALLOWED_AT_RULES.has(name)) throw rule.error(`The @${rule.name} rule is not allowed in a skin package.`);
if (name.endsWith("keyframes")) {
const keyframeName = rule.params.trim();
if (!/^[-_a-z][-_a-z0-9]*$/i.test(keyframeName)) throw rule.error("Keyframe names must be simple CSS identifiers.");
keyframeNames.set(keyframeName, `${namespace}-${keyframeName}`);
rule.params = `${namespace}-${keyframeName}`;
} else if (name === "layer") {
const layers = rule.params.split(",").map((layer) => layer.trim());
if (!layers.length || layers.some((layer) => !layer || !layer.split(".").every((part) => /^[-_a-z][-_a-z0-9]*$/i.test(part)))) {
throw rule.error("Skin CSS must use named @layer values so layer names can be isolated.");
}
rule.params = layers.map((layer) => `${namespace}-${layer.split(".").join(`.${namespace}-`)}`).join(", ");
} else if (name === "font-face") {
if (/\blocal\s*\(/i.test(rule.toString())) throw rule.error("@font-face local() is not allowed; include a WOFF2 file in the package.");
const family = rule.nodes?.find((node): node is Declaration => node.type === "decl" && node.prop.toLowerCase() === "font-family");
if (!family) throw rule.error("Each @font-face rule must declare font-family.");
const originalFamily = parseSingleFontFamily(family.value);
const scopedFamily = `${namespace}-${originalFamily.replace(/[^a-z0-9_-]/gi, "-")}`;
fontFamilyNames.set(originalFamily.toLowerCase(), scopedFamily);
family.value = `"${scopedFamily}"`;
}
});
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 (!pluginId && !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) => {
selectors.each((selector) => {
const text = selector.toString().trim();
if (!text) throw new SkinPackError("Empty selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/:global\s*\(|:host(?:-context)?\b/i.test(text)) throw new SkinPackError("Shadow and global escape selectors are not allowed.", "SKIN_CSS_SELECTOR");
if (/^:root\b/.test(text)) {
selector.replaceWith(selectorParser().astSync(text.replace(/^:root\b/, scope)).first!.clone());
return;
}
selector.prepend(selectorParser.combinator({ value: " " }));
for (let index = scopeNodes.length - 1; index >= 0; index -= 1) selector.prepend(scopeNodes[index].clone());
});
}).processSync(rule.selector);
} catch (error) {
if (error instanceof SkinPackError) throw error;
throw rule.error(`A CSS selector is invalid: ${(error as Error).message}`);
}
});
const referencedKeyframes = new Set<string>();
const nonOptionalKeyframes = new Set<string>();
root.walkRules((rule: Rule) => {
if (hasKeyframesAncestor(rule)) return;
const optionalTarget = hideableRules.has(rule);
rule.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
if (property !== "animation" && property !== "animation-name") return;
const value = declaration.value;
if (/\b(?:var|attr)\s*\(|\\/i.test(value)) {
keyframeNames.forEach((_, name) => nonOptionalKeyframes.add(name));
return;
}
for (const name of keyframeNames.keys()) {
if (!referencesCssIdentifier(value, name)) continue;
referencedKeyframes.add(name);
if (!optionalTarget) nonOptionalKeyframes.add(name);
}
});
});
const optionalOnlyKeyframes = new Set([...referencedKeyframes]
.filter((name) => !nonOptionalKeyframes.has(name))
.map((name) => keyframeNames.get(name)!));
root.walkDecls((declaration: Declaration) => {
const property = declaration.prop.toLowerCase();
const value = declaration.value.trim();
const owningRule = findOwningRule(declaration);
const keyframesRule = owningRule ? findKeyframesRule(owningRule) : null;
const canHideTarget = owningRule
? hideableRules.has(owningRule) || Boolean(keyframesRule && optionalOnlyKeyframes.has(keyframesRule.params.trim()))
: false;
if (property.startsWith("--") && !/^--skin-[a-z0-9_-]+$/i.test(property)
&& !(pluginId && property.startsWith(`--plugin-${pluginId}-`))) {
throw declaration.error(pluginId
? `Custom plugin variables must use --plugin-${pluginId}- or --skin- prefixes.`
: "Custom skin variables must use the --skin- prefix so they cannot replace WebSpeak's structural tokens.");
}
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.");
if (["behavior", "-moz-binding"].includes(property) || /expression\s*\(|javascript\s*:|vbscript\s*:/i.test(value)) {
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 (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"
|| (property === "display" && compactValue === "none")
|| (property === "visibility" && /^(?:hidden|collapse)$/.test(compactValue))
|| (property === "opacity" && /^0(?:\.0+)?%?$/.test(compactValue))
|| (property === "pointer-events" && compactValue === "none")
|| (property === "clip-path" && /inset\(\s*50%/.test(compactValue))
|| (property === "mask" && /(?:alpha\(0\)|luminance\(0\))/.test(compactValue));
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 && 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) => {
const blob = assets[assetPath];
if (!blob) throw declaration.error(`CSS references an asset not present in the package: ${assetPath}`);
return `wskin-asset:${encodeURIComponent(assetPath)}`;
});
});
return { css: root.toString(), warnings: [...warnings] };
}
function targetsOnlyOptionalVisualParts(selector: string): boolean {
try {
const parsed = selectorParser().astSync(selector);
return parsed.nodes.length > 0 && parsed.nodes.every((item) => {
if (item.nodes.length !== 1 || item.nodes[0].type !== "attribute") return false;
const attribute = item.nodes[0];
if (attribute.attribute.toLowerCase() !== "data-ws-part" || attribute.operator !== "=") return false;
const part = (attribute.value ?? "").replace(/^['"]|['"]$/g, "");
return OPTIONAL_VISUAL_PARTS.has(part);
});
} catch {
return false;
try { return compileSharedSkinCss(source, id, assets, schemaVersion, pluginId); }
catch (error) {
const cssError = error instanceof SkinCssValidationError
? error
: new SkinCssValidationError(error instanceof Error ? error.message : "The CSS file is invalid.", "SKIN_CSS_INVALID");
throw new SkinPackError(cssError.message, cssError.code);
}
}
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", ...(allowCustomClasses ? ["data-ws-plugin-part"] : [])].includes(node.attribute.toLowerCase())) scoped = true;
if (node.type === "pseudo" && node.value.toLowerCase() === ":root") scoped = true;
if (!allowCustomClasses && (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") {
if (parent.type === "rule") return parent as Rule;
parent = parent.parent;
}
return null;
}
function findKeyframesRule(rule: Rule): AtRule | null {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /(?:^|-)?keyframes$/i.test(parent.name)) return parent as AtRule;
parent = parent.parent;
}
return null;
}
function referencesCssIdentifier(value: string, identifier: string): boolean {
const escaped = identifier.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
return new RegExp(`(^|[^-_a-z0-9])${escaped}(?=$|[^-_a-z0-9])`, "i").test(value);
}
function rewriteAssetUrls(value: string, resolve: (path: string) => string): string {
const parsed = valueParser(value);
const resolvePackageAsset = (rawValue: string): string => {
const raw = rawValue.trim();
if (!raw || raw.startsWith("#")) throw new SkinPackError("CSS images and fonts must point to assets inside this skin package.", "SKIN_EXTERNAL_RESOURCE");
const isInternalMarker = raw.startsWith("wskin-asset:");
if (!isInternalMarker && /^(?:data:|blob:|https?:|\/\/|file:|javascript:)/i.test(raw)) throw new SkinPackError("Only relative paths to assets inside this skin package are allowed in url().", "SKIN_EXTERNAL_RESOURCE");
let path: string;
try { path = isInternalMarker ? decodeURIComponent(raw.slice("wskin-asset:".length)) : normalizeAssetPath(raw); }
catch { throw new SkinPackError("A skin asset reference is invalid.", "SKIN_ASSET_PATH"); }
return resolve(path);
};
const visit = (nodes: typeof parsed.nodes, inImageSet = false): void => {
for (const node of nodes) {
if (node.type === "function" && node.value.toLowerCase() === "url") {
const raw = valueParser.stringify(node.nodes).trim().replace(/^(?:"([\s\S]*)"|'([\s\S]*)')$/, "$1$2").trim();
node.nodes = [{ type: "string", quote: '"', value: resolvePackageAsset(raw), sourceIndex: 0, sourceEndIndex: 0, unclosed: undefined }];
node.before = "";
node.after = "";
continue;
}
if (node.type === "function" && (node.value.toLowerCase() === "image-set" || node.value.toLowerCase() === "-webkit-image-set")) {
for (const child of node.nodes) {
if (child.type === "string") child.value = resolvePackageAsset(child.value);
else if (child.type === "function") visit([child]);
}
continue;
}
if (node.type === "function") visit(node.nodes, inImageSet);
else if (inImageSet && node.type === "string") node.value = resolvePackageAsset(node.value);
}
};
visit(parsed.nodes);
return parsed.toString();
}
function parseSingleFontFamily(value: string): string {
const parsed = valueParser(value).nodes.filter((node) => node.type !== "space" && node.type !== "comment");
if (parsed.length !== 1 || (parsed[0].type !== "string" && parsed[0].type !== "word") || !parsed[0].value.trim()) {
throw new SkinPackError("@font-face must declare exactly one font family.", "SKIN_FONT_FAMILY");
}
return parsed[0].value.trim();
}
function rewriteScopedNames(value: string, property: string, keyframes: Map<string, string>, fontFamilies: Map<string, string>): string {
const parsed = valueParser(value);
if (["animation", "animation-name", "font", "font-family"].includes(property)) {
parsed.walk((node) => {
if (node.type !== "word" && node.type !== "string") return;
const keyframe = keyframes.get(node.value);
if (keyframe) node.value = keyframe;
const family = fontFamilies.get(node.value.toLowerCase());
if (family) node.value = family;
});
}
return parsed.toString();
}
function normalizeAssetPath(raw: string): string {
let path = raw.split(/[?#]/, 1)[0];
try { path = decodeURIComponent(path); } catch { throw new SkinPackError("An asset URL contains invalid encoding.", "SKIN_ASSET_PATH"); }
if (path.startsWith("/") || path.includes("\\") || path.includes("\0") || /^[a-z]:/i.test(path)) throw new SkinPackError("An asset URL must be a relative package path.", "SKIN_ASSET_PATH");
const segments: string[] = [];
for (const segment of path.split("/")) {
if (!segment || segment === ".") continue;
if (segment === "..") {
if (!segments.length) throw new SkinPackError("An asset URL cannot leave the skin package.", "SKIN_ASSET_PATH");
segments.pop();
} else {
segments.push(segment);
}
}
if (!segments.length) throw new SkinPackError("An asset URL must point to a package file.", "SKIN_ASSET_PATH");
return segments.join("/");
}
function hasKeyframesAncestor(rule: Rule): boolean {
let parent = rule.parent;
while (parent && parent.type !== "root") {
if (parent.type === "atrule" && /keyframes$/i.test(parent.name)) return true;
parent = parent.parent;
}
return false;
}
function assetMimeType(path: string): string | null {
const extension = path.split(".").at(-1)?.toLowerCase();
switch (extension) {
@@ -58,3 +58,33 @@ test("a missing plugin asset releases a cached URL instead of returning stale ar
URL.revokeObjectURL = originalRevoke;
}
});
test("plugin asset URLs are released when their final component reference is removed", () => {
const originalCreate = URL.createObjectURL;
const originalRevoke = URL.revokeObjectURL;
const created: string[] = [];
const revoked: string[] = [];
URL.createObjectURL = () => {
const url = `blob:skin-retain-${created.length + 1}`;
created.push(url);
return url;
};
URL.revokeObjectURL = (url) => { revoked.push(url); };
try {
const cache = createSkinPluginAssetUrlCache();
cache.resolve("assets/used.png", { "assets/used.png": new Blob(["used"]) });
cache.resolve("assets/removed.png", { "assets/removed.png": new Blob(["removed"]) });
cache.retain(["assets/used.png"]);
assert.deepEqual(revoked, ["blob:skin-retain-2"]);
assert.equal(cache.size, 1);
cache.retain([]);
assert.deepEqual(revoked, ["blob:skin-retain-2", "blob:skin-retain-1"]);
assert.equal(cache.size, 0);
} finally {
URL.createObjectURL = originalCreate;
URL.revokeObjectURL = originalRevoke;
}
});
@@ -26,6 +26,10 @@ export function createSkinPluginAssetUrlCache() {
clear(): void {
for (const path of urls.keys()) release(path);
},
retain(paths: Iterable<string>): void {
const retained = new Set(paths);
for (const path of urls.keys()) if (!retained.has(path)) release(path);
},
get size(): number { return urls.size; },
};
}
+36 -6
View File
@@ -13,7 +13,7 @@ import {
removeSkinPluginNode,
replaceSkinPluginNode,
} from "../../../src/shared/skin-plugin-editor.js";
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
import {
clearSkinPluginAuthoringDocument,
exportSkinPluginAuthoringDocument,
@@ -101,7 +101,7 @@ test("component order is editable and stays within the selected skin document",
test("duplicating a nested component node gives copied layout parts unique stable IDs", () => {
const source = document();
source.components[0].root.children![0] = {
tag: "div", part: "message", children: [{ tag: "span", part: "author", text: "Author" }],
tag: "div", part: "message", children: [{ tag: "span", part: "author", children: [{ text: "Author" }] }],
};
const copy = duplicateSkinPluginNode(source, "voice-panel", [0]);
assert.equal(copy.part, "message-copy");
@@ -109,6 +109,24 @@ test("duplicating a nested component node gives copied layout parts unique stabl
assert.throws(() => duplicateSkinPluginNode(source, "voice-panel", []), /root cannot be duplicated/i);
});
test("repeated node duplication skips existing layout part IDs", () => {
const source = document();
source.components[0].root.children = [
{ tag: "div", part: "message", children: [{ tag: "span", part: "author" }] },
{ tag: "div", part: "message-copy", children: [{ tag: "span", part: "author-copy" }] },
{ tag: "div", part: "message-copy-2", children: [{ tag: "span", part: "author-copy-2" }] },
];
const first = duplicateSkinPluginNode(source, "voice-panel", [0]);
assert.equal(first.part, "message-copy-3");
assert.equal(first.children?.[0].part, "author-copy-3");
const withFirstCopy = addSkinPluginNodeSibling(source, "voice-panel", [0], first);
const second = duplicateSkinPluginNode(withFirstCopy, "voice-panel", [0]);
assert.equal(second.part, "message-copy-4");
assert.equal(second.children?.[0].part, "author-copy-4");
});
test("component editor rejects unsafe markup and invalid permission/action combinations", () => {
assert.throws(() => addSkinPluginNode(document(), "voice-panel", [], { tag: "script" }), /unsupported HTML element/i);
assert.throws(() => replaceSkinPluginNode(document(), "voice-panel", [0], {
@@ -124,11 +142,23 @@ test("component editor rejects unsafe markup and invalid permission/action combi
});
test("older package trees upgrade to editable schema v3 without losing their component", () => {
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
const editable = editableSkinPluginDocument(legacy);
assert.equal(editable.schemaVersion, 3);
assert.equal(editable.components[0].root.tag, "section");
for (const schemaVersion of [1, 2]) {
const legacy = { ...document(), schemaVersion } as unknown as SkinPluginDocument;
const editable = editableSkinPluginDocument(legacy);
assert.equal(editable.schemaVersion, 3);
assert.equal(editable.components[0].root.tag, "section");
}
const normalizedV1 = parseSkinPluginDocument({ ...document(), schemaVersion: 1 });
assert.equal(normalizedV1.components[0].mode, "widget", "the package parser materializes the schema-v1 default mode");
assert.equal(editableSkinPluginDocument(normalizedV1).schemaVersion, 3,
"revalidating a normalized legacy package must safely strip the parser-generated default before migration");
assert.throws(() => parseSkinPluginDocument({
...document(), schemaVersion: 1,
components: [{ ...document().components[0], mode: "surface" }],
}), /Page surfaces require components schema version 2/i);
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
const legacyWithWidget = structuredClone(legacy);
legacyWithWidget.components[0].permissions = [];
legacyWithWidget.components[0].root = { tag: "section", children: [{ widget: "voice.audio-controls" }] };
@@ -45,3 +45,51 @@ test("Wasm worker governor rejects queued work after the bounded wait", async ()
assert.equal(governor.pendingRuns, 0);
release();
});
test("Wasm worker governor stays bounded and drains a saturated burst in FIFO order", async () => {
const maxConcurrentRuns = 2;
const maxPendingRuns = 64;
const burstSize = 2_000;
const governor = createSkinRuntimePluginWasmGovernor({
maxConcurrentRuns,
maxPendingRuns,
queueTimeoutMs: 10_000,
});
const started: number[] = [];
let active = 0;
let peakActive = 0;
const acquisitions = Array.from({ length: burstSize }, (_, index) => governor.acquire(new AbortController().signal)
.then((release) => {
active += 1;
peakActive = Math.max(peakActive, active);
started.push(index);
return {
index,
release: () => {
active -= 1;
release();
},
};
}, (error: unknown) => ({ index, error })));
assert.equal(governor.activeRuns, maxConcurrentRuns);
assert.equal(governor.pendingRuns, maxPendingRuns);
const overflow = await Promise.all(acquisitions.slice(maxConcurrentRuns + maxPendingRuns));
assert.equal(overflow.length, burstSize - maxConcurrentRuns - maxPendingRuns);
assert.ok(overflow.every((item) => "error" in item
&& item.error instanceof SkinRuntimePluginWasmGovernorError
&& item.error.code === "SKIN_EXTENSION_WASM_QUEUE_FULL"));
for (let index = 0; index < maxConcurrentRuns + maxPendingRuns; index += maxConcurrentRuns) {
const batch = await Promise.all(acquisitions.slice(index, index + maxConcurrentRuns));
assert.ok(batch.every((item) => "release" in item));
batch.forEach((item) => {
if ("release" in item) item.release();
});
}
assert.deepEqual(started, Array.from({ length: maxConcurrentRuns + maxPendingRuns }, (_, index) => index));
assert.equal(peakActive, maxConcurrentRuns);
assert.equal(governor.activeRuns, 0);
assert.equal(governor.pendingRuns, 0);
});
@@ -198,3 +198,43 @@ test("approved Wasm entries run as disposable workers with bounded interpreter o
else Reflect.deleteProperty(globalThis, "window");
}
});
test("a worker that exceeds the execution deadline is terminated and releases its handle", async () => {
const { files, approval } = await approvedFiles();
const previousWorker = Object.getOwnPropertyDescriptor(globalThis, "Worker");
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
let terminated = 0;
class HangingWorker {
onmessage: ((event: MessageEvent<unknown>) => void) | null = null;
onmessageerror: (() => void) | null = null;
onerror: (() => void) | null = null;
postMessage(): void {
queueMicrotask(() => this.onmessage?.({ data: { type: "running" } } as MessageEvent<unknown>));
}
terminate(): void { terminated += 1; }
}
Object.defineProperty(globalThis, "Worker", { configurable: true, value: HangingWorker });
Object.defineProperty(globalThis, "window", { configurable: true, value: { setTimeout, clearTimeout } });
try {
const handle = await createSkinRuntimePluginWasmSandbox({
skinId: "community.sample",
skinVersion: "2.0.0",
plugin,
approval,
files,
readSessionStatus: () => ({ connected: false, channelName: null, memberCount: 0 }),
});
await handle.ready;
await assert.rejects(handle.result, (error: unknown) =>
error instanceof Error && "code" in error && error.code === "SKIN_EXTENSION_WASM_EXECUTION_TIMEOUT");
await handle.stopped;
assert.equal(handle.closeReason, "execution-timeout");
assert.equal(handle.closed, true);
assert.equal(terminated, 1, "the host must terminate the worker when its execution deadline expires");
} finally {
if (previousWorker) Object.defineProperty(globalThis, "Worker", previousWorker);
else Reflect.deleteProperty(globalThis, "Worker");
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
@@ -4,6 +4,8 @@ import test from "node:test";
import {
createSkinExtensionWasmCappedRunProbe,
createSkinExtensionWasmInfiniteRunProbe,
createSkinExtensionWasmLargeUiOutputProbe,
createSkinExtensionWasmOversizedUiOutputProbe,
createSkinExtensionWasmPrefixByteImmediateProbe,
createSkinExtensionWasmUiInputProbe,
createSkinExtensionWasmUiOutputProbe,
@@ -88,6 +90,12 @@ test("the fixed Wasmi artifact caps its own memory and stops guest execution at
"the interpreter must accept payloads larger than the previous 16 KiB cap");
assert.equal(run(createSkinExtensionWasmUiOutputProbe('{"type":"root"}', true)).error, 12,
"the interpreter must reject more than one UI payload per execution");
const largeUiOutput = `{"text":"${"x".repeat(240 * 1024)}"}`;
const largeUiResult = run(createSkinExtensionWasmLargeUiOutputProbe(240 * 1024));
assert.equal(largeUiResult.error, 0, "the interpreter must accept a large payload that remains under the output limit");
assert.equal(largeUiResult.uiOutput, largeUiOutput);
assert.equal(run(createSkinExtensionWasmOversizedUiOutputProbe()).error, 12,
"the interpreter must reject UI output beyond its 256 KiB cap before copying it");
const memory = runtime.memory;
const currentPages = memory.buffer.byteLength / (64 * 1024);
+63
View File
@@ -96,6 +96,69 @@ export function createSkinExtensionWasmUiOutputProbe(output = '{"type":"root"}',
]);
}
/** Calls the UI bridge with a payload length just beyond its 256 KiB output cap. */
export function createSkinExtensionWasmOversizedUiOutputProbe(): Uint8Array {
const oversizedLength = 256 * 1024 + 1;
const body = [
0,
0x41, 0x00,
0x41, ...signedLeb128(oversizedLength),
0x10, 0x00,
0x1a,
0x41, 0x07,
0x0b,
];
return Uint8Array.from([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
...section(1, [2, 0x60, 2, 0x7f, 0x7f, 1, 0x7f, 0x60, 0, 1, 0x7f]),
...section(2, [
2,
...name("env"), ...name("memory"), 0x02, 0x01, 1, 64,
...name("env"), ...name("ui_emit_json"), 0x00, 0,
]),
...section(3, [1, 1]),
...section(7, [1, ...name("run"), 0, 1]),
...section(10, [1, body.length, ...body]),
]);
}
/** Grows bounded guest memory, fills a large JSON payload, and emits it through the host bridge. */
export function createSkinExtensionWasmLargeUiOutputProbe(fillerLength: number): Uint8Array {
const outputPointer = 16;
const prefix = Array.from(new TextEncoder().encode('{"text":"'));
const fillerPointer = outputPointer + prefix.length;
const suffixPointer = fillerPointer + fillerLength;
const outputLength = prefix.length + fillerLength + 2;
const body = [
0,
0x41, 0x03, 0x40, 0x00, 0x1a,
0x41, ...signedLeb128(fillerPointer),
0x41, ...signedLeb128(0x78),
0x41, ...signedLeb128(fillerLength),
0xfc, 0x0b, 0x00,
0x41, ...signedLeb128(suffixPointer), 0x41, ...signedLeb128(0x22), 0x3a, 0x00, 0x00,
0x41, ...signedLeb128(suffixPointer + 1), 0x41, ...signedLeb128(0x7d), 0x3a, 0x00, 0x00,
0x41, ...signedLeb128(outputPointer),
0x41, ...signedLeb128(outputLength),
0x10, 0x00, 0x1a,
0x41, 0x07,
0x0b,
];
return Uint8Array.from([
0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
...section(1, [2, 0x60, 2, 0x7f, 0x7f, 1, 0x7f, 0x60, 0, 1, 0x7f]),
...section(2, [
2,
...name("env"), ...name("memory"), 0x02, 0x01, 1, 64,
...name("env"), ...name("ui_emit_json"), 0x00, 0,
]),
...section(3, [1, 1]),
...section(7, [1, ...name("run"), 0, 1]),
...section(10, [1, body.length, ...body]),
...section(11, [1, 0, 0x41, outputPointer, 0x0b, ...unsignedLeb128(prefix.length), ...prefix]),
]);
}
/** Reads the host-provided bounded local state/event JSON once and echoes it through UI output. */
export function createSkinExtensionWasmUiInputProbe(readTwice = false): Uint8Array {
const readInput = [
+38
View File
@@ -115,3 +115,41 @@ test("a local order override is applied only to the registered element", () => {
assert.equal(pluginRoot.dataset.wsLayoutOrder, "true");
assert.equal(pluginRoot.style.values.get("--ws-layout-order"), "3");
});
test("arbitrary component nodes accept local layout edits while interactive nodes keep a 44px target", () => {
const root = new FakeElement();
root.dataset.wsPage = "home";
root.dataset.wsSkin = "test.skin";
const content = append(root, new FakeElement());
content.dataset.wsPart = "skin.home.demo-banner.node-root-0";
const button = append(root, new FakeElement());
button.dataset.wsPart = "skin.home.demo-banner.control-node-root-1";
const collection = JSON.stringify({
schemaVersion: 2,
skins: {
"test.skin": {
schemaVersion: 1,
pages: { home: { desktop: {
"skin.home.demo-banner.node-root-0": { x: 24, y: 36, width: 280, height: 96, visible: false },
"skin.home.demo-banner.control-node-root-1": { order: 5 },
} } },
},
},
recoveries: {},
});
setGlobal("localStorage", { getItem: () => collection, setItem: () => undefined });
setGlobal("document", { querySelectorAll: () => [root] });
setGlobal("window", { matchMedia: () => ({ matches: false }) });
runtime.refreshSkinLayout();
assert.equal(content.dataset.wsLayoutActive, "true");
assert.equal(content.dataset.wsLayoutHidden, "true");
assert.equal(content.style.values.get("--ws-layout-x"), "24px");
assert.equal(content.style.values.get("--ws-layout-y"), "36px");
assert.equal(content.style.values.get("--ws-layout-width"), "280px");
assert.equal(content.style.values.get("--ws-layout-height"), "96px");
assert.equal(button.style.values.get("--ws-layout-order"), "5");
assert.equal(button.dataset.wsLayoutTouchTarget, "44");
});
+688 -48
View File
@@ -8,6 +8,7 @@ import { createRenderer, nextTick, ssrContextKey, createSSRApp } from "vue";
import { renderToString } from "@vue/server-renderer";
import { createServer } from "vite";
import vuePlugin from "@vitejs/plugin-vue";
import { SKIN_PLUGIN_ALLOWED_ELEMENTS } from "../../src/shared/skin-plugin.js";
let vite;
let SkinPluginEditor;
@@ -15,6 +16,7 @@ let SkinPluginOutlet;
let authoring;
let approvals;
let focusedNode;
let supportsPopoverApi = true;
const localStorageDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
class MemoryStorage {
@@ -24,18 +26,25 @@ class MemoryStorage {
removeItem(key) { this.values.delete(key); }
}
const hostNode = (tag, type = "element") => ({
tag, type, props: {}, text: "", children: [], parent: null, value: "", listeners: new Map(), focus() { focusedNode = this; },
addEventListener(name, listener) {
const listeners = this.listeners.get(name) ?? [];
listeners.push(listener);
this.listeners.set(name, listeners);
},
removeEventListener(name, listener) {
this.listeners.set(name, (this.listeners.get(name) ?? []).filter(candidate => candidate !== listener));
},
dispatchEvent(event) { for (const listener of this.listeners.get(event.type) ?? []) listener(event); },
});
const hostNode = (tag, type = "element") => {
const node = {
tag, type, props: {}, text: "", children: [], parent: null, value: "", listeners: new Map(), popoverOpen: false,
focus() { focusedNode = this; },
setAttribute(name, value) { this.props[name] = value; },
removeAttribute(name) { delete this.props[name]; },
addEventListener(name, listener) {
const listeners = this.listeners.get(name) ?? [];
listeners.push(listener);
this.listeners.set(name, listeners);
},
removeEventListener(name, listener) {
this.listeners.set(name, (this.listeners.get(name) ?? []).filter(candidate => candidate !== listener));
},
dispatchEvent(event) { for (const listener of this.listeners.get(event.type) ?? []) listener(event); },
};
if (supportsPopoverApi) node.showPopover = function () { this.popoverOpen = true; };
return node;
};
const teleportRoot = hostNode("teleport-root");
function insert(child, parent, anchor = null) {
if (child.parent) {
@@ -184,88 +193,146 @@ test("component editor creates, changes, and deletes a skin component tree throu
page: "voice",
lang: "zh",
};
const html = await renderToString(createSSRApp(SkinPluginEditor, props));
assert.match(html, /组件结构/);
const ssrContext = {};
const html = await renderToString(createSSRApp(SkinPluginEditor, props), ssrContext);
assert.doesNotMatch(html, /组件结构/);
assert.match(ssrContext.teleports.body, /组件结构/,
"the editor controls are teleported outside the skin-rendered DOM tree");
const root = hostNode("root");
const app = renderer.createApp(SkinPluginEditor, props);
const hostView = Vue.defineComponent({
setup() {
return () => Vue.h("main", { class: "ws-skin-root", "data-ws-skin": props.skinId }, [
Vue.h(SkinPluginEditor, props),
]);
},
});
const app = renderer.createApp(hostView);
app.provide(ssrContextKey, { modules: new Set() });
app.mount(root);
try {
clickButton(root, "组件结构");
assert.equal(visit(root, node => node.props["data-ws-plugin-editor"] !== undefined), null,
"skin CSS cannot target the host-owned component editor");
const teleportedEditor = visit(teleportRoot, node => node.props["data-ws-plugin-editor"] !== undefined);
assert.ok(teleportedEditor);
await nextTick();
assert.equal(teleportedEditor.popoverOpen, true,
"browsers with the Popover API keep the host editor above skin-authored stacking layers");
clickButton(teleportRoot, "组件结构");
await nextTick();
await nextTick();
assert.equal(app._instance.setupState.open, true, "the trigger opens the editor");
assert.equal(focusedNode?.props["aria-label"], "关闭", "opening moves keyboard focus to the close control");
assert.equal(visit(root, node => node.tag === "button" && nodeText(node).trim() === "组件结构")?.props["aria-expanded"], true);
clickButton(root, "新增组件");
assert.equal(visit(teleportRoot, node => node.tag === "button" && nodeText(node).trim() === "组件结构")?.props["aria-expanded"], true);
clickButton(teleportRoot, "新增组件");
await nextTick();
const key = authoring.getSkinPluginAuthoringStorageKey("community.example", "1.0.0");
let edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components.length, 2);
assert.equal(edited.components[1].id, "custom-component-1");
clickButton(root, "组件上移");
changeSelect(teleportRoot, 1, "root");
await nextTick();
assert.match(nodeText(teleportRoot), /节点定义/, "the root node has a distinct selectable entry in the tree");
editTextarea(teleportRoot, JSON.stringify({ tag: "article", children: [{ text: "新建组件" }] }, null, 2));
await nextTick();
clickButton(teleportRoot, "应用定义");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[1].root.tag, "article",
"selecting the root lets authors replace it through the ordinary node editor");
changeSelect(teleportRoot, 2, "button");
await nextTick();
const nodeTypeOptions = visit(teleportRoot, node => node.tag === "select" && node.props["aria-label"] === "新增节点类型");
assert.ok(nodeTypeOptions.children.some(option => option.props.value === "svg"),
"the node type picker exposes the shared safe element set, including SVG");
clickButton(teleportRoot, "组件上移");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["custom-component-1", "base-panel"]);
clickButton(root, "添加子节点");
clickButton(teleportRoot, "添加子节点");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children.length, 2);
assert.equal(edited.components[0].root.children[1].tag, "button",
"authors can add a selected safe element directly instead of hand-writing its node JSON");
assert.ok(localStorage.getItem(key));
changeSelect(root, 1, "0");
clickButton(teleportRoot, "复制节点");
await nextTick();
editTextarea(root, JSON.stringify({ text: "Edited in the component editor" }, null, 2));
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children.length, 3, "the editor duplicates the selected node as a sibling");
clickButton(teleportRoot, "节点上移");
await nextTick();
clickButton(root, "应用定义");
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children[1].tag, "button", "the selected node moves within its parent");
clickButton(teleportRoot, "节点下移");
await nextTick();
changeSelect(teleportRoot, 2, "text");
await nextTick();
clickButton(teleportRoot, "添加同级节点");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children.length, 4, "the editor adds a sibling beside the selected node");
assert.equal(edited.components[0].root.children[3].text, "新建内容",
"text nodes are available through the same authoring flow");
clickButton(teleportRoot, "删除节点");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children.length, 3, "the editor deletes the selected node without deleting its parent");
changeSelect(teleportRoot, 1, "0");
await nextTick();
editTextarea(teleportRoot, JSON.stringify({ text: "Edited in the component editor" }, null, 2));
await nextTick();
clickButton(teleportRoot, "应用定义");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children[0].text, "Edited in the component editor");
clickButton(root, "撤销");
clickButton(teleportRoot, "撤销");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children[0].text, "新建组件");
clickButton(root, "重做");
clickButton(teleportRoot, "重做");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[0].root.children[0].text, "Edited in the component editor");
clickButton(root, "删除组件");
clickButton(teleportRoot, "删除组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["base-panel"]);
changeSelect(root, 0, "base-panel");
changeSelect(teleportRoot, 0, "base-panel");
await nextTick();
clickButton(root, "复制组件");
clickButton(teleportRoot, "复制组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["base-panel", "base-panel-2"]);
changeSelect(root, 0, "base-panel");
changeSelect(teleportRoot, 0, "base-panel");
await nextTick();
changeSelect(root, 1, "0");
changeSelect(teleportRoot, 1, "0");
await nextTick();
clickButton(root, "删除组件");
clickButton(teleportRoot, "删除组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["base-panel-2"]);
clickButton(root, "新增组件");
clickButton(teleportRoot, "新增组件");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.equal(edited.components[1].id, "custom-component-1");
assert.match(nodeText(root), /组件定义/, "creating after deleting a component from node mode selects the component definition");
assert.match(visit(root, node => node.tag === "textarea").value, /"id": "custom-component-1"/);
assert.match(nodeText(teleportRoot), /组件定义/, "creating after deleting a component from node mode selects the component definition");
assert.match(visit(teleportRoot, node => node.tag === "textarea").value, /"id": "custom-component-1"/);
changeSelect(root, 1, "0");
changeSelect(teleportRoot, 1, "0");
await nextTick();
const importInput = visit(root, node => node.tag === "input");
const importInput = visit(teleportRoot, node => node.tag === "input");
assert.ok(importInput);
const importedDocument = {
schemaVersion: 3,
@@ -278,16 +345,47 @@ test("component editor creates, changes, and deletes a skin component tree throu
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
assert.deepEqual(edited.components.map(component => component.id), ["imported-panel"]);
assert.match(visit(root, node => node.tag === "textarea").value, /"id": "imported-panel"/,
assert.match(visit(teleportRoot, node => node.tag === "textarea").value, /"id": "imported-panel"/,
"importing from node mode selects the imported component definition");
const panel = visit(root, node => node.tag === "section" && node.props.role === "dialog");
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
const previousCreateObjectURL = Object.getOwnPropertyDescriptor(URL, "createObjectURL");
const previousRevokeObjectURL = Object.getOwnPropertyDescriptor(URL, "revokeObjectURL");
let exportedBlob;
let downloadedUrl;
const downloadAnchor = { href: "", download: "", click() { downloadedUrl = this.href; } };
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {
document: { createElement: tag => { assert.equal(tag, "a"); return downloadAnchor; } },
setTimeout: callback => { callback(); return 0; },
},
});
Object.defineProperty(URL, "createObjectURL", { configurable: true, value: blob => { exportedBlob = blob; return "blob:skin-export"; } });
Object.defineProperty(URL, "revokeObjectURL", { configurable: true, value: url => { assert.equal(url, "blob:skin-export"); } });
try {
clickButton(teleportRoot, "导出 components.json");
assert.equal(downloadAnchor.download, "community.example-components.json");
assert.equal(downloadedUrl, "blob:skin-export", "the editor starts a local file download");
assert.ok(exportedBlob instanceof Blob);
assert.deepEqual(authoring.importSkinPluginAuthoringDocument(await exportedBlob.text()), edited,
"the exported editor file round-trips through the same package validator");
} finally {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
if (previousCreateObjectURL) Object.defineProperty(URL, "createObjectURL", previousCreateObjectURL);
else Reflect.deleteProperty(URL, "createObjectURL");
if (previousRevokeObjectURL) Object.defineProperty(URL, "revokeObjectURL", previousRevokeObjectURL);
else Reflect.deleteProperty(URL, "revokeObjectURL");
}
const panel = visit(teleportRoot, node => node.tag === "section" && node.props.role === "dialog");
assert.ok(panel);
assert.equal(panel.props["aria-modal"], "false");
panel.props.onKeydown({ key: "Escape", preventDefault() {}, stopPropagation() {} });
await nextTick();
await nextTick();
assert.equal(visit(root, node => node.tag === "section" && node.props.role === "dialog"), null,
assert.equal(visit(teleportRoot, node => node.tag === "section" && node.props.role === "dialog"), null,
"Escape closes the editor dialog");
assert.equal(nodeText(focusedNode), "组件结构", "closing returns keyboard focus to the trigger");
} finally {
@@ -295,6 +393,308 @@ test("component editor creates, changes, and deletes a skin component tree throu
}
});
test("the node picker can create and delete every schema-safe element and text node", async () => {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
const skinId = "community.node-picker";
const skinVersion = "1.0.0";
const baseDocument = { schemaVersion: 3, components: [] };
const revision = Vue.ref(0);
const editorProps = {
skinId,
skinVersion,
page: "voice",
lang: "zh",
baseDocument,
};
const view = Vue.defineComponent({
setup() {
const currentDocument = () => {
revision.value;
return authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion) ?? baseDocument;
};
return () => Vue.h("main", null, [
Vue.h(SkinPluginOutlet, {
skinId,
skinVersion,
document: currentDocument(),
page: "voice",
data: {},
assets: {},
actions: {},
}),
Vue.h(SkinPluginEditor, { ...editorProps, onUpdated: () => { revision.value += 1; } }),
]);
},
});
const root = hostNode("root");
const app = renderer.createApp(view);
app.provide(ssrContextKey, { modules: new Set() });
app.mount(root);
try {
clickButton(teleportRoot, "组件结构");
await nextTick();
await nextTick();
clickButton(teleportRoot, "新增组件");
await nextTick();
const picker = visit(teleportRoot, node => node.tag === "select" && node.props["aria-label"] === "新增节点类型");
assert.ok(picker);
const choices = picker.children.filter(option => option.tag === "option").map(option => option.props.value);
assert.deepEqual(choices, ["text", ...SKIN_PLUGIN_ALLOWED_ELEMENTS],
"the editor picker stays in sync with the single schema allowlist");
const renderedComponent = () => visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1");
const countRendered = (node, predicate) => (predicate(node) ? 1 : 0) + node.children.reduce((count, child) => count + countRendered(child, predicate), 0);
for (const type of choices) {
changeSelect(teleportRoot, 1, "root");
await nextTick();
changeSelect(teleportRoot, 2, type);
await nextTick();
const initialComponentView = renderedComponent();
assert.ok(initialComponentView);
const initialRoot = initialComponentView.children[0];
const isNewText = node => node.type === "text" && node.text === "新建内容";
const isSelectedTag = node => node.tag === type;
const initialCount = countRendered(initialRoot, type === "text" ? isNewText : isSelectedTag);
clickButton(teleportRoot, "添加子节点");
await nextTick();
let edited = authoring.loadSkinPluginAuthoringDocument(skinId, "1.0.0");
const added = edited.components[0].root.children.at(-1);
if (type === "text") assert.deepEqual(added, { text: "新建内容" });
else assert.equal(added.tag, type, `the picker creates <${type}>`);
if (type === "img") assert.equal(added.attributes.alt, "皮肤图片");
const componentView = renderedComponent();
assert.ok(componentView, "the edited component remains mounted in the page preview");
const componentRoot = componentView.children[0];
assert.equal(countRendered(componentRoot, type === "text" ? isNewText : isSelectedTag), initialCount + 1,
`adding ${type} updates the live preview`);
if (type === "text") {
assert.ok(visit(componentRoot, isNewText), "the authored text node is visible in the live preview");
} else {
assert.ok(visit(componentRoot, node => node.tag === type && node.props["data-ws-part"]?.endsWith("node-root-1")),
`<${type}> receives a stable host layout target in the live preview`);
}
clickButton(teleportRoot, "删除节点");
await nextTick();
edited = authoring.loadSkinPluginAuthoringDocument(skinId, "1.0.0");
assert.equal(edited.components[0].root.children.length, 1, `the created ${type} node can be deleted`);
const afterDelete = renderedComponent()?.children[0];
assert.equal(countRendered(afterDelete, type === "text" ? isNewText : isSelectedTag), initialCount,
`deleting ${type} restores the previous live preview`);
}
} finally {
app.unmount();
}
});
test("corrupt local component edits can be cleared from the editor to restore package CRUD", async () => {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
const skinId = "community.corrupt-edits";
const skinVersion = "1.0.0";
const key = authoring.getSkinPluginAuthoringStorageKey(skinId, skinVersion);
localStorage.setItem(key, "{not valid JSON");
const props = {
skinId,
skinVersion,
page: "voice",
lang: "zh",
baseDocument: {
schemaVersion: 3,
components: [{
id: "package-component",
name: "Package component",
page: "voice",
accessibleName: "Package component",
permissions: [],
actions: {},
root: { tag: "section", children: [{ text: "Package content" }] },
}],
},
};
const root = hostNode("root");
const app = renderer.createApp(SkinPluginEditor, props);
app.provide(ssrContextKey, { modules: new Set() });
app.mount(root);
try {
clickButton(teleportRoot, "组件结构");
await nextTick();
await nextTick();
assert.match(nodeText(teleportRoot), /本地修改无法通过校验/,
"the editor explains that this skin version has invalid saved edits");
const resetButton = visit(teleportRoot, node => node.tag === "button" && nodeText(node).trim() === "清除本地修改");
assert.ok(resetButton);
assert.equal(resetButton.props.disabled, false, "recovery remains enabled for corrupt saved edits");
clickButton(teleportRoot, "清除本地修改");
await nextTick();
assert.equal(localStorage.getItem(key), null, "recovery clears only this skin version's saved edits");
assert.match(nodeText(teleportRoot), /本地修改已清除/);
clickButton(teleportRoot, "新增组件");
await nextTick();
const recovered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion);
assert.deepEqual(recovered.components.map(component => component.id), ["package-component", "custom-component-1"],
"the package document is restored and normal component editing works again");
} finally {
app.unmount();
}
});
test("the first edit upgrades legacy v1 and v2 component packages to v3", async () => {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
for (const schemaVersion of [1, 2]) {
const skinId = `community.legacy-v${schemaVersion}`;
const baseDocument = {
schemaVersion,
components: [{
id: `legacy-component-v${schemaVersion}`,
name: `Legacy v${schemaVersion} component`,
page: "voice",
accessibleName: `Legacy v${schemaVersion} component`,
permissions: [],
actions: {},
root: { tag: "section", children: [{ text: `Original schema v${schemaVersion}` }] },
}],
};
const app = renderer.createApp(SkinPluginEditor, {
skinId,
skinVersion: "1.0.0",
page: "voice",
baseDocument,
});
app.provide(ssrContextKey, { modules: new Set() });
app.mount(hostNode("root"));
try {
clickButton(teleportRoot, "组件结构");
await nextTick();
await nextTick();
clickButton(teleportRoot, "新增组件");
await nextTick();
const saved = authoring.loadSkinPluginAuthoringDocument(skinId, "1.0.0");
assert.equal(saved.schemaVersion, 3, `the first v${schemaVersion} edit is persisted as schema v3`);
assert.deepEqual(saved.components.map(component => component.id), [
`legacy-component-v${schemaVersion}`,
"custom-component-1",
]);
assert.equal(saved.components[0].root.children[0].text, `Original schema v${schemaVersion}`);
assert.equal(baseDocument.schemaVersion, schemaVersion, "the package object stays unchanged while local edits migrate");
} finally {
app.unmount();
}
}
});
test("component editor stays visible in browsers without the Popover API", async () => {
const previousSupport = supportsPopoverApi;
supportsPopoverApi = false;
const root = hostNode("root");
const app = renderer.createApp(SkinPluginEditor, {
skinId: "community.legacy-browser",
skinVersion: "1.0.0",
page: "voice",
baseDocument: { schemaVersion: 3, components: [] },
});
app.provide(ssrContextKey, { modules: new Set() });
app.mount(root);
try {
await nextTick();
const editor = visit(teleportRoot, node => node.props["data-ws-plugin-editor"] !== undefined);
assert.ok(editor);
assert.equal(editor.props.popover, undefined,
"unsupported browsers use the ordinary fixed-position fallback instead of leaving an undisplayed popover");
} finally {
app.unmount();
supportsPopoverApi = previousSupport;
}
});
test("component runtime state is isolated by skin version and reset after deletion or schema changes", async () => {
const skinId = "community.runtime-state-isolation";
const component = {
id: "stateful-panel",
name: "Stateful panel",
page: "voice",
accessibleName: "Stateful panel",
permissions: [],
actions: { toggle: { type: "ui.toggleState", args: { key: "enabled" } } },
state: { enabled: false },
root: { tag: "section", children: [
{ tag: "button", events: { click: "toggle" }, children: [{ text: "Toggle" }] },
{ tag: "span", children: [{ text: "{{state.enabled}}" }] },
] },
};
const version = Vue.ref("1.0.0");
const document = Vue.ref({ schemaVersion: 3, components: [component] });
const hostView = Vue.defineComponent({
setup() {
return () => Vue.h(SkinPluginOutlet, {
skinId,
skinVersion: version.value,
document: document.value,
page: "voice",
data: {},
assets: {},
actions: {},
});
},
});
const root = hostNode("root");
const app = renderer.createApp(hostView);
app.mount(root);
const renderedComponent = () => visit(root, node => node.props["data-ws-plugin-component"] === component.id);
const toggle = () => {
const button = visit(renderedComponent(), node => node.tag === "button");
assert.ok(button?.props.onClick, "the component's local toggle action is rendered");
button.props.onClick({ type: "click", target: button, isTrusted: true });
};
try {
await nextTick();
assert.match(nodeText(renderedComponent()), /false/);
toggle();
await nextTick();
assert.match(nodeText(renderedComponent()), /true/);
version.value = "2.0.0";
await nextTick();
assert.match(nodeText(renderedComponent()), /false/,
"a new skin version starts from its own declared component state");
toggle();
await nextTick();
assert.match(nodeText(renderedComponent()), /true/);
document.value = { schemaVersion: 3, components: [] };
await nextTick();
assert.equal(renderedComponent(), null, "deleting a component removes it from the active runtime");
document.value = { schemaVersion: 3, components: [component] };
await nextTick();
assert.match(nodeText(renderedComponent()), /false/,
"re-adding a deleted component does not revive its previous local state");
document.value = { schemaVersion: 3, components: [{
...component,
actions: {},
state: { enabled: "closed" },
root: { tag: "span", children: [{ text: "{{state.enabled}}" }] },
}] };
await nextTick();
assert.match(nodeText(renderedComponent()), /closed/,
"editing a state key's declared type applies the new default in the live preview");
} finally {
app.unmount();
}
});
test("component create, update, and delete immediately change the rendered skin preview", async () => {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
const skinId = "community.preview";
@@ -328,33 +728,71 @@ test("component create, update, and delete immediately change the rendered skin
app.mount(root);
try {
clickButton(root, "组件结构");
clickButton(teleportRoot, "组件结构");
await nextTick();
await nextTick();
clickButton(root, "新增组件");
clickButton(teleportRoot, "新增组件");
await nextTick();
let rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1");
assert.ok(rendered, "the newly created component is rendered in the page preview");
assert.match(nodeText(rendered), /新建组件/);
changeSelect(teleportRoot, 1, "root");
await nextTick();
editTextarea(teleportRoot, JSON.stringify({ tag: "article", children: [{ text: "根节点已更新" }] }, null, 2));
await nextTick();
clickButton(teleportRoot, "应用定义");
await nextTick();
rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1");
assert.equal(rendered.children[0].tag, "article", "editing the selected root replaces the live preview root");
assert.match(nodeText(rendered), /根节点已更新/);
const saved = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion);
const updated = {
...saved.components[0],
name: "Preview component",
accessibleName: "Preview component",
root: { tag: "section", children: [{ text: "预览已更新" }] },
root: { tag: "section", children: [{ text: "预览已更新" }, { tag: "span", children: [{ text: "尾部" }] }] },
};
editTextarea(root, JSON.stringify(updated, null, 2));
changeSelect(teleportRoot, 1, "");
await nextTick();
clickButton(root, "应用定义");
editTextarea(teleportRoot, JSON.stringify(updated, null, 2));
await nextTick();
clickButton(teleportRoot, "应用定义");
await nextTick();
rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1");
assert.ok(rendered);
assert.match(nodeText(rendered), /预览已更新/, "applying a component definition updates the rendered preview immediately");
clickButton(root, "删除组件");
changeSelect(teleportRoot, 1, "0");
await nextTick();
clickButton(teleportRoot, "节点下移");
await nextTick();
let reordered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion);
assert.deepEqual(reordered.components[0].root.children.map(node => node.text ?? node.tag), ["span", "预览已更新"]);
rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1");
assert.ok(nodeText(rendered).indexOf("尾部") < nodeText(rendered).indexOf("预览已更新"),
"reordering nodes also changes their actual preview order");
clickButton(teleportRoot, "撤销");
await nextTick();
reordered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion);
assert.deepEqual(reordered.components[0].root.children.map(node => node.text ?? node.tag), ["预览已更新", "span"]);
rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1");
assert.ok(nodeText(rendered).indexOf("预览已更新") < nodeText(rendered).indexOf("尾部"),
"undo restores both the saved component tree and its preview");
clickButton(teleportRoot, "重做");
await nextTick();
reordered = authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion);
assert.deepEqual(reordered.components[0].root.children.map(node => node.text ?? node.tag), ["span", "预览已更新"]);
rendered = visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1");
assert.ok(nodeText(rendered).indexOf("尾部") < nodeText(rendered).indexOf("预览已更新"),
"redo restores both the reordered tree and its preview");
clickButton(teleportRoot, "删除组件");
await nextTick();
assert.equal(visit(root, node => node.props["data-ws-plugin-component"] === "custom-component-1"), null,
"deleting the component removes it from the rendered page preview");
@@ -363,6 +801,75 @@ test("component create, update, and delete immediately change the rendered skin
}
});
test("deleting the final image node releases its URL and outlet teardown releases remaining assets", async () => {
const originalCreate = URL.createObjectURL;
const originalRevoke = URL.revokeObjectURL;
const created = [];
const revoked = [];
URL.createObjectURL = () => {
const url = `blob:skin-outlet-${created.length + 1}`;
created.push(url);
return url;
};
URL.revokeObjectURL = (url) => { revoked.push(url); };
const skinId = "community.asset-cleanup";
const skinVersion = "1.0.0";
const image = {
id: "image-panel",
name: "Image panel",
page: "voice",
accessibleName: "Image panel",
permissions: [],
actions: {},
root: { tag: "section", children: [{ tag: "img", asset: "assets/icon.png" }] },
};
const document = Vue.ref({ schemaVersion: 3, components: [image] });
const assets = { "assets/icon.png": new Blob(["icon"]) };
const view = Vue.defineComponent({
setup() {
return () => Vue.h(SkinPluginOutlet, {
skinId,
skinVersion,
document: document.value,
page: "voice",
data: {},
assets,
actions: {},
});
},
});
const root = hostNode("root");
const app = renderer.createApp(view);
app.provide(ssrContextKey, { modules: new Set() });
try {
app.mount(root);
await nextTick();
const firstImage = visit(root, node => node.tag === "img");
assert.equal(firstImage?.props.src, "blob:skin-outlet-1");
document.value = { schemaVersion: 3, components: [{ ...image, root: { tag: "section" } }] };
await nextTick();
assert.deepEqual(revoked, ["blob:skin-outlet-1"],
"removing the final node reference releases the asset URL while keeping its component mounted");
assert.ok(visit(root, node => node.props["data-ws-plugin-component"] === "image-panel"));
assert.equal(visit(root, node => node.tag === "img"), null);
document.value = { schemaVersion: 3, components: [image] };
await nextTick();
assert.equal(visit(root, node => node.tag === "img")?.props.src, "blob:skin-outlet-2",
"re-adding the component receives a fresh object URL");
app.unmount();
assert.deepEqual(revoked, ["blob:skin-outlet-1", "blob:skin-outlet-2"],
"outlet teardown releases every remaining asset URL");
} finally {
URL.createObjectURL = originalCreate;
URL.revokeObjectURL = originalRevoke;
}
});
test("deleting the last surface component immediately restores the host page", async () => {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
const skinId = "community.surface";
@@ -417,10 +924,10 @@ test("deleting the last surface component immediately restores the host page", a
assert.equal(surfaceActive.value, true, "the approved surface replaces the host page");
assert.equal(visit(root, node => node.props["data-native-host"] === "true"), null);
clickButton(root, "组件结构");
clickButton(teleportRoot, "组件结构");
await nextTick();
await nextTick();
clickButton(root, "删除组件");
clickButton(teleportRoot, "删除组件");
await nextTick();
await nextTick();
@@ -431,3 +938,136 @@ test("deleting the last surface component immediately restores the host page", a
app.unmount();
}
});
test("surface access can be refused, approved, and revoked from the host UI", async () => {
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
const skinId = "community.access-lifecycle";
const skinVersion = "1.0.0";
const surface = {
id: "protected-surface",
name: "Protected surface",
page: "voice",
mode: "surface",
accessibleName: "Protected voice page",
permissions: ["ui.surface.replace"],
actions: { toggle: { type: "ui.toggleState", args: { key: "enabled" } } },
state: { enabled: false },
root: { tag: "main", children: [
{ text: "Protected custom page" },
{ tag: "button", events: { click: "toggle" }, children: [{ text: "Toggle state" }] },
{ tag: "span", children: [{ text: "{{state.enabled}}" }] },
] },
};
const baseDocument = { schemaVersion: 3, components: [surface] };
const props = { skinId, skinVersion, baseDocument, page: "voice", lang: "zh" };
const hostView = Vue.defineComponent({
setup() {
const surfaceActive = Vue.ref(false);
const revision = Vue.ref(0);
const currentDocument = () => {
revision.value;
return authoring.loadSkinPluginAuthoringDocument(skinId, skinVersion) ?? baseDocument;
};
return () => Vue.h("main", null, [
surfaceActive.value ? null : Vue.h("section", { "data-native-host": "true" }, "WebSpeak host page"),
Vue.h(SkinPluginOutlet, {
skinId,
skinVersion,
document: currentDocument(),
page: "voice",
data: {},
assets: {},
actions: {},
onSurfaceChange: (active) => { surfaceActive.value = active; },
}),
Vue.h(SkinPluginEditor, { ...props, onUpdated: () => { revision.value += 1; } }),
]);
},
});
const root = hostNode("root");
const app = renderer.createApp(hostView);
app.provide(ssrContextKey, { modules: new Set() });
app.mount(root);
try {
await nextTick();
assert.match(nodeText(teleportRoot), /Replace the built-in public page/,
"the host asks for approval before showing the surface permission");
assert.equal(visit(root, node => node.props["data-native-host"] === "true")?.text, "WebSpeak host page",
"the built-in page remains visible before consent");
assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null);
clickButton(teleportRoot, "暂不启用 / Keep disabled");
await nextTick();
assert.equal(visit(teleportRoot, node => node.props["data-ws-plugin-consent"] === "true"), null,
"refusal closes the consent prompt");
assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null,
"a refused surface does not render");
assert.ok(visit(root, node => node.props["data-native-host"] === "true"),
"refusal leaves the built-in page usable");
clickButton(teleportRoot, "管理皮肤组件权限 / Manage skin component access");
await nextTick();
clickButton(teleportRoot, "批准所列权限 / Approve listed access");
await nextTick();
const activeSurface = visit(root, node => node.props["data-ws-plugin-surface"] === "voice");
assert.ok(activeSurface, "the surface activates only after explicit approval");
assert.match(nodeText(activeSurface), /Protected custom page/);
assert.equal(visit(root, node => node.props["data-native-host"] === "true"), null);
let stateToggle = visit(activeSurface, node => node.tag === "button");
stateToggle.props.onClick({ type: "click", target: stateToggle, isTrusted: true });
await nextTick();
assert.match(nodeText(activeSurface), /true/, "approved UI interactions update component-local state");
clickButton(teleportRoot, "组件结构");
await nextTick();
await nextTick();
const original = baseDocument.components[0];
const expanded = { ...original, permissions: [...original.permissions, "session.status.read"] };
changeSelect(teleportRoot, 0, surface.id);
await nextTick();
editTextarea(teleportRoot, JSON.stringify(expanded, null, 2));
await nextTick();
clickButton(teleportRoot, "应用定义");
await nextTick();
await nextTick();
assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null,
"editing a component to request another permission disables its old approval");
assert.ok(visit(root, node => node.props["data-native-host"] === "true"),
"the host page returns while the changed permission request awaits consent");
assert.equal(approvals.isSkinPluginComponentApproved(skinId, skinVersion, expanded), false);
assert.ok(visit(teleportRoot, node => node.props["data-ws-plugin-consent"] === "true"),
"the changed component is presented for renewed approval");
clickButton(teleportRoot, "批准所列权限 / Approve listed access");
await nextTick();
let reapprovedSurface = visit(root, node => node.props["data-ws-plugin-surface"] === "voice");
assert.ok(reapprovedSurface,
"the updated surface activates after its expanded permission set is approved");
assert.match(nodeText(reapprovedSurface), /false/, "a component awaiting new permissions does not retain its previous state");
stateToggle = visit(reapprovedSurface, node => node.tag === "button");
stateToggle.props.onClick({ type: "click", target: stateToggle, isTrusted: true });
await nextTick();
assert.match(nodeText(reapprovedSurface), /true/);
clickButton(teleportRoot, "管理皮肤组件权限 / Manage skin component access");
await nextTick();
clickButton(teleportRoot, "撤销全部授权 / Revoke all access");
await nextTick();
assert.equal(visit(root, node => node.props["data-ws-plugin-surface"] === "voice"), null,
"revocation removes the active surface immediately");
assert.ok(visit(root, node => node.props["data-native-host"] === "true"),
"revocation restores the built-in page");
assert.equal(approvals.isSkinPluginComponentApproved(skinId, skinVersion, surface), false,
"revocation also removes the persisted component grant");
clickButton(teleportRoot, "管理皮肤组件权限 / Manage skin component access");
await nextTick();
clickButton(teleportRoot, "批准所列权限 / Approve listed access");
await nextTick();
reapprovedSurface = visit(root, node => node.props["data-ws-plugin-surface"] === "voice");
assert.ok(reapprovedSurface);
assert.match(nodeText(reapprovedSurface), /false/, "revocation clears component-local state before the next approval");
} finally {
app.unmount();
}
});