mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 12:02:50 +08:00
feat(skins): add component authoring workflow
This commit is contained in:
1 parent
96c29394f3
commit
0c4cc344ef
25 files changed
+2013
-58
No files matched your search
@@ -0,0 +1,12 @@
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { zipSync } from "fflate";
|
||||
|
||||
const sourceDirectory = new URL("../../docs/examples/harbor-voice/", import.meta.url);
|
||||
const outputPath = fileURLToPath(new URL("../../docs/examples/harbor-voice.wskin", import.meta.url));
|
||||
const files = Object.fromEntries(await Promise.all(["manifest.json", "components.json", "skin.css"].map(async (name) => [
|
||||
name,
|
||||
await readFile(new URL(name, sourceDirectory)),
|
||||
])));
|
||||
|
||||
await writeFile(outputPath, zipSync(files, { level: 9 }));
|
||||
@@ -0,0 +1,512 @@
|
||||
<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>
|
||||
|
||||
<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>
|
||||
</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>
|
||||
</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>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref, watch } from "vue";
|
||||
import {
|
||||
addSkinPluginComponent,
|
||||
addSkinPluginNode,
|
||||
addSkinPluginNodeSibling,
|
||||
editableSkinPluginDocument,
|
||||
getSkinPluginNode,
|
||||
moveSkinPluginComponent as movePluginComponent,
|
||||
moveSkinPluginNode as movePluginNode,
|
||||
duplicateSkinPluginNode,
|
||||
removeSkinPluginComponent,
|
||||
removeSkinPluginNode,
|
||||
replaceSkinPluginComponent,
|
||||
replaceSkinPluginNode,
|
||||
} from "../../../src/shared/skin-plugin-editor.js";
|
||||
import type { SkinPluginComponent, SkinPluginDocument, SkinPluginNode } from "../../../src/shared/skin-plugin.js";
|
||||
import {
|
||||
clearSkinPluginAuthoringDocument,
|
||||
exportSkinPluginAuthoringDocument,
|
||||
hasSkinPluginAuthoringDocument,
|
||||
importSkinPluginAuthoringDocument,
|
||||
loadSkinPluginAuthoringDocument,
|
||||
saveSkinPluginAuthoringDocument,
|
||||
} from "../services/skin-plugin-authoring.js";
|
||||
|
||||
const props = defineProps<{
|
||||
skinId: string;
|
||||
skinVersion: string;
|
||||
baseDocument?: SkinPluginDocument;
|
||||
page: "home" | "voice" | "demo";
|
||||
lang?: string;
|
||||
}>();
|
||||
const emit = defineEmits<{ updated: [] }>();
|
||||
|
||||
type NodeRow = { key: string; label: string; depth: number };
|
||||
const emptyDocument: SkinPluginDocument = { schemaVersion: 3, components: [] };
|
||||
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 draftJson = ref("");
|
||||
const errorMessage = ref("");
|
||||
const statusMessage = ref("");
|
||||
const importInput = ref<HTMLInputElement | null>(null);
|
||||
const triggerButton = ref<HTMLButtonElement | null>(null);
|
||||
const closeButton = ref<HTMLButtonElement | null>(null);
|
||||
const history = ref<SkinPluginDocument[]>([]);
|
||||
const historyIndex = ref(-1);
|
||||
const editRevision = ref(0);
|
||||
const storageInvalid = ref(false);
|
||||
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 canUndo = computed(() => historyIndex.value > 0);
|
||||
const canRedo = computed(() => historyIndex.value >= 0 && historyIndex.value < history.value.length - 1);
|
||||
const canMoveComponent = (direction: -1 | 1) => {
|
||||
const index = document.value.components.findIndex((component) => component.id === selectedComponentId.value);
|
||||
return index >= 0 && index + direction >= 0 && index + direction < document.value.components.length;
|
||||
};
|
||||
const hasLocalEdits = computed(() => { editRevision.value; return hasSkinPluginAuthoringDocument(props.skinId, props.skinVersion); });
|
||||
const draftDirty = computed(() => {
|
||||
const current = editorTarget.value === "component" ? selectedComponent.value : selectedNode.value;
|
||||
return Boolean(current && draftJson.value !== JSON.stringify(current, null, 2));
|
||||
});
|
||||
const nodeRows = computed<NodeRow[]>(() => {
|
||||
const component = selectedComponent.value;
|
||||
if (!component) return [];
|
||||
const rows: 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 });
|
||||
node.children?.forEach((child, index) => visit(child, [...path, index], depth + 1));
|
||||
};
|
||||
visit(component.root, [], 0);
|
||||
return rows;
|
||||
});
|
||||
|
||||
function activeBase(): SkinPluginDocument {
|
||||
return editableSkinPluginDocument(props.baseDocument ?? emptyDocument);
|
||||
}
|
||||
|
||||
function loadDocument(): void {
|
||||
try {
|
||||
const hasStoredDocument = hasSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
|
||||
const savedDocument = loadSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
|
||||
storageInvalid.value = hasStoredDocument && !savedDocument;
|
||||
document.value = savedDocument ?? activeBase();
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) {
|
||||
selectedComponentId.value = document.value.components[0]?.id ?? "";
|
||||
}
|
||||
history.value = [document.value];
|
||||
historyIndex.value = 0;
|
||||
resetDraft();
|
||||
errorMessage.value = storageInvalid.value
|
||||
? (english.value ? "Saved edits are invalid. Clear this skin version's local edits to restore its package." : "本地修改无法通过校验。清除当前皮肤版本的本地修改即可恢复皮肤包。")
|
||||
: "";
|
||||
} catch (error) {
|
||||
document.value = activeBase();
|
||||
errorMessage.value = message(error);
|
||||
}
|
||||
}
|
||||
|
||||
function message(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function snapshot<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
|
||||
function save(next: unknown): boolean {
|
||||
try {
|
||||
if (storageInvalid.value) throw new Error(english.value ? "Clear the invalid local edits before saving." : "请先清除无效的本地修改,再保存。");
|
||||
const normalized = editableSkinPluginDocument(next);
|
||||
saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, normalized);
|
||||
const nextHistory = history.value.slice(0, historyIndex.value + 1);
|
||||
nextHistory.push(snapshot(normalized));
|
||||
history.value = nextHistory.slice(-50);
|
||||
historyIndex.value = history.value.length - 1;
|
||||
editRevision.value += 1;
|
||||
document.value = normalized;
|
||||
if (!normalized.components.some((component) => component.id === selectedComponentId.value)) {
|
||||
selectedComponentId.value = normalized.components[0]?.id ?? "";
|
||||
selectedPath.value = [];
|
||||
}
|
||||
if (editorTarget.value === "node" && selectedComponent.value) {
|
||||
try { getSkinPluginNode(normalized, selectedComponentId.value, selectedPath.value); }
|
||||
catch { selectedPath.value = []; editorTarget.value = "component"; }
|
||||
}
|
||||
statusMessage.value = english.value ? "Saved on this device." : "已保存到本机。";
|
||||
errorMessage.value = "";
|
||||
resetDraft();
|
||||
emit("updated");
|
||||
return true;
|
||||
} catch (error) {
|
||||
errorMessage.value = message(error);
|
||||
statusMessage.value = "";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectComponent(id: string): void {
|
||||
selectedComponentId.value = id;
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
resetDraft();
|
||||
}
|
||||
|
||||
function selectPath(key: string): void {
|
||||
selectedPath.value = key ? key.split(".").map(Number) : [];
|
||||
editorTarget.value = "node";
|
||||
resetDraft();
|
||||
}
|
||||
|
||||
function resetDraft(): void {
|
||||
const component = selectedComponent.value;
|
||||
if (!component) { draftJson.value = ""; return; }
|
||||
const current = editorTarget.value === "component" ? component : selectedNode.value;
|
||||
draftJson.value = current ? JSON.stringify(current, null, 2) : "";
|
||||
}
|
||||
|
||||
function applyDraft(): void {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(draftJson.value);
|
||||
if (editorTarget.value === "component") {
|
||||
const next = replaceSkinPluginComponent(document.value, selectedComponentId.value, parsed);
|
||||
const nextComponent = (parsed as SkinPluginComponent).id;
|
||||
if (save(next)) {
|
||||
selectedComponentId.value = nextComponent;
|
||||
selectedPath.value = [];
|
||||
resetDraft();
|
||||
}
|
||||
} else {
|
||||
const next = replaceSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value, parsed);
|
||||
save(next);
|
||||
}
|
||||
} catch (error) { errorMessage.value = message(error); statusMessage.value = ""; }
|
||||
}
|
||||
|
||||
function createComponent(): void {
|
||||
const baseId = "custom-component";
|
||||
const ids = new Set(document.value.components.map((component) => component.id));
|
||||
let suffix = 1;
|
||||
while (ids.has(baseId + "-" + suffix)) suffix += 1;
|
||||
const id = baseId + "-" + suffix;
|
||||
const component: SkinPluginComponent = {
|
||||
id,
|
||||
name: english.value ? "Custom component" : "自定义组件",
|
||||
page: props.page === "demo" ? "home" : props.page,
|
||||
accessibleName: english.value ? "Custom component" : "自定义组件",
|
||||
permissions: [],
|
||||
actions: {},
|
||||
root: { tag: "section", children: [{ text: english.value ? "New component" : "新建组件" }] },
|
||||
};
|
||||
try {
|
||||
if (!save(addSkinPluginComponent(document.value, component))) return;
|
||||
selectedComponentId.value = id;
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function duplicateComponent(): void {
|
||||
const source = selectedComponent.value;
|
||||
if (!source) return;
|
||||
const stem = source.id.slice(0, 56);
|
||||
let suffix = 2;
|
||||
let id = stem + "-" + suffix;
|
||||
const ids = new Set(document.value.components.map((component) => component.id));
|
||||
while (ids.has(id)) id = stem + "-" + (++suffix);
|
||||
const copy = { ...snapshot(source), id, name: source.name.slice(0, 72) + (english.value ? " copy" : " 副本"), accessibleName: source.accessibleName.slice(0, 108) + (english.value ? " copy" : " 副本") };
|
||||
try {
|
||||
if (!save(addSkinPluginComponent(document.value, copy))) return;
|
||||
selectedComponentId.value = id;
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function deleteComponent(): void {
|
||||
if (!selectedComponentId.value) return;
|
||||
try {
|
||||
if (!save(removeSkinPluginComponent(document.value, selectedComponentId.value))) return;
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
resetDraft();
|
||||
}
|
||||
catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function moveComponent(direction: -1 | 1): void {
|
||||
if (!selectedComponentId.value || !canMoveComponent(direction)) return;
|
||||
try { save(movePluginComponent(document.value, selectedComponentId.value, direction)); }
|
||||
catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
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" : "新建内容" }] });
|
||||
if (!save(next)) return;
|
||||
selectedPath.value = [...parent, childIndex];
|
||||
editorTarget.value = "node";
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
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 (!save(next)) return;
|
||||
path[path.length - 1] += 1;
|
||||
selectedPath.value = path;
|
||||
editorTarget.value = "node";
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function duplicateNode(): void {
|
||||
if (!selectedPath.value.length || !selectedNode.value) return;
|
||||
const path = [...selectedPath.value];
|
||||
const copy = duplicateSkinPluginNode(document.value, selectedComponentId.value, path);
|
||||
try {
|
||||
const next = addSkinPluginNodeSibling(document.value, selectedComponentId.value, path, copy);
|
||||
if (!save(next)) return;
|
||||
path[path.length - 1] += 1;
|
||||
selectedPath.value = path;
|
||||
editorTarget.value = "node";
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function deleteNode(): void {
|
||||
if (!selectedPath.value.length) return;
|
||||
try {
|
||||
const next = removeSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value);
|
||||
if (!save(next)) return;
|
||||
selectedPath.value = selectedPath.value.slice(0, -1);
|
||||
editorTarget.value = "node";
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function canMove(direction: -1 | 1): boolean {
|
||||
if (!selectedPath.value.length) return false;
|
||||
const index = selectedPath.value[selectedPath.value.length - 1];
|
||||
const parent = getSkinPluginNode(document.value, selectedComponentId.value, selectedPath.value.slice(0, -1));
|
||||
return index + direction >= 0 && index + direction < (parent.children?.length ?? 0);
|
||||
}
|
||||
|
||||
function moveNode(direction: -1 | 1): void {
|
||||
try {
|
||||
const next = movePluginNode(document.value, selectedComponentId.value, selectedPath.value, direction);
|
||||
if (!save(next)) return;
|
||||
const path = [...selectedPath.value];
|
||||
path[path.length - 1] += direction;
|
||||
selectedPath.value = path;
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function undo(): void {
|
||||
if (!canUndo.value) return;
|
||||
historyIndex.value -= 1;
|
||||
const value = history.value[historyIndex.value];
|
||||
try {
|
||||
document.value = saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, value);
|
||||
editRevision.value += 1;
|
||||
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) selectedComponentId.value = document.value.components[0]?.id ?? "";
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
statusMessage.value = english.value ? "Change undone." : "已撤销。";
|
||||
resetDraft();
|
||||
emit("updated");
|
||||
} catch (error) { historyIndex.value += 1; errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function redo(): void {
|
||||
if (!canRedo.value) return;
|
||||
historyIndex.value += 1;
|
||||
const value = history.value[historyIndex.value];
|
||||
try {
|
||||
document.value = saveSkinPluginAuthoringDocument(props.skinId, props.skinVersion, value);
|
||||
editRevision.value += 1;
|
||||
if (!document.value.components.some((component) => component.id === selectedComponentId.value)) selectedComponentId.value = document.value.components[0]?.id ?? "";
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
statusMessage.value = english.value ? "Change redone." : "已重做。";
|
||||
resetDraft();
|
||||
emit("updated");
|
||||
} catch (error) { historyIndex.value -= 1; errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function resetAll(): void {
|
||||
try {
|
||||
clearSkinPluginAuthoringDocument(props.skinId, props.skinVersion);
|
||||
storageInvalid.value = false;
|
||||
editRevision.value += 1;
|
||||
document.value = activeBase();
|
||||
selectedComponentId.value = document.value.components[0]?.id ?? "";
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
history.value = [document.value];
|
||||
historyIndex.value = 0;
|
||||
resetDraft();
|
||||
errorMessage.value = "";
|
||||
statusMessage.value = english.value ? "Local edits cleared." : "本地修改已清除。";
|
||||
emit("updated");
|
||||
} catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
function download(source: string, filename: string): void {
|
||||
const url = URL.createObjectURL(new Blob([source], { type: "application/json" }));
|
||||
const anchor = window.document.createElement("a");
|
||||
anchor.href = url;
|
||||
anchor.download = filename;
|
||||
anchor.click();
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 0);
|
||||
}
|
||||
|
||||
function exportDocument(): void {
|
||||
try { download(exportSkinPluginAuthoringDocument(document.value), props.skinId + "-components.json"); }
|
||||
catch (error) { errorMessage.value = message(error); }
|
||||
}
|
||||
|
||||
async function importDocument(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
if (!file) return;
|
||||
try {
|
||||
if (file.size > 256 * 1024) throw new Error("components.json exceeds the 256 KiB limit.");
|
||||
const imported = importSkinPluginAuthoringDocument(await file.text());
|
||||
if (!save(imported)) return;
|
||||
selectedComponentId.value = imported.components[0]?.id ?? "";
|
||||
selectedPath.value = [];
|
||||
editorTarget.value = "component";
|
||||
resetDraft();
|
||||
} catch (error) { errorMessage.value = message(error); statusMessage.value = ""; }
|
||||
}
|
||||
|
||||
watch(() => [props.skinId, props.skinVersion, props.baseDocument] as const, loadDocument, { immediate: true });
|
||||
watch(() => [selectedComponentId.value, selectedPathKey.value, editorTarget.value] as const, resetDraft);
|
||||
watch(open, async (isOpen) => {
|
||||
await nextTick();
|
||||
const target = isOpen ? closeButton.value : triggerButton.value;
|
||||
target?.focus?.();
|
||||
});
|
||||
</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 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; }
|
||||
.skin-plugin-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 10px; }
|
||||
.skin-plugin-heading h2 { margin: 0; font-size: 16px; }
|
||||
.skin-plugin-heading p { margin: 5px 0 0; color: #475569; font-size: 11px; }
|
||||
.skin-plugin-close { width: 44px; height: 44px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 21px !important; cursor: pointer; }
|
||||
.skin-plugin-actions { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.skin-plugin-actions button { min-height: 44px; padding: 0 9px; border: 1px solid #cbd5e1; border-radius: 7px; color: #172033; background: #f8fafc; cursor: pointer; }
|
||||
.skin-plugin-actions button:disabled { opacity: .45; cursor: not-allowed; }
|
||||
.skin-plugin-actions .is-primary { color: #fff; border-color: #4338ca; background: #4f46e5; }
|
||||
.skin-plugin-actions .is-danger { color: #991b1b; border-color: #fecaca; background: #fef2f2; }
|
||||
.skin-plugin-label { display: grid; gap: 5px; color: #475569; font-size: 12px; }
|
||||
.skin-plugin-label select { width: 100%; min-height: 44px; padding: 5px 8px; border: 1px solid #cbd5e1; border-radius: 7px; color: #172033; background: #fff; }
|
||||
.skin-plugin-json-label small { color: #64748b; }
|
||||
.skin-plugin-json-label textarea { width: 100%; min-height: 230px; resize: vertical; padding: 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; font: 12px/1.45 ui-monospace, SFMono-Regular, Consolas, monospace; tab-size: 2; }
|
||||
.skin-plugin-file { display: none; }
|
||||
.skin-plugin-error, .skin-plugin-status, .skin-plugin-context { margin: 0; overflow-wrap: anywhere; }
|
||||
.skin-plugin-error { color: #b91c1c; }
|
||||
.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; } }
|
||||
</style>
|
||||
@@ -230,7 +230,10 @@ export default defineComponent({
|
||||
if (node.widget) {
|
||||
if (node.when) {
|
||||
const value = resolvePath(node.when.path, context, state);
|
||||
if (node.when.equals !== undefined ? value !== node.when.equals : !value) return null;
|
||||
const expected = typeof node.when.equals === "string" ? interpolate(node.when.equals, context, state) : node.when.equals;
|
||||
if (node.when.empty !== undefined) {
|
||||
if (!Array.isArray(value) || (value.length === 0) !== node.when.empty) return null;
|
||||
} else if (expected !== undefined ? value !== expected : !value) return null;
|
||||
}
|
||||
const widget = props.widgets[node.widget];
|
||||
if (!widget) return null;
|
||||
@@ -258,10 +261,16 @@ export default defineComponent({
|
||||
}
|
||||
if (node.when) {
|
||||
const value = resolvePath(node.when.path, context, state);
|
||||
if (node.when.equals !== undefined ? value !== node.when.equals : !value) return null;
|
||||
const expected = typeof node.when.equals === "string" ? interpolate(node.when.equals, context, state) : node.when.equals;
|
||||
if (node.when.empty !== undefined) {
|
||||
if (!Array.isArray(value) || (value.length === 0) !== node.when.empty) return null;
|
||||
} else if (expected !== undefined ? value !== expected : !value) return null;
|
||||
}
|
||||
const attrs: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(node.attributes ?? {})) {
|
||||
// data-ws-* belongs to host layout, page, and recovery machinery. Older
|
||||
// packages remain loadable, but their nodes cannot impersonate host hooks.
|
||||
if (key.startsWith("data-ws-")) continue;
|
||||
attrs[svgAttributeNames[key] ?? key] = typeof value === "string" ? interpolate(value, context, state) : value;
|
||||
}
|
||||
if (node.asset) {
|
||||
|
||||
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createRenderer, createSSRApp, nextTick } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import { parseSkinPluginDocument, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import { approveSkinPluginComponents } from "./skin-plugin-approval.js";
|
||||
import {
|
||||
parseSkinExtensionUiActionRequest,
|
||||
@@ -556,3 +556,33 @@ test("skin-authored DOM nodes expose independent layout parts and retain touch b
|
||||
assert.match(html, /data-ws-part="skin\.voice\.voice-toolbar\.control-part-disconnect"/);
|
||||
assert.match(html, /data-ws-part="skin\.voice\.voice-toolbar\.part-caption"/);
|
||||
});
|
||||
|
||||
test("skin nodes cannot impersonate WebSpeak page and layout hooks", async () => {
|
||||
const document = parseSkinPluginDocument({
|
||||
schemaVersion: 3,
|
||||
components: [{
|
||||
id: "hook-test",
|
||||
name: "Hook test",
|
||||
page: "voice",
|
||||
accessibleName: "Hook test",
|
||||
permissions: [],
|
||||
actions: {},
|
||||
root: {
|
||||
tag: "section",
|
||||
children: [{ tag: "div", attributes: { "data-ws-page": "admin", "data-ws-layout-hidden": true, "data-testid": "safe" } }],
|
||||
},
|
||||
}],
|
||||
});
|
||||
const html = await renderToString(createSSRApp(SkinPluginOutlet, {
|
||||
skinId: "community.test",
|
||||
skinVersion: "1.0.0",
|
||||
document,
|
||||
page: "voice",
|
||||
data: {},
|
||||
assets: {},
|
||||
actions: {},
|
||||
}));
|
||||
assert.match(html, /data-testid="safe"/);
|
||||
assert.doesNotMatch(html, /data-ws-page="admin"/);
|
||||
assert.doesNotMatch(html, /data-ws-layout-hidden=/);
|
||||
});
|
||||
@@ -375,7 +375,11 @@ test("schema version 3 accepts a schema v2 full-page surface with host widgets",
|
||||
});
|
||||
|
||||
test("schema version 4 validates and caches isolated plugin package files without executing them", async () => {
|
||||
const skin = await importSkinPack(makeSkinV4());
|
||||
const defaultLayout = {
|
||||
schemaVersion: 1,
|
||||
pages: { voice: { desktop: { "skin.voice.runtime_plugin_root_voice-toolbar": { order: 2, visible: true } } } },
|
||||
};
|
||||
const skin = await importSkinPack(makeSkinV4(undefined, { layout: defaultLayout }));
|
||||
const entry = "plugins/voice-toolbar/index.js";
|
||||
const style = "plugins/voice-toolbar/style.css";
|
||||
const icon = "plugins/voice-toolbar/assets/icon.png";
|
||||
@@ -389,6 +393,7 @@ test("schema version 4 validates and caches isolated plugin package files withou
|
||||
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /data-ws-runtime-plugin="voice-toolbar".*?\.toolbar/s);
|
||||
assert.match(skin.runtimePluginStyles?.["voice-toolbar"] ?? "", /color: teal/);
|
||||
assert.match(skin.css, /position: fixed/);
|
||||
assert.deepEqual(skin.layoutData?.pages.voice?.desktop?.["skin.voice.runtime_plugin_root_voice-toolbar"], { order: 2, visible: true });
|
||||
|
||||
await assert.rejects(
|
||||
importSkinPack(makeSkinV4(undefined, { includeEntry: false })),
|
||||
@@ -526,6 +531,11 @@ test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspac
|
||||
assert.ok(voiceSurface?.permissions.includes("session.channel.join"));
|
||||
assert.ok(voiceSurface?.permissions.includes("servers.quickList.switch"));
|
||||
assert.ok(voiceSurface?.permissions.includes("session.members.read"));
|
||||
assert.ok(voiceSurface?.permissions.includes("chat.channel.read"));
|
||||
assert.ok(voiceSurface?.permissions.includes("chat.channel.send"));
|
||||
assert.ok(voiceSurface?.permissions.includes("audio.microphone.control"));
|
||||
assert.ok(voiceSurface?.permissions.includes("audio.output.control"));
|
||||
assert.ok(voiceSurface?.permissions.includes("voice.screenShare.control"));
|
||||
function findPart(node: SkinPluginNode | undefined, part: string): SkinPluginNode | undefined {
|
||||
if (!node) return undefined;
|
||||
if (node.part === part) return node;
|
||||
@@ -536,11 +546,34 @@ test("the Harbor voice skin imports a complete voice-only KOOK-inspired workspac
|
||||
return undefined;
|
||||
}
|
||||
const channelRow = findPart(voiceSurface?.root, "channel-row");
|
||||
assert.equal(channelRow?.events?.click, "select-channel", "single-click only selects a channel in this skin");
|
||||
assert.equal(channelRow?.events?.dblclick, "join-channel", "channel switching follows TeamSpeak's double-click join behavior");
|
||||
assert.equal(channelRow?.attributes?.["data-depth"], "{{channel.depth}}", "the channel hierarchy is represented without a new host API");
|
||||
assert.equal(findPart(channelRow, "selected-channel-indicator")?.when?.equals, "{{channel.id}}");
|
||||
const identityEntry = findPart(voiceSurface?.root, "identity-entry");
|
||||
assert.equal(identityEntry?.attributes?.role, "group");
|
||||
assert.equal(identityEntry?.when?.path, "session.status.userName");
|
||||
assert.equal(findPart(identityEntry, "identity-name")?.children?.[0]?.text, "{{session.status.userName}}");
|
||||
const channelVoiceMembers = findPart(voiceSurface?.root, "channel-voice-members");
|
||||
assert.equal(channelVoiceMembers?.when?.path, "channel.current");
|
||||
assert.equal(findPart(channelVoiceMembers, "channel-voice-member")?.repeat?.path, "channel.members");
|
||||
assert.equal(findPart(channelVoiceMembers, "channel-member-muted")?.when?.path, "voicemember.status");
|
||||
assert.equal(findPart(voiceSurface?.root, "member-away-state")?.when?.path, "member.status");
|
||||
const voiceDockActions = findPart(voiceSurface?.root, "voice-dock-actions");
|
||||
assert.equal(findPart(voiceDockActions, "screen-share-start")?.widget, "voice.screen-share-start");
|
||||
assert.equal(findPart(voiceDockActions, "audio-controls")?.widget, "voice.audio-controls");
|
||||
assert.equal(findPart(voiceDockActions, "disconnect-control")?.events?.click, "disconnect");
|
||||
const chat = findPart(voiceSurface?.root, "chat");
|
||||
assert.equal(findPart(chat, "chat-message")?.repeat?.path, "chat.messages");
|
||||
assert.equal(findPart(chat, "chat-composer")?.events?.submit, "send-message");
|
||||
assert.equal(findPart(chat, "chat-input")?.bindValue, "message");
|
||||
assert.equal(findPart(chat, "chat-empty")?.when?.empty, true);
|
||||
assert.equal(findPart(voiceSurface?.root, "whisper-start")?.events?.click, "whisper-on");
|
||||
assert.ok(skin.css.includes("@media (max-width: 820px)"));
|
||||
assert.ok(skin.css.includes('[data-ws-plugin-part="harbor-workspace.channel-row"][data-depth="1"]'));
|
||||
assert.ok(skin.css.includes('[data-ws-plugin-part="harbor-workspace.identity-entry"]'));
|
||||
assert.ok(skin.css.includes('data-ws-plugin-part="harbor-workspace.screen-share-start"'), "the host screen-share control uses the stable plugin part hook");
|
||||
assert.ok(skin.css.includes(".accompaniment-toggle { display: none; }"));
|
||||
assert.ok(!skin.css.includes("https://"), "the skin uses no remote artwork or font resources");
|
||||
});
|
||||
|
||||
@@ -588,12 +621,13 @@ function makeSkinV4(
|
||||
permissions: ["session.channels.read"],
|
||||
}],
|
||||
},
|
||||
options: { includeEntry?: boolean; entryBytes?: Uint8Array; entryPath?: string; extra?: Record<string, Uint8Array> } = {},
|
||||
options: { includeEntry?: boolean; entryBytes?: Uint8Array; entryPath?: string; layout?: unknown; extra?: Record<string, Uint8Array> } = {},
|
||||
): File {
|
||||
const packageFiles: Record<string, Uint8Array> = {
|
||||
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", plugins: "plugins.json" })),
|
||||
"manifest.json": strToU8(JSON.stringify({ ...manifest, schemaVersion: 4, packageType: "open-skin", plugins: "plugins.json", ...(options.layout ? { layout: "layout.json" } : {}) })),
|
||||
"skin.css": strToU8('[data-ws-part="app"] { position: fixed; color: teal; }'),
|
||||
"plugins.json": strToU8(JSON.stringify(pluginDocument)),
|
||||
...(options.layout ? { "layout.json": strToU8(JSON.stringify(options.layout)) } : {}),
|
||||
"plugins/voice-toolbar/style.css": strToU8(".toolbar { color: teal; }"),
|
||||
"plugins/voice-toolbar/assets/icon.png": new Uint8Array([1, 2, 3, 4]),
|
||||
...options.extra,
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
addSkinPluginComponent,
|
||||
addSkinPluginNode,
|
||||
addSkinPluginNodeSibling,
|
||||
duplicateSkinPluginNode,
|
||||
editableSkinPluginDocument,
|
||||
getSkinPluginNode,
|
||||
moveSkinPluginComponent,
|
||||
moveSkinPluginNode,
|
||||
removeSkinPluginComponent,
|
||||
removeSkinPluginNode,
|
||||
replaceSkinPluginNode,
|
||||
} from "../../../src/shared/skin-plugin-editor.js";
|
||||
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import {
|
||||
clearSkinPluginAuthoringDocument,
|
||||
exportSkinPluginAuthoringDocument,
|
||||
getSkinPluginAuthoringStorageKey,
|
||||
hasSkinPluginAuthoringDocument,
|
||||
importSkinPluginAuthoringDocument,
|
||||
loadSkinPluginAuthoringDocument,
|
||||
saveSkinPluginAuthoringDocument,
|
||||
SKIN_PLUGIN_AUTHORING_STORAGE_KEY,
|
||||
} from "./skin-plugin-authoring.js";
|
||||
|
||||
class MemoryStorage {
|
||||
private readonly values = new Map<string, string>();
|
||||
failWrites = false;
|
||||
getItem(key: string): string | null { return this.values.get(key) ?? null; }
|
||||
setItem(key: string, value: string): void {
|
||||
if (this.failWrites) throw new Error("quota exceeded");
|
||||
this.values.set(key, value);
|
||||
}
|
||||
removeItem(key: string): void { this.values.delete(key); }
|
||||
}
|
||||
|
||||
function withLocalStorage<T>(run: (storage: MemoryStorage) => T): T {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
|
||||
const storage = new MemoryStorage();
|
||||
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: storage });
|
||||
try { return run(storage); }
|
||||
finally {
|
||||
if (previous) Object.defineProperty(globalThis, "localStorage", previous);
|
||||
else Reflect.deleteProperty(globalThis, "localStorage");
|
||||
}
|
||||
}
|
||||
|
||||
function document(): SkinPluginDocument {
|
||||
return {
|
||||
schemaVersion: 3,
|
||||
components: [{
|
||||
id: "voice-panel",
|
||||
name: "Voice panel",
|
||||
page: "voice",
|
||||
accessibleName: "Voice panel",
|
||||
permissions: [],
|
||||
actions: {},
|
||||
root: { tag: "section", children: [{ tag: "p", children: [{ text: "Original" }] }, { tag: "button", attributes: { type: "button" } }] },
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
test("component document editor supports add, update, reorder, delete, and an empty v3 document", () => {
|
||||
const source = document();
|
||||
const first = addSkinPluginNode(source, "voice-panel", [], { tag: "div", children: [{ text: "Added" }] });
|
||||
assert.equal(getSkinPluginNode(first, "voice-panel", [2]).tag, "div");
|
||||
assert.equal(source.components[0].root.children?.length, 2, "editing leaves the source tree unchanged");
|
||||
|
||||
const second = addSkinPluginNodeSibling(first, "voice-panel", [2], { tag: "small", children: [{ text: "Sibling" }] });
|
||||
assert.equal(getSkinPluginNode(second, "voice-panel", [3]).tag, "small");
|
||||
const reordered = moveSkinPluginNode(second, "voice-panel", [3], -1);
|
||||
assert.equal(getSkinPluginNode(reordered, "voice-panel", [2]).tag, "small");
|
||||
|
||||
const updated = replaceSkinPluginNode(reordered, "voice-panel", [2, 0], { text: "Changed" });
|
||||
assert.equal(getSkinPluginNode(updated, "voice-panel", [2, 0]).text, "Changed");
|
||||
const withoutNode = removeSkinPluginNode(updated, "voice-panel", [2]);
|
||||
assert.equal(withoutNode.components[0].root.children?.length, 3);
|
||||
const withSecondComponent = addSkinPluginComponent(withoutNode, {
|
||||
id: "extra-panel", name: "Extra panel", page: "voice", accessibleName: "Extra panel",
|
||||
permissions: [], actions: {}, root: { tag: "aside" },
|
||||
});
|
||||
assert.equal(withSecondComponent.components.length, 2);
|
||||
assert.equal(removeSkinPluginComponent(withSecondComponent, "voice-panel").components.length, 1);
|
||||
assert.deepEqual(removeSkinPluginComponent(withSecondComponent, "voice-panel").components.map(({ id }) => id), ["extra-panel"]);
|
||||
assert.deepEqual(removeSkinPluginComponent(document(), "voice-panel"), { schemaVersion: 3, components: [] });
|
||||
});
|
||||
|
||||
test("component order is editable and stays within the selected skin document", () => {
|
||||
const source = addSkinPluginComponent(document(), {
|
||||
id: "second-panel", name: "Second panel", page: "voice", accessibleName: "Second panel",
|
||||
permissions: [], actions: {}, root: { tag: "aside" },
|
||||
});
|
||||
const moved = moveSkinPluginComponent(source, "voice-panel", 1);
|
||||
assert.deepEqual(moved.components.map((component) => component.id), ["second-panel", "voice-panel"]);
|
||||
assert.deepEqual(moveSkinPluginComponent(moved, "voice-panel", 1), moved, "moving past the end is a no-op");
|
||||
assert.deepEqual(source.components.map((component) => component.id), ["voice-panel", "second-panel"]);
|
||||
});
|
||||
|
||||
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" }],
|
||||
};
|
||||
const copy = duplicateSkinPluginNode(source, "voice-panel", [0]);
|
||||
assert.equal(copy.part, "message-copy");
|
||||
assert.equal(copy.children?.[0].part, "author-copy");
|
||||
assert.throws(() => duplicateSkinPluginNode(source, "voice-panel", []), /root cannot be duplicated/i);
|
||||
});
|
||||
|
||||
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], {
|
||||
tag: "button", events: { click: "disconnect" },
|
||||
}), /refer to a declared host action/i);
|
||||
assert.throws(() => addSkinPluginComponent(document(), {
|
||||
id: "unsafe", name: "Unsafe", page: "voice", accessibleName: "Unsafe",
|
||||
permissions: [], actions: { disconnect: { type: "voice.disconnect", args: {} } },
|
||||
root: { tag: "button", events: { click: "disconnect" } },
|
||||
}), /requires voice.disconnect/i);
|
||||
assert.throws(() => removeSkinPluginNode(document(), "voice-panel", []), /root cannot be removed/i);
|
||||
assert.throws(() => moveSkinPluginNode(document(), "voice-panel", [1.5], -1), /no longer exists/i);
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
const legacyWithWidget = structuredClone(legacy);
|
||||
legacyWithWidget.components[0].permissions = [];
|
||||
legacyWithWidget.components[0].root = { tag: "section", children: [{ widget: "voice.audio-controls" }] };
|
||||
const migratedWidget = editableSkinPluginDocument(legacyWithWidget);
|
||||
assert.deepEqual(migratedWidget.components[0].permissions, ["audio.status.read", "audio.microphone.control", "audio.output.control"]);
|
||||
});
|
||||
|
||||
test("component authoring saves are isolated by skin version and round-trip through export/import", () => {
|
||||
withLocalStorage((storage) => {
|
||||
const source = addSkinPluginNode(document(), "voice-panel", [], { tag: "strong", children: [{ text: "Local edit" }] });
|
||||
saveSkinPluginAuthoringDocument("community.example", "1.2.3", source);
|
||||
assert.notEqual(storage.getItem(getSkinPluginAuthoringStorageKey("community.example", "1.2.3")), null);
|
||||
assert.equal(storage.getItem(SKIN_PLUGIN_AUTHORING_STORAGE_KEY), null);
|
||||
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.2.3"), true);
|
||||
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.3")?.components[0].root.children?.length, 3);
|
||||
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.4"), null);
|
||||
const exported = exportSkinPluginAuthoringDocument(source);
|
||||
assert.deepEqual(importSkinPluginAuthoringDocument(exported), source);
|
||||
clearSkinPluginAuthoringDocument("community.example", "1.2.3");
|
||||
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), null);
|
||||
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.2.3"), false);
|
||||
const empty = removeSkinPluginComponent(source, "voice-panel");
|
||||
saveSkinPluginAuthoringDocument("community.example", "1.2.3", empty);
|
||||
assert.deepEqual(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), { schemaVersion: 3, components: [] });
|
||||
assert.deepEqual(importSkinPluginAuthoringDocument(exportSkinPluginAuthoringDocument(empty)), empty);
|
||||
|
||||
const legacy = { ...document(), schemaVersion: 2 } as unknown as SkinPluginDocument;
|
||||
saveSkinPluginAuthoringDocument("community.example", "1.2.4", legacy);
|
||||
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.2.4")?.schemaVersion, 3);
|
||||
});
|
||||
});
|
||||
|
||||
test("invalid component files and unsafe local edits are rejected before persistence", () => {
|
||||
withLocalStorage((storage) => {
|
||||
assert.throws(() => importSkinPluginAuthoringDocument(JSON.stringify({
|
||||
schemaVersion: 3,
|
||||
components: [{
|
||||
id: "broken", name: "Broken", page: "voice", accessibleName: "Broken",
|
||||
permissions: [], actions: {}, root: { tag: "iframe" },
|
||||
}],
|
||||
})));
|
||||
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1", {
|
||||
schemaVersion: 3, components: [{ ...document().components[0], root: { tag: "script" } }],
|
||||
}));
|
||||
const reservedHook = document();
|
||||
reservedHook.components[0].root.children![0].attributes = { "data-ws-page": "admin" };
|
||||
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1", reservedHook), /owned by WebSpeak/i);
|
||||
assert.equal(storage.getItem(getSkinPluginAuthoringStorageKey("community.example", "1")), null);
|
||||
});
|
||||
});
|
||||
|
||||
test("a local-storage write failure preserves the last saved component document", () => {
|
||||
withLocalStorage((storage) => {
|
||||
const saved = document();
|
||||
saveSkinPluginAuthoringDocument("community.example", "1.2.3", saved);
|
||||
const key = getSkinPluginAuthoringStorageKey("community.example", "1.2.3");
|
||||
const rawBeforeFailure = storage.getItem(key);
|
||||
const changed = addSkinPluginNode(saved, "voice-panel", [], { text: "not committed" });
|
||||
storage.failWrites = true;
|
||||
assert.throws(() => saveSkinPluginAuthoringDocument("community.example", "1.2.3", changed), /could not save/i);
|
||||
assert.equal(storage.getItem(key), rawBeforeFailure);
|
||||
assert.deepEqual(loadSkinPluginAuthoringDocument("community.example", "1.2.3"), editableSkinPluginDocument(saved));
|
||||
});
|
||||
});
|
||||
|
||||
test("corrupt authoring data stays isolated and can be cleared without touching another skin", () => {
|
||||
withLocalStorage((storage) => {
|
||||
const corruptKey = getSkinPluginAuthoringStorageKey("community.example", "1.0.0");
|
||||
saveSkinPluginAuthoringDocument("community.other", "1.0.0", document());
|
||||
storage.setItem(corruptKey, "not json");
|
||||
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.0.0"), true);
|
||||
assert.equal(loadSkinPluginAuthoringDocument("community.example", "1.0.0"), null);
|
||||
clearSkinPluginAuthoringDocument("community.example", "1.0.0");
|
||||
assert.equal(hasSkinPluginAuthoringDocument("community.example", "1.0.0"), false);
|
||||
assert.equal(loadSkinPluginAuthoringDocument("community.other", "1.0.0")?.components[0].id, "voice-panel");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import { parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import { assertSkinPluginAuthoringDocument, editableSkinPluginDocument } from "../../../src/shared/skin-plugin-editor.js";
|
||||
|
||||
export const SKIN_PLUGIN_AUTHORING_STORAGE_KEY = "webspeak:skin-plugin-authoring:v1";
|
||||
const MAX_DOCUMENT_BYTES = 256 * 1024;
|
||||
|
||||
interface StorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
removeItem(key: string): void;
|
||||
}
|
||||
|
||||
function browserStorage(): StorageLike | null {
|
||||
try { return typeof localStorage === "undefined" ? null : localStorage; }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
export function getSkinPluginAuthoringStorageKey(skinId: string, skinVersion: string): string {
|
||||
if (!/^[a-z0-9](?:[a-z0-9.-]{0,78}[a-z0-9])?$/.test(skinId)
|
||||
|| !skinVersion || skinVersion.length > 32 || !/^[A-Za-z0-9.+_-]+$/.test(skinVersion)) {
|
||||
throw new Error("Skin identity is invalid.");
|
||||
}
|
||||
return SKIN_PLUGIN_AUTHORING_STORAGE_KEY + ":" + skinId + "@" + skinVersion;
|
||||
}
|
||||
|
||||
export function hasSkinPluginAuthoringDocument(skinId: string, skinVersion: string): boolean {
|
||||
let key: string;
|
||||
try { key = getSkinPluginAuthoringStorageKey(skinId, skinVersion); } catch { return false; }
|
||||
const storage = browserStorage();
|
||||
if (!storage) return false;
|
||||
try { return storage.getItem(key) !== null; } catch { return false; }
|
||||
}
|
||||
|
||||
export function loadSkinPluginAuthoringDocument(skinId: string, skinVersion: string): SkinPluginDocument | null {
|
||||
let key: string;
|
||||
try { key = getSkinPluginAuthoringStorageKey(skinId, skinVersion); } catch { return null; }
|
||||
const storage = browserStorage();
|
||||
if (!storage) return null;
|
||||
let source: string | null;
|
||||
try { source = storage.getItem(key); } catch { return null; }
|
||||
if (!source) return null;
|
||||
if (new TextEncoder().encode(source).byteLength > MAX_DOCUMENT_BYTES) return null;
|
||||
try { return editableSkinPluginDocument(parseSkinPluginJson(source)); }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
export function saveSkinPluginAuthoringDocument(skinId: string, skinVersion: string, document: unknown): SkinPluginDocument {
|
||||
const key = getSkinPluginAuthoringStorageKey(skinId, skinVersion);
|
||||
const validated = assertSkinPluginAuthoringDocument(document);
|
||||
const serialized = JSON.stringify(validated);
|
||||
if (new TextEncoder().encode(serialized).byteLength > MAX_DOCUMENT_BYTES) throw new Error("Saved component edits exceed the 256 KiB document limit.");
|
||||
const storage = browserStorage();
|
||||
if (!storage) throw new Error("Local browser storage is unavailable.");
|
||||
try { storage.setItem(key, serialized); }
|
||||
catch { throw new Error("Local browser storage could not save the component edits."); }
|
||||
return validated;
|
||||
}
|
||||
|
||||
export function clearSkinPluginAuthoringDocument(skinId: string, skinVersion: string): void {
|
||||
const key = getSkinPluginAuthoringStorageKey(skinId, skinVersion);
|
||||
const storage = browserStorage();
|
||||
if (!storage) throw new Error("Local browser storage is unavailable.");
|
||||
try { storage.removeItem(key); }
|
||||
catch { throw new Error("Local browser storage could not clear the component edits."); }
|
||||
}
|
||||
|
||||
export function importSkinPluginAuthoringDocument(source: string): SkinPluginDocument {
|
||||
return assertSkinPluginAuthoringDocument(parseSkinPluginJson(source));
|
||||
}
|
||||
|
||||
export function exportSkinPluginAuthoringDocument(document: unknown): string {
|
||||
const validated = assertSkinPluginAuthoringDocument(document);
|
||||
const readable = JSON.stringify(validated, null, 2);
|
||||
if (new TextEncoder().encode(readable).byteLength <= MAX_DOCUMENT_BYTES) return readable;
|
||||
const compact = JSON.stringify(validated);
|
||||
if (new TextEncoder().encode(compact).byteLength > MAX_DOCUMENT_BYTES) throw new Error("components.json exceeds the 256 KiB document limit.");
|
||||
return compact;
|
||||
}
|
||||
@@ -12,10 +12,10 @@
|
||||
:data-ws-page="showVoiceShell ? 'voice' : 'home'"
|
||||
>
|
||||
<SkinPluginOutlet
|
||||
v-if="activeSkin?.pluginData"
|
||||
v-if="activeSkin"
|
||||
:skin-id="activeSkin.id"
|
||||
:skin-version="activeSkin.version"
|
||||
:document="activeSkin.pluginData"
|
||||
:document="skinPluginDocument"
|
||||
:page="showVoiceShell ? 'voice' : 'home'"
|
||||
:data="skinPluginContext"
|
||||
:assets="activeSkin.assets"
|
||||
@@ -24,6 +24,15 @@
|
||||
@surface-change="skinPluginSurfaceActive = $event"
|
||||
@restore-skin="switchToBuiltIn"
|
||||
/>
|
||||
<SkinPluginEditor
|
||||
v-if="activeSkin"
|
||||
:skin-id="activeSkin.id"
|
||||
:skin-version="activeSkin.version"
|
||||
:base-document="activeSkin.pluginData"
|
||||
:page="showVoiceShell ? 'voice' : 'home'"
|
||||
:lang="language"
|
||||
@updated="skinPluginDocumentRevision += 1"
|
||||
/>
|
||||
<SkinRuntimePluginHost
|
||||
v-if="activeSkin?.runtimePlugins"
|
||||
:skin-id="activeSkin.id"
|
||||
@@ -966,6 +975,7 @@ import { observeMobileViewport } from "../services/mobile-viewport.js";
|
||||
import { computed, h, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from "vue";
|
||||
import Icon from "../components/Icon.vue";
|
||||
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
|
||||
import SkinPluginEditor from "../components/SkinPluginEditor.vue";
|
||||
import SkinRuntimePluginHost from "../components/SkinRuntimePluginHost.js";
|
||||
import SkinLoadRecoveryNotice from "../components/SkinLoadRecoveryNotice.vue";
|
||||
import VoiceMemberCards from "../components/web-client/VoiceMemberCards.vue";
|
||||
@@ -1009,6 +1019,8 @@ import { applyTheme, getStoredTheme, type ThemeMode } from "../services/theme.js
|
||||
import { createScreenWakeLockController, getScreenWakeLockApi, type ScreenWakeLockController, type ScreenWakeLockSnapshot } from "../services/screen-wake-lock.js";
|
||||
import { createMobileAwayController, type MobileAwayController } from "../services/mobile-away.js";
|
||||
import { createSkinPluginQuickServerProjection } from "../services/skin-plugin-context.js";
|
||||
import { loadSkinPluginAuthoringDocument } from "../services/skin-plugin-authoring.js";
|
||||
import type { SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
|
||||
import { combineTeamSpeakTarget, DEFAULT_TEAM_SPEAK_PORT, isValidTeamSpeakPort, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
|
||||
|
||||
const {
|
||||
@@ -1133,6 +1145,14 @@ let toastTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
const language = ref<Language>(getInitialLanguage());
|
||||
const activeSkin = shallowRef<InstalledSkin | null>(null);
|
||||
const skinPluginDocumentRevision = ref(0);
|
||||
const emptySkinPluginDocument: SkinPluginDocument = { schemaVersion: 3, components: [] };
|
||||
const skinPluginDocument = computed<SkinPluginDocument>(() => {
|
||||
skinPluginDocumentRevision.value;
|
||||
const skin = activeSkin.value;
|
||||
if (!skin) return emptySkinPluginDocument;
|
||||
return loadSkinPluginAuthoringDocument(skin.id, skin.version) ?? skin.pluginData ?? emptySkinPluginDocument;
|
||||
});
|
||||
const skinPluginSurfaceActive = ref(false);
|
||||
const skinRuntimePluginSurfaceActive = ref(false);
|
||||
watch(activeSkin, () => {
|
||||
@@ -1614,8 +1634,11 @@ const skinPluginActions = {
|
||||
"voice.toggleMicrophone": () => { if (voiceState.connected) toggleMicrophone(); },
|
||||
"voice.toggleOutputMute": () => { if (voiceState.connected) toggleOutputMute(); },
|
||||
"voice.setOutputVolume": (args: Record<string, string | number | boolean>) => {
|
||||
if (!voiceState.connected || typeof args.volume !== "number" || !Number.isFinite(args.volume)) return;
|
||||
setOutputVolume(Math.max(0, Math.min(1, args.volume)));
|
||||
if (!voiceState.connected) return;
|
||||
const volume = typeof args.volume === "number" ? args.volume
|
||||
: typeof args.volume === "string" && args.volume.trim() ? Number(args.volume) : Number.NaN;
|
||||
if (!Number.isFinite(volume)) return;
|
||||
setOutputVolume(Math.max(0, Math.min(1, volume)));
|
||||
},
|
||||
"voice.disconnect": () => { if (voiceState.connected || voiceState.connecting) doDisconnect(); },
|
||||
"voice.setAway": (args: Record<string, string | number | boolean>) => {
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { after, before, test } from "node:test";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import * as Vue from "vue";
|
||||
import { createRenderer, nextTick, ssrContextKey, createSSRApp } from "vue";
|
||||
import { renderToString } from "@vue/server-renderer";
|
||||
import { createServer } from "vite";
|
||||
import vuePlugin from "@vitejs/plugin-vue";
|
||||
|
||||
let vite;
|
||||
let SkinPluginEditor;
|
||||
let authoring;
|
||||
const localStorageDescriptor = Object.getOwnPropertyDescriptor(globalThis, "localStorage");
|
||||
|
||||
class MemoryStorage {
|
||||
values = new Map();
|
||||
getItem(key) { return this.values.get(key) ?? null; }
|
||||
setItem(key, value) { this.values.set(key, value); }
|
||||
removeItem(key) { this.values.delete(key); }
|
||||
}
|
||||
|
||||
const hostNode = (tag, type = "element") => ({
|
||||
tag, type, props: {}, text: "", children: [], parent: null, value: "", listeners: new Map(), focus() {},
|
||||
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); },
|
||||
});
|
||||
function insert(child, parent, anchor = null) {
|
||||
if (child.parent) {
|
||||
const previous = child.parent.children.indexOf(child);
|
||||
if (previous >= 0) child.parent.children.splice(previous, 1);
|
||||
}
|
||||
const index = anchor ? parent.children.indexOf(anchor) : -1;
|
||||
child.parent = parent;
|
||||
if (index < 0) parent.children.push(child);
|
||||
else parent.children.splice(index, 0, child);
|
||||
}
|
||||
|
||||
const renderer = createRenderer({
|
||||
createElement: tag => hostNode(tag),
|
||||
createText: text => Object.assign(hostNode("#text", "text"), { text }),
|
||||
createComment: text => Object.assign(hostNode("#comment", "comment"), { text }),
|
||||
setText(node, text) { node.text = text; },
|
||||
setElementText(node, text) { node.children.forEach(child => { child.parent = null; }); node.children = []; node.text = text; },
|
||||
patchProp(node, key, _previous, value) { node.props[key] = value; },
|
||||
insert,
|
||||
remove(node) {
|
||||
if (!node.parent) return;
|
||||
const index = node.parent.children.indexOf(node);
|
||||
if (index >= 0) node.parent.children.splice(index, 1);
|
||||
node.parent = null;
|
||||
},
|
||||
parentNode: node => node.parent,
|
||||
nextSibling(node) {
|
||||
if (!node.parent) return null;
|
||||
return node.parent.children[node.parent.children.indexOf(node) + 1] ?? null;
|
||||
},
|
||||
insertStaticContent(content, parent, anchor) {
|
||||
const node = Object.assign(hostNode("#static", "static"), { text: content });
|
||||
insert(node, parent, anchor);
|
||||
return [node, node];
|
||||
},
|
||||
});
|
||||
const testVueRuntime = {
|
||||
...Vue,
|
||||
vModelText: {
|
||||
created(element, binding, vnode) {
|
||||
element.value = binding.value ?? "";
|
||||
const assign = vnode.props?.["onUpdate:modelValue"];
|
||||
if (assign) element.addEventListener("input", event => assign(event.target.value));
|
||||
},
|
||||
beforeUpdate(element, binding) { element.value = binding.value ?? ""; },
|
||||
},
|
||||
};
|
||||
|
||||
function visit(root, predicate) {
|
||||
if (predicate(root)) return root;
|
||||
for (const child of root.children) {
|
||||
const found = visit(child, predicate);
|
||||
if (found) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function nodeText(node) {
|
||||
return node.text + node.children.map(nodeText).join("");
|
||||
}
|
||||
|
||||
function clickButton(root, label) {
|
||||
const button = visit(root, node => node.tag === "button"
|
||||
&& (node.props["aria-label"] === label || nodeText(node).trim() === label));
|
||||
assert.ok(button, `button ${label} exists in the rendered editor; rendered text: ${nodeText(root)}`);
|
||||
assert.equal(typeof button.props.onClick, "function", `button ${label} has a click handler`);
|
||||
button.props.onClick({ type: "click", target: button });
|
||||
}
|
||||
|
||||
function changeSelect(root, index, value) {
|
||||
const selects = [];
|
||||
const collect = node => {
|
||||
if (node.tag === "select") selects.push(node);
|
||||
node.children.forEach(collect);
|
||||
};
|
||||
collect(root);
|
||||
const select = selects[index];
|
||||
assert.ok(select, `select ${index} exists in the rendered editor`);
|
||||
assert.equal(typeof select.props.onChange, "function");
|
||||
select.props.onChange({ type: "change", target: { value } });
|
||||
}
|
||||
|
||||
function editTextarea(root, value) {
|
||||
const textarea = visit(root, node => node.tag === "textarea");
|
||||
assert.ok(textarea, "JSON editor is rendered");
|
||||
textarea.value = value;
|
||||
textarea.dispatchEvent({ type: "input", target: textarea });
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
vite = await createServer({
|
||||
configFile: false,
|
||||
root: fileURLToPath(new URL("../", import.meta.url)),
|
||||
plugins: [vuePlugin()],
|
||||
server: { middlewareMode: true, hmr: false, ws: false, watch: null },
|
||||
optimizeDeps: { noDiscovery: true, include: [] },
|
||||
appType: "custom",
|
||||
});
|
||||
({ default: SkinPluginEditor } = await vite.ssrLoadModule("/src/components/SkinPluginEditor.vue"));
|
||||
const require = createRequire(import.meta.url);
|
||||
const { parse, compileScript, compileTemplate } = require("../node_modules/@vue/compiler-sfc");
|
||||
const filename = fileURLToPath(new URL("../src/components/SkinPluginEditor.vue", import.meta.url));
|
||||
const source = readFileSync(filename, "utf8");
|
||||
const { descriptor } = parse(source, { filename });
|
||||
const script = compileScript(descriptor, { id: "skin-plugin-editor-test" });
|
||||
const templateSource = descriptor.template.content.replaceAll("($event.target as HTMLSelectElement).value", "($event.target).value");
|
||||
const template = compileTemplate({ source: templateSource, filename, id: "skin-plugin-editor-test", compilerOptions: { expressionPlugins: ["typescript"], bindingMetadata: script.bindings } });
|
||||
assert.deepEqual(template.errors, [], "the editor template compiles for client rendering");
|
||||
const vueImport = /^import \{([\s\S]*?)\} from "vue"\s*/.exec(template.code);
|
||||
assert.ok(vueImport, "compiled template imports Vue runtime helpers");
|
||||
const vueBindings = vueImport[1].split(",").map(binding => binding.trim().replace(" as ", ": ")).join(", ");
|
||||
const clientRenderCode = `const { ${vueBindings} } = Vue;\n${template.code.slice(vueImport[0].length).replace("export function render", "return function render")}`;
|
||||
SkinPluginEditor.render = new Function("Vue", clientRenderCode)(testVueRuntime);
|
||||
authoring = await vite.ssrLoadModule("/src/services/skin-plugin-authoring.ts");
|
||||
});
|
||||
|
||||
after(async () => {
|
||||
await vite?.close();
|
||||
if (localStorageDescriptor) Object.defineProperty(globalThis, "localStorage", localStorageDescriptor);
|
||||
else Reflect.deleteProperty(globalThis, "localStorage");
|
||||
});
|
||||
|
||||
test("component editor creates, changes, and deletes a skin component tree through its UI", async () => {
|
||||
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: new MemoryStorage() });
|
||||
const baseDocument = {
|
||||
schemaVersion: 3,
|
||||
components: [{
|
||||
id: "base-panel",
|
||||
name: "Base panel",
|
||||
page: "voice",
|
||||
accessibleName: "Base panel",
|
||||
permissions: [],
|
||||
actions: {},
|
||||
root: { tag: "section", children: [{ text: "Base" }] },
|
||||
}],
|
||||
};
|
||||
const props = {
|
||||
skinId: "community.example",
|
||||
skinVersion: "1.0.0",
|
||||
baseDocument,
|
||||
page: "voice",
|
||||
lang: "zh",
|
||||
};
|
||||
const html = await renderToString(createSSRApp(SkinPluginEditor, props));
|
||||
assert.match(html, /组件结构/);
|
||||
|
||||
const root = hostNode("root");
|
||||
const app = renderer.createApp(SkinPluginEditor, props);
|
||||
app.provide(ssrContextKey, { modules: new Set() });
|
||||
app.mount(root);
|
||||
|
||||
try {
|
||||
clickButton(root, "组件结构");
|
||||
await nextTick();
|
||||
assert.equal(app._instance.setupState.open, true, "the trigger opens the editor");
|
||||
clickButton(root, "新增组件");
|
||||
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, "组件上移");
|
||||
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, "添加子节点");
|
||||
await nextTick();
|
||||
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
|
||||
assert.equal(edited.components[0].root.children.length, 2);
|
||||
assert.ok(localStorage.getItem(key));
|
||||
|
||||
changeSelect(root, 1, "0");
|
||||
await nextTick();
|
||||
editTextarea(root, JSON.stringify({ text: "Edited in the component editor" }, null, 2));
|
||||
await nextTick();
|
||||
clickButton(root, "应用定义");
|
||||
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, "撤销");
|
||||
await nextTick();
|
||||
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
|
||||
assert.equal(edited.components[0].root.children[0].text, "新建组件");
|
||||
clickButton(root, "重做");
|
||||
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, "删除组件");
|
||||
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");
|
||||
await nextTick();
|
||||
clickButton(root, "复制组件");
|
||||
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");
|
||||
await nextTick();
|
||||
changeSelect(root, 1, "0");
|
||||
await nextTick();
|
||||
clickButton(root, "删除组件");
|
||||
await nextTick();
|
||||
edited = authoring.loadSkinPluginAuthoringDocument("community.example", "1.0.0");
|
||||
assert.deepEqual(edited.components.map(component => component.id), ["base-panel-2"]);
|
||||
|
||||
clickButton(root, "新增组件");
|
||||
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"/);
|
||||
|
||||
changeSelect(root, 1, "0");
|
||||
await nextTick();
|
||||
const importInput = visit(root, node => node.tag === "input");
|
||||
assert.ok(importInput);
|
||||
const importedDocument = {
|
||||
schemaVersion: 3,
|
||||
components: [{
|
||||
id: "imported-panel", name: "Imported panel", page: "voice", accessibleName: "Imported panel",
|
||||
permissions: [], actions: {}, root: { tag: "section", children: [{ text: "Imported" }] },
|
||||
}],
|
||||
};
|
||||
await importInput.props.onChange({ target: { files: [new File([JSON.stringify(importedDocument)], "components.json")], value: "components.json" } });
|
||||
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"/,
|
||||
"importing from node mode selects the imported component definition");
|
||||
|
||||
const panel = visit(root, 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();
|
||||
assert.equal(visit(root, node => node.tag === "section" && node.props.role === "dialog"), null,
|
||||
"Escape closes the editor dialog");
|
||||
} finally {
|
||||
app.unmount();
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user