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

+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();
}
});