mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix(skin-editor): hide dev controls from visitors
This commit is contained in:
1 parent
8cde1eae5a
commit
16df12e4b2
12 files changed
+1652
-2253
No files matched your search
@@ -1,267 +1,326 @@
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div v-if="editor.available.value" ref="editorRoot" class="skin-layout-editor" data-ws-layout-editor @keydown.esc.stop.prevent="editor.setOpen(false)">
|
||||
<button
|
||||
v-if="editorMode.isAdmin.value"
|
||||
class="skin-editor-mode-trigger"
|
||||
type="button"
|
||||
:aria-pressed="editorMode.isEnabled.value"
|
||||
@click="toggleEditorMode"
|
||||
>
|
||||
<span aria-hidden="true">⚙</span>
|
||||
{{ editorMode.isEnabled.value ? "退出编辑器 / Exit editor" : "编辑器模式 / Editor mode" }}
|
||||
</button>
|
||||
<button
|
||||
v-if="editorMode.isEnabled.value"
|
||||
ref="triggerButton"
|
||||
class="skin-layout-trigger"
|
||||
type="button"
|
||||
:aria-expanded="editor.isOpen.value"
|
||||
aria-controls="skin-layout-panel"
|
||||
@click="editor.setOpen(!editor.isOpen.value)"
|
||||
>
|
||||
<span aria-hidden="true">⠿</span>
|
||||
{{ editor.labels.value.editButton }}
|
||||
</button>
|
||||
|
||||
<section
|
||||
v-if="editor.isOpen.value"
|
||||
id="skin-layout-panel"
|
||||
class="skin-layout-panel"
|
||||
role="dialog"
|
||||
aria-modal="false"
|
||||
:aria-label="editor.labels.value.title"
|
||||
>
|
||||
<header class="skin-layout-heading">
|
||||
<div>
|
||||
<h2>{{ editor.labels.value.title }}</h2>
|
||||
<p>{{ editor.labels.value.hint }}</p>
|
||||
</div>
|
||||
<button ref="closeButton" type="button" class="skin-layout-close" :aria-label="editor.labels.value.close" @click="editor.setOpen(false)">×</button>
|
||||
</header>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.isEditing.value" @change="editor.setEditing(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.editMode }}</span>
|
||||
</label>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.focusPreviewEnabled.value" @change="editor.setFocusPreview(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.focusPreview }}</span>
|
||||
</label>
|
||||
<ol v-if="editor.focusPreviewEnabled.value" class="skin-layout-focus-list" :aria-label="editor.labels.value.focusPreview">
|
||||
<li v-if="!editor.focusPreviewTargets.value.length" class="skin-layout-focus-empty">
|
||||
{{ editor.labels.value.focusPreviewEmpty }}
|
||||
</li>
|
||||
<li v-for="target in editor.focusPreviewTargets.value" :key="target.key" :class="{ 'is-small': !target.meetsTouchTarget }">
|
||||
<span class="skin-layout-focus-number" aria-hidden="true">{{ target.order }}</span>
|
||||
<span class="skin-layout-focus-name"><strong>{{ target.componentName }}</strong><small>{{ target.accessibleName || editor.labels.value.focusPreviewUnnamed }}</small></span>
|
||||
<span class="skin-layout-focus-size">{{ editor.labels.value.focusPreviewTargetSize.replace("{width}", String(Math.round(target.width))).replace("{height}", String(Math.round(target.height))) }}<small>{{ target.meetsTouchTarget ? editor.labels.value.focusPreviewTargetAdequate : editor.labels.value.focusPreviewTargetSmall }}</small></span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<label class="skin-layout-field">
|
||||
<span>{{ editor.labels.value.component }}</span>
|
||||
<input v-model="editor.filter.value" type="search" :placeholder="editor.labels.value.filter" />
|
||||
<select :value="editor.selectedComponentId.value" @change="editor.selectComponent(($event.target as HTMLSelectElement).value)">
|
||||
<option v-for="component in editor.filteredComponents.value" :key="component.id" :value="component.id">{{ component.name }} ({{ component.id }})</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.selectedVisible.value" @change="editor.setVisible(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.visible }}</span>
|
||||
</label>
|
||||
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.positionX }}</span><output>{{ Math.round(editor.selectedX.value) }} px</output></label>
|
||||
<input type="range" :min="editor.positionBoundsX.value.minimum" :max="editor.positionBoundsX.value.maximum" step="1" :value="editor.selectedX.value" @input="editor.setX(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.positionY }}</span><output>{{ Math.round(editor.selectedY.value) }} px</output></label>
|
||||
<input type="range" :min="editor.positionBoundsY.value.minimum" :max="editor.positionBoundsY.value.maximum" step="1" :value="editor.selectedY.value" @input="editor.setY(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.size }}</span><output>{{ Math.round(editor.selectedScale.value * 100) }}%</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minScale" :max="editor.selectedSizeBounds.value.maxScale" step="0.05" :value="editor.selectedScale.value" @input="editor.setScale(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.width }}</span><output>{{ Math.round(editor.selectedWidth.value) }} px</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minWidth" :max="editor.selectedSizeBounds.value.maxWidth" step="4" :value="editor.selectedWidth.value" @input="editor.setWidth(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.height }}</span><output>{{ Math.round(editor.selectedHeight.value) }} px</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minHeight" :max="editor.selectedSizeBounds.value.maxHeight" step="4" :value="editor.selectedHeight.value" @input="editor.setHeight(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range" :title="editor.labels.value.orderHint">
|
||||
<label><span>{{ editor.labels.value.order }}</span><output>{{ editor.selectedOrder.value }}</output></label>
|
||||
<input type="range" min="-100" max="100" step="1" :value="editor.selectedOrder.value" @input="editor.setOrder(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-colors">
|
||||
<label><span>{{ editor.labels.value.foreground }}</span><input type="color" :value="editor.selectedForeground.value" @input="editor.setForeground(($event.target as HTMLInputElement).value)" /></label>
|
||||
<label><span>{{ editor.labels.value.background }}</span><input type="color" :value="editor.selectedBackground.value" @input="editor.setBackground(($event.target as HTMLInputElement).value)" /></label>
|
||||
<label><span>{{ editor.labels.value.border }}</span><input type="color" :value="editor.selectedBorder.value" @input="editor.setBorder(($event.target as HTMLInputElement).value)" /></label>
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.radius }}</span><output>{{ Math.round(editor.selectedRadius.value) }} px</output></label>
|
||||
<input type="range" min="0" max="64" step="1" :value="editor.selectedRadius.value" @input="editor.setRadius(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" :disabled="!editor.canUndo.value" @click="editor.undo">{{ editor.labels.value.undo }}</button>
|
||||
<button type="button" :disabled="!editor.canRedo.value" @click="editor.redo">{{ editor.labels.value.redo }}</button>
|
||||
</div>
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" @click="editor.resetComponent">{{ editor.labels.value.resetItem }}</button>
|
||||
<button type="button" @click="editor.resetAll">{{ editor.labels.value.resetAll }}</button>
|
||||
</div>
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" @click="editor.exportCurrent">{{ editor.labels.value.export }}</button>
|
||||
<button type="button" @click="importInput?.click()">{{ editor.labels.value.import }}</button>
|
||||
<input ref="importInput" class="skin-layout-file" type="file" accept="application/json,.json" @change="onImport" />
|
||||
</div>
|
||||
<p v-if="editor.statusMessage.value" class="skin-layout-status" role="status">{{ editor.statusMessage.value }}</p>
|
||||
<div v-if="editor.layoutWarnings.value.length" class="skin-layout-warning" role="status">
|
||||
<p v-for="warning in editor.layoutWarnings.value" :key="warning">{{ warning }}</p>
|
||||
<button type="button" @click="editor.ignoreLayoutWarnings">{{ editor.labels.value.ignoreWarnings }}</button>
|
||||
</div>
|
||||
<div v-if="editor.migrationRecovery.value" class="skin-layout-warning" role="status">
|
||||
<span>{{ editor.labels.value.migrationWarning(editor.migrationRecoveryCount.value) }}</span>
|
||||
<button type="button" @click="editor.exportRecovery">{{ editor.labels.value.exportRecovery }}</button>
|
||||
</div>
|
||||
<p class="skin-layout-context">{{ editor.context.value?.skinId }} · {{ editor.context.value?.page }} · {{ editor.context.value?.profile }}</p>
|
||||
</section>
|
||||
</div>
|
||||
<div v-if="editor.focusPreviewEnabled.value" class="skin-layout-focus-overlay" aria-hidden="true">
|
||||
<span
|
||||
v-for="target in editor.focusPreviewTargets.value"
|
||||
:key="target.key"
|
||||
class="skin-layout-focus-marker"
|
||||
:class="{ 'is-small': !target.meetsTouchTarget }"
|
||||
:style="{ left: `${target.left}px`, top: `${target.top}px`, width: `${target.width}px`, height: `${target.height}px` }"
|
||||
>{{ target.order }}</span>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from "vue";
|
||||
type="button"
|
||||
:aria-expanded="editor.isOpen.value"
|
||||
aria-controls="skin-layout-panel"
|
||||
@click="editor.setOpen(!editor.isOpen.value)"
|
||||
>
|
||||
<span aria-hidden="true">⠿</span>
|
||||
{{ editor.labels.value.editButton }}
|
||||
</button>
|
||||
|
||||
<section
|
||||
v-if="editorMode.isEnabled.value && editor.isOpen.value"
|
||||
id="skin-layout-panel"
|
||||
class="skin-layout-panel"
|
||||
role="dialog"
|
||||
aria-modal="false"
|
||||
:aria-label="editor.labels.value.title"
|
||||
>
|
||||
<header class="skin-layout-heading">
|
||||
<div>
|
||||
<h2>{{ editor.labels.value.title }}</h2>
|
||||
<p>{{ editor.labels.value.hint }}</p>
|
||||
</div>
|
||||
<button ref="closeButton" type="button" class="skin-layout-close" :aria-label="editor.labels.value.close" @click="editor.setOpen(false)">×</button>
|
||||
</header>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.isEditing.value" @change="editor.setEditing(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.editMode }}</span>
|
||||
</label>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.focusPreviewEnabled.value" @change="editor.setFocusPreview(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.focusPreview }}</span>
|
||||
</label>
|
||||
<ol v-if="editor.focusPreviewEnabled.value" class="skin-layout-focus-list" :aria-label="editor.labels.value.focusPreview">
|
||||
<li v-if="!editor.focusPreviewTargets.value.length" class="skin-layout-focus-empty">
|
||||
{{ editor.labels.value.focusPreviewEmpty }}
|
||||
</li>
|
||||
<li v-for="target in editor.focusPreviewTargets.value" :key="target.key" :class="{ 'is-small': !target.meetsTouchTarget }">
|
||||
<span class="skin-layout-focus-number" aria-hidden="true">{{ target.order }}</span>
|
||||
<span class="skin-layout-focus-name"><strong>{{ target.componentName }}</strong><small>{{ target.accessibleName || editor.labels.value.focusPreviewUnnamed }}</small></span>
|
||||
<span class="skin-layout-focus-size">{{ editor.labels.value.focusPreviewTargetSize.replace("{width}", String(Math.round(target.width))).replace("{height}", String(Math.round(target.height))) }}<small>{{ target.meetsTouchTarget ? editor.labels.value.focusPreviewTargetAdequate : editor.labels.value.focusPreviewTargetSmall }}</small></span>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<label class="skin-layout-field">
|
||||
<span>{{ editor.labels.value.component }}</span>
|
||||
<input v-model="editor.filter.value" type="search" :placeholder="editor.labels.value.filter" />
|
||||
<select :value="editor.selectedComponentId.value" @change="editor.selectComponent(($event.target as HTMLSelectElement).value)">
|
||||
<option v-for="component in editor.filteredComponents.value" :key="component.id" :value="component.id">{{ component.name }} ({{ component.id }})</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="skin-layout-toggle">
|
||||
<input type="checkbox" :checked="editor.selectedVisible.value" @change="editor.setVisible(($event.target as HTMLInputElement).checked)" />
|
||||
<span>{{ editor.labels.value.visible }}</span>
|
||||
</label>
|
||||
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.positionX }}</span><output>{{ Math.round(editor.selectedX.value) }} px</output></label>
|
||||
<input type="range" :min="editor.positionBoundsX.value.minimum" :max="editor.positionBoundsX.value.maximum" step="1" :value="editor.selectedX.value" @input="editor.setX(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.positionY }}</span><output>{{ Math.round(editor.selectedY.value) }} px</output></label>
|
||||
<input type="range" :min="editor.positionBoundsY.value.minimum" :max="editor.positionBoundsY.value.maximum" step="1" :value="editor.selectedY.value" @input="editor.setY(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.size }}</span><output>{{ Math.round(editor.selectedScale.value * 100) }}%</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minScale" :max="editor.selectedSizeBounds.value.maxScale" step="0.05" :value="editor.selectedScale.value" @input="editor.setScale(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.width }}</span><output>{{ Math.round(editor.selectedWidth.value) }} px</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minWidth" :max="editor.selectedSizeBounds.value.maxWidth" step="4" :value="editor.selectedWidth.value" @input="editor.setWidth(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.height }}</span><output>{{ Math.round(editor.selectedHeight.value) }} px</output></label>
|
||||
<input type="range" :min="editor.selectedSizeBounds.value.minHeight" :max="editor.selectedSizeBounds.value.maxHeight" step="4" :value="editor.selectedHeight.value" @input="editor.setHeight(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
<div class="skin-layout-range" :title="editor.labels.value.orderHint">
|
||||
<label><span>{{ editor.labels.value.order }}</span><output>{{ editor.selectedOrder.value }}</output></label>
|
||||
<input type="range" min="-100" max="100" step="1" :value="editor.selectedOrder.value" @input="editor.setOrder(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-colors">
|
||||
<label><span>{{ editor.labels.value.foreground }}</span><input type="color" :value="editor.selectedForeground.value" @input="editor.setForeground(($event.target as HTMLInputElement).value)" /></label>
|
||||
<label><span>{{ editor.labels.value.background }}</span><input type="color" :value="editor.selectedBackground.value" @input="editor.setBackground(($event.target as HTMLInputElement).value)" /></label>
|
||||
<label><span>{{ editor.labels.value.border }}</span><input type="color" :value="editor.selectedBorder.value" @input="editor.setBorder(($event.target as HTMLInputElement).value)" /></label>
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-range">
|
||||
<label><span>{{ editor.labels.value.radius }}</span><output>{{ Math.round(editor.selectedRadius.value) }} px</output></label>
|
||||
<input type="range" min="0" max="64" step="1" :value="editor.selectedRadius.value" @input="editor.setRadius(Number(($event.target as HTMLInputElement).value))" />
|
||||
</div>
|
||||
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" :disabled="!editor.canUndo.value" @click="editor.undo">{{ editor.labels.value.undo }}</button>
|
||||
<button type="button" :disabled="!editor.canRedo.value" @click="editor.redo">{{ editor.labels.value.redo }}</button>
|
||||
</div>
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" @click="editor.resetComponent">{{ editor.labels.value.resetItem }}</button>
|
||||
<button type="button" @click="editor.resetAll">{{ editor.labels.value.resetAll }}</button>
|
||||
</div>
|
||||
<div class="skin-layout-actions">
|
||||
<button type="button" @click="editor.exportCurrent">{{ editor.labels.value.export }}</button>
|
||||
<button type="button" @click="importInput?.click()">{{ editor.labels.value.import }}</button>
|
||||
<input ref="importInput" class="skin-layout-file" type="file" accept="application/json,.json" @change="onImport" />
|
||||
</div>
|
||||
<p v-if="editor.statusMessage.value" class="skin-layout-status" role="status">{{ editor.statusMessage.value }}</p>
|
||||
<div v-if="editor.layoutWarnings.value.length" class="skin-layout-warning" role="status">
|
||||
<p v-for="warning in editor.layoutWarnings.value" :key="warning">{{ warning }}</p>
|
||||
<button type="button" @click="editor.ignoreLayoutWarnings">{{ editor.labels.value.ignoreWarnings }}</button>
|
||||
</div>
|
||||
<div v-if="editor.migrationRecovery.value" class="skin-layout-warning" role="status">
|
||||
<span>{{ editor.labels.value.migrationWarning(editor.migrationRecoveryCount.value) }}</span>
|
||||
<button type="button" @click="editor.exportRecovery">{{ editor.labels.value.exportRecovery }}</button>
|
||||
</div>
|
||||
<p class="skin-layout-context">{{ editor.context.value?.skinId }} · {{ editor.context.value?.page }} · {{ editor.context.value?.profile }}</p>
|
||||
</section>
|
||||
</div>
|
||||
<div v-if="editorMode.isEnabled.value && editor.focusPreviewEnabled.value" class="skin-layout-focus-overlay" aria-hidden="true">
|
||||
<span
|
||||
v-for="target in editor.focusPreviewTargets.value"
|
||||
:key="target.key"
|
||||
class="skin-layout-focus-marker"
|
||||
:class="{ 'is-small': !target.meetsTouchTarget }"
|
||||
:style="{ left: `${target.left}px`, top: `${target.top}px`, width: `${target.width}px`, height: `${target.height}px` }"
|
||||
>{{ target.order }}</span>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
import { useSkinLayoutEditor } from "../composables/useSkinLayoutEditor.js";
|
||||
import { promoteHostEditorToTopLayer } from "../services/host-editor-top-layer.js";
|
||||
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
|
||||
import { useRoute } from "vue-router";
|
||||
|
||||
const editor = useSkinLayoutEditor();
|
||||
const editorMode = useSkinEditorMode();
|
||||
const route = useRoute();
|
||||
const editorRoot = ref<HTMLElement | null>(null);
|
||||
const importInput = ref<HTMLInputElement | null>(null);
|
||||
const triggerButton = ref<HTMLButtonElement | null>(null);
|
||||
const importInput = ref<HTMLInputElement | null>(null);
|
||||
const triggerButton = ref<HTMLButtonElement | null>(null);
|
||||
const closeButton = ref<HTMLButtonElement | null>(null);
|
||||
let accessCheckTimer: number | undefined;
|
||||
|
||||
watch(editorRoot, promoteHostEditorToTopLayer, { flush: "post" });
|
||||
watch(editor.isOpen, async (isOpen) => {
|
||||
await nextTick();
|
||||
(isOpen ? closeButton.value : triggerButton.value)?.focus();
|
||||
function refreshAdminAccess(): void {
|
||||
if (document.visibilityState !== "hidden") void editorMode.refreshAdminAccess();
|
||||
}
|
||||
|
||||
async function toggleEditorMode(): Promise<void> {
|
||||
const enabled = await editorMode.setEnabled(!editorMode.isEnabled.value);
|
||||
if (!enabled) editor.setOpen(false);
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
refreshAdminAccess();
|
||||
window.addEventListener("focus", refreshAdminAccess);
|
||||
document.addEventListener("visibilitychange", refreshAdminAccess);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener("focus", refreshAdminAccess);
|
||||
document.removeEventListener("visibilitychange", refreshAdminAccess);
|
||||
if (accessCheckTimer !== undefined) window.clearInterval(accessCheckTimer);
|
||||
});
|
||||
|
||||
async function onImport(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
await editor.importFile(input.files?.[0]);
|
||||
input.value = "";
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.skin-layout-editor {
|
||||
position: fixed;
|
||||
inset: auto;
|
||||
z-index: 2147483647;
|
||||
top: auto;
|
||||
left: auto;
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
overflow: visible;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
color: #172033;
|
||||
background: transparent;
|
||||
font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.skin-layout-editor button,
|
||||
.skin-layout-editor input,
|
||||
.skin-layout-editor select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
watch(editorRoot, promoteHostEditorToTopLayer, { flush: "post" });
|
||||
watch(() => route.fullPath, refreshAdminAccess);
|
||||
watch(editorMode.isEnabled, (enabled) => {
|
||||
if (accessCheckTimer !== undefined) window.clearInterval(accessCheckTimer);
|
||||
accessCheckTimer = enabled ? window.setInterval(refreshAdminAccess, 60_000) : undefined;
|
||||
if (!enabled) editor.setOpen(false);
|
||||
});
|
||||
watch(editor.isOpen, async (isOpen) => {
|
||||
await nextTick();
|
||||
(isOpen ? closeButton.value : triggerButton.value)?.focus();
|
||||
});
|
||||
|
||||
async function onImport(event: Event): Promise<void> {
|
||||
const input = event.target as HTMLInputElement;
|
||||
await editor.importFile(input.files?.[0]);
|
||||
input.value = "";
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.skin-layout-editor {
|
||||
position: fixed;
|
||||
inset: auto;
|
||||
z-index: 2147483647;
|
||||
top: auto;
|
||||
left: auto;
|
||||
right: 14px;
|
||||
bottom: 14px;
|
||||
width: auto;
|
||||
height: auto;
|
||||
max-width: none;
|
||||
max-height: none;
|
||||
overflow: visible;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
color: #172033;
|
||||
background: transparent;
|
||||
font: 13px/1.45 Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.skin-layout-editor button,
|
||||
.skin-layout-editor input,
|
||||
.skin-layout-editor select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.skin-layout-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-height: 44px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 999px;
|
||||
color: #fff;
|
||||
background: #273449;
|
||||
box-shadow: 0 5px 22px #0f172a55;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.skin-editor-mode-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
min-height: 44px;
|
||||
margin-inline-end: 8px;
|
||||
padding: 0 14px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 999px;
|
||||
color: #fff;
|
||||
background: #273449;
|
||||
background: #334155;
|
||||
box-shadow: 0 5px 22px #0f172a55;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.skin-layout-trigger span { font-size: 19px; line-height: 1; }
|
||||
|
||||
.skin-layout-panel {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 56px;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
width: min(360px, calc(100vw - 24px));
|
||||
max-height: min(78vh, 720px);
|
||||
overflow: auto;
|
||||
padding: 16px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
box-shadow: 0 18px 60px #0f172a44;
|
||||
}
|
||||
|
||||
.skin-layout-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.skin-layout-heading h2 { margin: 0; font-size: 16px; }
|
||||
.skin-layout-heading p { margin: 5px 0 0; color: #475569; font-size: 12px; }
|
||||
.skin-layout-close { width: 44px; height: 44px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 22px !important; cursor: pointer; }
|
||||
.skin-layout-toggle { display: flex; align-items: center; gap: 8px; min-height: 44px; }
|
||||
.skin-layout-field { display: grid; gap: 6px; }
|
||||
.skin-layout-field > span,
|
||||
.skin-layout-range label,
|
||||
.skin-layout-colors span { color: #475569; font-size: 12px; }
|
||||
.skin-layout-field input[type="search"],
|
||||
.skin-layout-field select { width: 100%; min-height: 44px; padding: 6px 9px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #fff; }
|
||||
.skin-layout-range { display: grid; gap: 3px; }
|
||||
.skin-layout-range label { display: flex; justify-content: space-between; gap: 8px; }
|
||||
.skin-layout-range output { color: #172033; font-variant-numeric: tabular-nums; }
|
||||
.skin-layout-range input { width: 100%; min-height: 44px; accent-color: #4f46e5; }
|
||||
.skin-layout-colors { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
|
||||
.skin-layout-colors label { display: grid; gap: 4px; }
|
||||
.skin-layout-colors input { width: 100%; height: 44px; padding: 2px; border: 1px solid #cbd5e1; border-radius: 7px; background: #fff; }
|
||||
.skin-layout-actions { display: flex; flex-wrap: wrap; gap: 7px; }
|
||||
.skin-layout-actions button { min-height: 44px; padding: 0 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; cursor: pointer; }
|
||||
.skin-layout-actions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.skin-layout-file { display: none; }
|
||||
.skin-layout-status { margin: 0; color: #4338ca; }
|
||||
.skin-layout-warning { margin: 0; padding: 8px 10px; border: 1px solid #fcd34d; border-radius: 8px; color: #854d0e; background: #fffbeb; }
|
||||
.skin-layout-warning button { min-height: 44px; margin-top: 6px; padding: 0 9px; border: 1px solid #d97706; border-radius: 7px; color: #78350f; background: #fff; cursor: pointer; }
|
||||
.skin-layout-context { margin: 0; color: #64748b; font-size: 11px; overflow-wrap: anywhere; }
|
||||
.skin-layout-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
|
||||
.skin-layout-focus-list { display: grid; gap: 6px; max-height: 220px; overflow: auto; margin: 0; padding: 0; list-style: none; }
|
||||
.skin-layout-focus-list > li { display: flex; align-items: flex-start; gap: 8px; min-width: 0; padding: 7px; border: 1px solid #86efac; border-radius: 8px; background: #f0fdf4; }
|
||||
.skin-layout-focus-list > li.is-small { border-color: #fca5a5; background: #fef2f2; }
|
||||
.skin-layout-focus-list .skin-layout-focus-empty { border-color: #cbd5e1; background: #f8fafc; color: #475569; }
|
||||
.skin-layout-focus-number { display: grid; place-items: center; flex: 0 0 22px; width: 22px; height: 22px; border-radius: 50%; color: #fff; background: #15803d; font-weight: 700; }
|
||||
.is-small .skin-layout-focus-number { background: #b91c1c; }
|
||||
.skin-layout-focus-name, .skin-layout-focus-size { display: grid; min-width: 0; gap: 2px; overflow-wrap: anywhere; }
|
||||
.skin-layout-focus-name { flex: 1; }
|
||||
.skin-layout-focus-name small, .skin-layout-focus-size small { color: #475569; font-size: 10px; }
|
||||
.skin-layout-focus-size { flex: 0 0 auto; text-align: right; }
|
||||
.skin-layout-focus-overlay { position: fixed; z-index: 2147483647; inset: 0; pointer-events: none; }
|
||||
.skin-layout-focus-marker { position: fixed; box-sizing: border-box; display: grid; place-items: start; padding: 0 2px; border: 2px solid #15803d; border-radius: 3px; color: #fff; background: #15803d40; font: 700 11px/16px ui-sans-serif, system-ui, sans-serif; }
|
||||
.skin-layout-focus-marker.is-small { border-color: #b91c1c; background: #b91c1c40; }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.skin-layout-editor { right: 10px; bottom: 10px; }
|
||||
.skin-layout-panel { max-height: 72vh; }
|
||||
}
|
||||
</style>
|
||||
.skin-editor-mode-trigger span { font-size: 19px; line-height: 1; }
|
||||
.skin-editor-mode-trigger:focus-visible { outline: 3px solid #fbbf24; outline-offset: 3px; }
|
||||
|
||||
.skin-layout-trigger span { font-size: 19px; line-height: 1; }
|
||||
|
||||
.skin-layout-panel {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 56px;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
width: min(360px, calc(100vw - 24px));
|
||||
max-height: min(78vh, 720px);
|
||||
overflow: auto;
|
||||
padding: 16px;
|
||||
border: 1px solid #cbd5e1;
|
||||
border-radius: 16px;
|
||||
background: #fff;
|
||||
box-shadow: 0 18px 60px #0f172a44;
|
||||
}
|
||||
|
||||
.skin-layout-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.skin-layout-heading h2 { margin: 0; font-size: 16px; }
|
||||
.skin-layout-heading p { margin: 5px 0 0; color: #475569; font-size: 12px; }
|
||||
.skin-layout-close { width: 44px; height: 44px; border-radius: 8px; color: #334155; background: #f1f5f9; font-size: 22px !important; cursor: pointer; }
|
||||
.skin-layout-toggle { display: flex; align-items: center; gap: 8px; min-height: 44px; }
|
||||
.skin-layout-field { display: grid; gap: 6px; }
|
||||
.skin-layout-field > span,
|
||||
.skin-layout-range label,
|
||||
.skin-layout-colors span { color: #475569; font-size: 12px; }
|
||||
.skin-layout-field input[type="search"],
|
||||
.skin-layout-field select { width: 100%; min-height: 44px; padding: 6px 9px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #fff; }
|
||||
.skin-layout-range { display: grid; gap: 3px; }
|
||||
.skin-layout-range label { display: flex; justify-content: space-between; gap: 8px; }
|
||||
.skin-layout-range output { color: #172033; font-variant-numeric: tabular-nums; }
|
||||
.skin-layout-range input { width: 100%; min-height: 44px; accent-color: #4f46e5; }
|
||||
.skin-layout-colors { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; }
|
||||
.skin-layout-colors label { display: grid; gap: 4px; }
|
||||
.skin-layout-colors input { width: 100%; height: 44px; padding: 2px; border: 1px solid #cbd5e1; border-radius: 7px; background: #fff; }
|
||||
.skin-layout-actions { display: flex; flex-wrap: wrap; gap: 7px; }
|
||||
.skin-layout-actions button { min-height: 44px; padding: 0 10px; border: 1px solid #cbd5e1; border-radius: 8px; color: #172033; background: #f8fafc; cursor: pointer; }
|
||||
.skin-layout-actions button:disabled { opacity: .5; cursor: not-allowed; }
|
||||
.skin-layout-file { display: none; }
|
||||
.skin-layout-status { margin: 0; color: #4338ca; }
|
||||
.skin-layout-warning { margin: 0; padding: 8px 10px; border: 1px solid #fcd34d; border-radius: 8px; color: #854d0e; background: #fffbeb; }
|
||||
.skin-layout-warning button { min-height: 44px; margin-top: 6px; padding: 0 9px; border: 1px solid #d97706; border-radius: 7px; color: #78350f; background: #fff; cursor: pointer; }
|
||||
.skin-layout-context { margin: 0; color: #64748b; font-size: 11px; overflow-wrap: anywhere; }
|
||||
.skin-layout-editor :focus-visible { outline: 2px solid #4f46e5; outline-offset: 2px; }
|
||||
.skin-layout-focus-list { display: grid; gap: 6px; max-height: 220px; overflow: auto; margin: 0; padding: 0; list-style: none; }
|
||||
.skin-layout-focus-list > li { display: flex; align-items: flex-start; gap: 8px; min-width: 0; padding: 7px; border: 1px solid #86efac; border-radius: 8px; background: #f0fdf4; }
|
||||
.skin-layout-focus-list > li.is-small { border-color: #fca5a5; background: #fef2f2; }
|
||||
.skin-layout-focus-list .skin-layout-focus-empty { border-color: #cbd5e1; background: #f8fafc; color: #475569; }
|
||||
.skin-layout-focus-number { display: grid; place-items: center; flex: 0 0 22px; width: 22px; height: 22px; border-radius: 50%; color: #fff; background: #15803d; font-weight: 700; }
|
||||
.is-small .skin-layout-focus-number { background: #b91c1c; }
|
||||
.skin-layout-focus-name, .skin-layout-focus-size { display: grid; min-width: 0; gap: 2px; overflow-wrap: anywhere; }
|
||||
.skin-layout-focus-name { flex: 1; }
|
||||
.skin-layout-focus-name small, .skin-layout-focus-size small { color: #475569; font-size: 10px; }
|
||||
.skin-layout-focus-size { flex: 0 0 auto; text-align: right; }
|
||||
.skin-layout-focus-overlay { position: fixed; z-index: 2147483647; inset: 0; pointer-events: none; }
|
||||
.skin-layout-focus-marker { position: fixed; box-sizing: border-box; display: grid; place-items: start; padding: 0 2px; border: 2px solid #15803d; border-radius: 3px; color: #fff; background: #15803d40; font: 700 11px/16px ui-sans-serif, system-ui, sans-serif; }
|
||||
.skin-layout-focus-marker.is-small { border-color: #b91c1c; background: #b91c1c40; }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.skin-layout-editor { right: 10px; bottom: 10px; }
|
||||
.skin-layout-panel { max-height: 72vh; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,139 +1,149 @@
|
||||
import { computed, defineComponent, Fragment, h, onUnmounted, reactive, ref, Teleport, watch, type PropType, type VNodeChild } from "vue";
|
||||
import {
|
||||
SKIN_PLUGIN_COMPONENT_LIMIT,
|
||||
SKIN_PLUGIN_PERMISSIONS,
|
||||
SKIN_PLUGIN_RENDER_NODE_LIMIT,
|
||||
SKIN_PLUGIN_REPEAT_LIMIT,
|
||||
listSkinPluginAssetPaths,
|
||||
parseSkinPluginDocument,
|
||||
type SkinPluginActionDefinition,
|
||||
type SkinPluginComponent,
|
||||
type SkinPluginComponentMode,
|
||||
type SkinPluginDocument,
|
||||
type SkinPluginHostWidget,
|
||||
import { computed, defineComponent, Fragment, h, onUnmounted, reactive, ref, Teleport, watch, type PropType, type VNodeChild } from "vue";
|
||||
import {
|
||||
SKIN_PLUGIN_COMPONENT_LIMIT,
|
||||
SKIN_PLUGIN_PERMISSIONS,
|
||||
SKIN_PLUGIN_RENDER_NODE_LIMIT,
|
||||
SKIN_PLUGIN_REPEAT_LIMIT,
|
||||
listSkinPluginAssetPaths,
|
||||
parseSkinPluginDocument,
|
||||
type SkinPluginActionDefinition,
|
||||
type SkinPluginComponent,
|
||||
type SkinPluginComponentMode,
|
||||
type SkinPluginDocument,
|
||||
type SkinPluginHostWidget,
|
||||
type SkinPluginNode,
|
||||
type SkinPluginWidgetOptions,
|
||||
type SkinPluginPermission,
|
||||
} from "../../../src/shared/skin-plugin.js";
|
||||
import { parseSkinExtensionUiOutput } from "../../../src/shared/skin-extension-ui.js";
|
||||
import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
|
||||
type SkinPluginPermission,
|
||||
} from "../../../src/shared/skin-plugin.js";
|
||||
import { parseSkinExtensionUiOutput } from "../../../src/shared/skin-extension-ui.js";
|
||||
import { parseSkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
|
||||
import { approveSkinPluginComponents, getMissingSkinPluginApprovals, isSkinPluginComponentApproved, revokeSkinPluginApprovals } from "../services/skin-plugin-approval.js";
|
||||
import { createSkinPluginAssetUrlCache } from "../services/skin-plugin-asset-urls.js";
|
||||
|
||||
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
|
||||
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
|
||||
|
||||
type Scalar = string | number | boolean;
|
||||
const LOCAL_STATE_SCOPE_LIMIT = 128;
|
||||
type SafeContext = Record<string, unknown>;
|
||||
type HostAction = (args: Record<string, Scalar>, component: SkinPluginComponent) => void | Promise<void>;
|
||||
type SafeContext = Record<string, unknown>;
|
||||
type HostAction = (args: Record<string, Scalar>, component: SkinPluginComponent) => void | Promise<void>;
|
||||
type HostWidget = (options?: SkinPluginWidgetOptions) => VNodeChild;
|
||||
|
||||
const eventProps: Record<string, string> = {
|
||||
click: "onClick", dblclick: "onDblclick", change: "onChange", input: "onInput", submit: "onSubmit", keydown: "onKeydown", keyup: "onKeyup",
|
||||
contextmenu: "onContextmenu", focus: "onFocus", blur: "onBlur", pointerdown: "onPointerdown", pointerup: "onPointerup",
|
||||
pointerenter: "onPointerenter", pointerleave: "onPointerleave", dragstart: "onDragstart", dragover: "onDragover", drop: "onDrop",
|
||||
};
|
||||
|
||||
const svgAttributeNames: Record<string, string> = {
|
||||
basefrequency: "baseFrequency", clippathunits: "clipPathUnits", diffuseconstant: "diffuseConstant", edgemode: "edgeMode",
|
||||
filterunits: "filterUnits", gradienttransform: "gradientTransform", gradientunits: "gradientUnits", kernelmatrix: "kernelMatrix",
|
||||
kernelunitlength: "kernelUnitLength", lengthadjust: "lengthAdjust", markerheight: "markerHeight", markerunits: "markerUnits",
|
||||
markerwidth: "markerWidth", numoctaves: "numOctaves", pathlength: "pathLength", pointsatx: "pointsAtX", pointsaty: "pointsAtY",
|
||||
pointsatz: "pointsAtZ", preserveaspectratio: "preserveAspectRatio", primitiveunits: "primitiveUnits", refx: "refX", refy: "refY",
|
||||
specularconstant: "specularConstant", specularexponent: "specularExponent", spreadmethod: "spreadMethod", startoffset: "startOffset",
|
||||
textlength: "textLength", viewbox: "viewBox",
|
||||
};
|
||||
|
||||
export default defineComponent({
|
||||
name: "SkinPluginOutlet",
|
||||
props: {
|
||||
skinId: { type: String, required: true },
|
||||
skinVersion: { type: String, required: true },
|
||||
document: { type: Object as PropType<SkinPluginDocument>, required: true },
|
||||
extensionOutput: { type: String as PropType<string | null>, default: null },
|
||||
extensionMode: { type: String as PropType<SkinPluginComponentMode | undefined>, default: undefined },
|
||||
extensionPermissions: { type: Array as PropType<readonly SkinPluginPermission[]>, default: () => [] },
|
||||
componentNamespace: { type: String, default: "" },
|
||||
manageSurfaceRecovery: { type: Boolean, default: true },
|
||||
page: { type: String as PropType<"home" | "voice" | "demo">, required: true },
|
||||
data: { type: Object as PropType<SafeContext>, required: true },
|
||||
assets: { type: Object as PropType<Record<string, Blob>>, required: true },
|
||||
actions: { type: Object as PropType<Record<string, HostAction>>, required: true },
|
||||
widgets: { type: Object as PropType<Partial<Record<SkinPluginHostWidget, HostWidget>>>, default: () => ({}) },
|
||||
},
|
||||
emits: {
|
||||
"surface-change": (_active: boolean) => typeof _active === "boolean",
|
||||
"restore-skin": () => true,
|
||||
"extension-event": (_payload: unknown) => true,
|
||||
|
||||
const eventProps: Record<string, string> = {
|
||||
click: "onClick", dblclick: "onDblclick", change: "onChange", input: "onInput", submit: "onSubmit", keydown: "onKeydown", keyup: "onKeyup",
|
||||
contextmenu: "onContextmenu", focus: "onFocus", blur: "onBlur", pointerdown: "onPointerdown", pointerup: "onPointerup",
|
||||
pointerenter: "onPointerenter", pointerleave: "onPointerleave", dragstart: "onDragstart", dragover: "onDragover", drop: "onDrop",
|
||||
};
|
||||
|
||||
const svgAttributeNames: Record<string, string> = {
|
||||
basefrequency: "baseFrequency", clippathunits: "clipPathUnits", diffuseconstant: "diffuseConstant", edgemode: "edgeMode",
|
||||
filterunits: "filterUnits", gradienttransform: "gradientTransform", gradientunits: "gradientUnits", kernelmatrix: "kernelMatrix",
|
||||
kernelunitlength: "kernelUnitLength", lengthadjust: "lengthAdjust", markerheight: "markerHeight", markerunits: "markerUnits",
|
||||
markerwidth: "markerWidth", numoctaves: "numOctaves", pathlength: "pathLength", pointsatx: "pointsAtX", pointsaty: "pointsAtY",
|
||||
pointsatz: "pointsAtZ", preserveaspectratio: "preserveAspectRatio", primitiveunits: "primitiveUnits", refx: "refX", refy: "refY",
|
||||
specularconstant: "specularConstant", specularexponent: "specularExponent", spreadmethod: "spreadMethod", startoffset: "startOffset",
|
||||
textlength: "textLength", viewbox: "viewBox",
|
||||
};
|
||||
|
||||
export default defineComponent({
|
||||
name: "SkinPluginOutlet",
|
||||
props: {
|
||||
skinId: { type: String, required: true },
|
||||
skinVersion: { type: String, required: true },
|
||||
document: { type: Object as PropType<SkinPluginDocument>, required: true },
|
||||
extensionOutput: { type: String as PropType<string | null>, default: null },
|
||||
extensionMode: { type: String as PropType<SkinPluginComponentMode | undefined>, default: undefined },
|
||||
extensionPermissions: { type: Array as PropType<readonly SkinPluginPermission[]>, default: () => [] },
|
||||
componentNamespace: { type: String, default: "" },
|
||||
manageSurfaceRecovery: { type: Boolean, default: true },
|
||||
page: { type: String as PropType<"home" | "voice" | "demo">, required: true },
|
||||
data: { type: Object as PropType<SafeContext>, required: true },
|
||||
assets: { type: Object as PropType<Record<string, Blob>>, required: true },
|
||||
actions: { type: Object as PropType<Record<string, HostAction>>, required: true },
|
||||
widgets: { type: Object as PropType<Partial<Record<SkinPluginHostWidget, HostWidget>>>, default: () => ({}) },
|
||||
},
|
||||
emits: {
|
||||
"surface-change": (_active: boolean) => typeof _active === "boolean",
|
||||
"restore-skin": () => true,
|
||||
"extension-event": (_payload: unknown) => true,
|
||||
},
|
||||
setup(props, { emit }) {
|
||||
const editorMode = useSkinEditorMode();
|
||||
const denied = ref(false);
|
||||
const surfaceSuppressed = ref(false);
|
||||
const manageOpen = ref(false);
|
||||
const refresh = ref(0);
|
||||
const surfaceSuppressed = ref(false);
|
||||
const manageOpen = ref(false);
|
||||
const refresh = ref(0);
|
||||
const stateByComponent = reactive<Record<string, Record<string, Record<string, Scalar>>>>({});
|
||||
const assetUrls = createSkinPluginAssetUrlCache();
|
||||
const validatedDocument = computed(() => {
|
||||
let document: SkinPluginDocument;
|
||||
const emptyRuntimeBase = Boolean(props.extensionOutput)
|
||||
&& props.document.schemaVersion === 3
|
||||
&& Array.isArray(props.document.components)
|
||||
&& props.document.components.length === 0;
|
||||
try {
|
||||
// Runtime plugins use an empty v3 base document so their validated generated output
|
||||
// can flow through the same approval, layout, and rendering path as packaged components.
|
||||
document = emptyRuntimeBase
|
||||
? { schemaVersion: 3, components: [] }
|
||||
: parseSkinPluginDocument(props.document);
|
||||
}
|
||||
catch { return { schemaVersion: 2 as const, components: [] }; }
|
||||
if (!props.extensionOutput || document.schemaVersion !== 3) return document;
|
||||
try {
|
||||
const parsedExtensionDocument = parseSkinExtensionUiOutput(props.extensionOutput, { permissions: props.extensionPermissions });
|
||||
const extensionDocument = props.extensionMode
|
||||
? { ...parsedExtensionDocument, components: parsedExtensionDocument.components.map((component) => ({ ...component, mode: props.extensionMode })) }
|
||||
: parsedExtensionDocument;
|
||||
const ids = new Set(document.components.map((component) => component.id));
|
||||
if (document.components.length + extensionDocument.components.length > SKIN_PLUGIN_COMPONENT_LIMIT
|
||||
|| extensionDocument.components.some((component) => ids.has(component.id))) return document;
|
||||
return { schemaVersion: 3 as const, components: [...document.components, ...extensionDocument.components] };
|
||||
} catch {
|
||||
// Dynamic output is optional; an invalid or colliding result leaves the package UI intact.
|
||||
return document;
|
||||
}
|
||||
});
|
||||
const matchingComponents = computed(() => validatedDocument.value.components.filter((component) => component.page === props.page));
|
||||
const pendingApproval = computed(() => {
|
||||
refresh.value;
|
||||
return denied.value ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
|
||||
});
|
||||
const accessComponents = computed(() => pendingApproval.value.length
|
||||
? pendingApproval.value
|
||||
: matchingComponents.value.filter((component) => component.permissions.length > 0));
|
||||
const activeComponents = computed(() => {
|
||||
refresh.value;
|
||||
return matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component));
|
||||
});
|
||||
const surfaceCandidate = computed(() => activeComponents.value.find((component) => component.mode === "surface") ?? null);
|
||||
const activeSurface = computed(() => surfaceSuppressed.value ? null : surfaceCandidate.value);
|
||||
const assetUrls = createSkinPluginAssetUrlCache();
|
||||
const validatedDocument = computed(() => {
|
||||
let document: SkinPluginDocument;
|
||||
const emptyRuntimeBase = Boolean(props.extensionOutput)
|
||||
&& props.document.schemaVersion === 3
|
||||
&& Array.isArray(props.document.components)
|
||||
&& props.document.components.length === 0;
|
||||
try {
|
||||
// Runtime plugins use an empty v3 base document so their validated generated output
|
||||
// can flow through the same approval, layout, and rendering path as packaged components.
|
||||
document = emptyRuntimeBase
|
||||
? { schemaVersion: 3, components: [] }
|
||||
: parseSkinPluginDocument(props.document);
|
||||
}
|
||||
catch { return { schemaVersion: 2 as const, components: [] }; }
|
||||
if (!props.extensionOutput || document.schemaVersion !== 3) return document;
|
||||
try {
|
||||
const parsedExtensionDocument = parseSkinExtensionUiOutput(props.extensionOutput, { permissions: props.extensionPermissions });
|
||||
const extensionDocument = props.extensionMode
|
||||
? { ...parsedExtensionDocument, components: parsedExtensionDocument.components.map((component) => ({ ...component, mode: props.extensionMode })) }
|
||||
: parsedExtensionDocument;
|
||||
const ids = new Set(document.components.map((component) => component.id));
|
||||
if (document.components.length + extensionDocument.components.length > SKIN_PLUGIN_COMPONENT_LIMIT
|
||||
|| extensionDocument.components.some((component) => ids.has(component.id))) return document;
|
||||
return { schemaVersion: 3 as const, components: [...document.components, ...extensionDocument.components] };
|
||||
} catch {
|
||||
// Dynamic output is optional; an invalid or colliding result leaves the package UI intact.
|
||||
return document;
|
||||
}
|
||||
});
|
||||
const matchingComponents = computed(() => validatedDocument.value.components.filter((component) => component.page === props.page));
|
||||
const pendingApproval = computed(() => {
|
||||
refresh.value;
|
||||
return denied.value ? [] : getMissingSkinPluginApprovals(props.skinId, props.skinVersion, { ...validatedDocument.value, components: matchingComponents.value });
|
||||
});
|
||||
const accessComponents = computed(() => pendingApproval.value.length
|
||||
? pendingApproval.value
|
||||
: matchingComponents.value.filter((component) => component.permissions.length > 0));
|
||||
const activeComponents = computed(() => {
|
||||
refresh.value;
|
||||
return matchingComponents.value.filter((component) => isSkinPluginComponentApproved(props.skinId, props.skinVersion, component));
|
||||
});
|
||||
const surfaceCandidate = computed(() => activeComponents.value.find((component) => component.mode === "surface") ?? null);
|
||||
const activeSurface = computed(() => surfaceSuppressed.value ? null : surfaceCandidate.value);
|
||||
const renderedComponents = computed(() => activeComponents.value.filter((component) =>
|
||||
component.mode !== "surface" || component !== surfaceCandidate.value || !surfaceSuppressed.value));
|
||||
|
||||
watch(() => [props.skinId, props.skinVersion, props.document, props.extensionOutput, props.extensionMode, props.componentNamespace, props.page], () => {
|
||||
denied.value = false;
|
||||
surfaceSuppressed.value = false;
|
||||
watch(pendingApproval, (components) => {
|
||||
if (PROMPT_FOR_SKIN_PERMISSIONS || !components.length) return;
|
||||
approveSkinPluginComponents(props.skinId, props.skinVersion, components);
|
||||
refresh.value += 1;
|
||||
}, { immediate: true });
|
||||
watch(() => [props.skinId, props.skinVersion, props.assets] as const, () => assetUrls.clear());
|
||||
watch(renderedComponents, (components) => {
|
||||
assetUrls.retain(listSkinPluginAssetPaths({ schemaVersion: 3, components }));
|
||||
const activeStateKeys = new Set(components.map(componentStateKey));
|
||||
for (const key of Object.keys(stateByComponent)) {
|
||||
if (!activeStateKeys.has(key)) delete stateByComponent[key];
|
||||
}
|
||||
}, { immediate: true });
|
||||
watch(activeSurface, (surface) => emit("surface-change", Boolean(surface)), { immediate: true, flush: "sync" });
|
||||
watch(editorMode.isEnabled, (enabled) => { if (!enabled) manageOpen.value = false; });
|
||||
|
||||
watch(() => [props.skinId, props.skinVersion, props.document, props.extensionOutput, props.extensionMode, props.componentNamespace, props.page], () => {
|
||||
denied.value = false;
|
||||
surfaceSuppressed.value = false;
|
||||
refresh.value += 1;
|
||||
}, { immediate: true });
|
||||
watch(() => [props.skinId, props.skinVersion, props.assets] as const, () => assetUrls.clear());
|
||||
watch(renderedComponents, (components) => {
|
||||
assetUrls.retain(listSkinPluginAssetPaths({ schemaVersion: 3, components }));
|
||||
const activeStateKeys = new Set(components.map(componentStateKey));
|
||||
for (const key of Object.keys(stateByComponent)) {
|
||||
if (!activeStateKeys.has(key)) delete stateByComponent[key];
|
||||
}
|
||||
}, { immediate: true });
|
||||
watch(activeSurface, (surface) => emit("surface-change", Boolean(surface)), { immediate: true, flush: "sync" });
|
||||
|
||||
function componentStateKey(component: SkinPluginComponent): string {
|
||||
return JSON.stringify([props.skinId, props.skinVersion, props.componentNamespace, component.id, component.stateScope ?? ""]);
|
||||
return JSON.stringify([props.skinId, props.skinVersion, props.componentNamespace, component.id, component.stateScope ?? "", [...component.permissions].sort()]);
|
||||
}
|
||||
|
||||
function localState(component: SkinPluginComponent, context: SafeContext): Record<string, Scalar> {
|
||||
@@ -155,289 +165,289 @@ export default defineComponent({
|
||||
scopedStates[scopeKey] = state;
|
||||
return state;
|
||||
}
|
||||
for (const stateKey of Object.keys(state)) {
|
||||
if (!Object.hasOwn(defaults, stateKey)) delete state[stateKey];
|
||||
}
|
||||
for (const [stateKey, value] of Object.entries(defaults)) {
|
||||
if (!Object.hasOwn(state, stateKey) || typeof state[stateKey] !== typeof value) state[stateKey] = value;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function permissionLabel(permission: string): string {
|
||||
return SKIN_PLUGIN_PERMISSIONS[permission as keyof typeof SKIN_PLUGIN_PERMISSIONS]?.description ?? permission;
|
||||
}
|
||||
|
||||
function resolvePath(path: string, context: SafeContext, state: Record<string, Scalar>): unknown {
|
||||
const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, "");
|
||||
const parts = normalized.split(".");
|
||||
let value: unknown = parts[0] === "state" ? state : context;
|
||||
const start = parts[0] === "state" ? 1 : 0;
|
||||
for (let index = start; index < parts.length; index += 1) {
|
||||
if (!value || typeof value !== "object" || !Object.prototype.hasOwnProperty.call(value, parts[index])) return undefined;
|
||||
value = (value as Record<string, unknown>)[parts[index]];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function interpolate(value: string, context: SafeContext, state: Record<string, Scalar>): string {
|
||||
return value.replace(/\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g, (_match, path: string) => {
|
||||
const resolved = resolvePath(path, context, state);
|
||||
return typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" ? String(resolved) : "";
|
||||
});
|
||||
}
|
||||
|
||||
function resolveActionArgs(definition: SkinPluginActionDefinition, context: SafeContext, state: Record<string, Scalar>): Record<string, Scalar> {
|
||||
const args: Record<string, Scalar> = {};
|
||||
for (const [key, value] of Object.entries(definition.args)) {
|
||||
if (typeof value !== "string") { args[key] = value; continue; }
|
||||
const exact = /^\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}$/.exec(value);
|
||||
const resolved = exact ? resolvePath(exact[1], context, state) : interpolate(value, context, state);
|
||||
if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean") args[key] = resolved;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function dispatch(component: SkinPluginComponent, actionId: string, context: SafeContext, state: Record<string, Scalar>): void {
|
||||
const definition = component.actions[actionId];
|
||||
if (!definition || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
|
||||
const args = resolveActionArgs(definition, context, state);
|
||||
if (definition.type === "ui.setState") {
|
||||
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && "value" in args) state[args.key] = args.value;
|
||||
return;
|
||||
}
|
||||
if (definition.type === "ui.toggleState") {
|
||||
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && typeof state[args.key] === "boolean") {
|
||||
state[args.key] = !state[args.key];
|
||||
}
|
||||
return;
|
||||
}
|
||||
const handler = props.actions[definition.type];
|
||||
if (handler) void Promise.resolve(handler(args, component)).catch(() => undefined);
|
||||
}
|
||||
|
||||
function dispatchRuntimeCallback(component: SkinPluginComponent, handlerId: string, eventName: string, event: Event, state: Record<string, Scalar>): void {
|
||||
if (!component.runtimeCallbacks) return;
|
||||
const callbackEvent: Record<string, unknown> = { componentId: component.id, handlerId, eventName };
|
||||
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) callbackEvent.key = event.key;
|
||||
const mayReadUserInput = props.extensionPermissions.includes("ui.input.read");
|
||||
if (mayReadUserInput && (eventName === "input" || eventName === "change") && event.target instanceof HTMLInputElement) {
|
||||
if (["password", "file", "hidden"].includes(event.target.type)) return;
|
||||
if (event.target.type === "checkbox") callbackEvent.checked = event.target.checked;
|
||||
else if (event.target.value.length <= 2_048) callbackEvent.value = event.target.value;
|
||||
} else if (mayReadUserInput && (eventName === "input" || eventName === "change") && event.target instanceof HTMLTextAreaElement) {
|
||||
if (event.target.value.length <= 2_048) callbackEvent.value = event.target.value;
|
||||
} else if (mayReadUserInput && (eventName === "input" || eventName === "change") && event.target instanceof HTMLSelectElement
|
||||
&& event.target.value.length <= 2_048) {
|
||||
callbackEvent.value = event.target.value;
|
||||
}
|
||||
try {
|
||||
const input = parseSkinExtensionUiInput({ schemaVersion: 1, state: { ...state }, event: callbackEvent });
|
||||
emit("extension-event", { skinId: props.skinId, componentId: component.id, input });
|
||||
} catch {
|
||||
// Overlarge or malformed local state stays local and is not passed to the extension guest.
|
||||
}
|
||||
}
|
||||
|
||||
function assetUrl(path: string): string | undefined {
|
||||
return assetUrls.resolve(path, props.assets);
|
||||
}
|
||||
|
||||
function layoutComponentPath(component: SkinPluginComponent): string {
|
||||
return props.componentNamespace ? `runtime_plugin_${props.componentNamespace}__${component.id}` : component.id;
|
||||
}
|
||||
|
||||
function layoutPart(component: SkinPluginComponent, node: SkinPluginNode, nodePath: string): string {
|
||||
const interactive = ["a", "button", "input", "select", "summary", "textarea"].includes(node.tag ?? "")
|
||||
|| node.widget === "voice.screen-share-start"
|
||||
|| node.attributes?.role === "button"
|
||||
|| ["click", "dblclick", "contextmenu", "keydown", "keyup", "pointerdown", "pointerup", "drop"]
|
||||
.some((eventName) => Boolean(node.events?.[eventName as keyof typeof node.events]));
|
||||
const part = node.part ? `part-${node.part}` : nodePath;
|
||||
const componentPath = layoutComponentPath(component);
|
||||
return `skin.${component.page}.${componentPath}.${interactive ? "control-" : ""}${part}`;
|
||||
}
|
||||
|
||||
function renderNode(component: SkinPluginComponent, node: SkinPluginNode, context: SafeContext, state: Record<string, Scalar>, budget: { remaining: number }, skipRepeat = false, nodePath = "node-root"): VNodeChild {
|
||||
if (budget.remaining <= 0) return null;
|
||||
budget.remaining -= 1;
|
||||
if (node.widget) {
|
||||
if (node.when) {
|
||||
const value = resolvePath(node.when.path, context, state);
|
||||
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;
|
||||
return h("div", {
|
||||
class: ["ws-plugin-host-widget", node.className],
|
||||
"data-ws-plugin-widget": node.widget,
|
||||
"data-ws-plugin-part": node.part ? `${component.id}.${node.part}` : component.id,
|
||||
"data-ws-part": layoutPart(component, node, nodePath),
|
||||
"aria-label": component.accessibleName,
|
||||
for (const stateKey of Object.keys(state)) {
|
||||
if (!Object.hasOwn(defaults, stateKey)) delete state[stateKey];
|
||||
}
|
||||
for (const [stateKey, value] of Object.entries(defaults)) {
|
||||
if (!Object.hasOwn(state, stateKey) || typeof state[stateKey] !== typeof value) state[stateKey] = value;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function permissionLabel(permission: string): string {
|
||||
return SKIN_PLUGIN_PERMISSIONS[permission as keyof typeof SKIN_PLUGIN_PERMISSIONS]?.description ?? permission;
|
||||
}
|
||||
|
||||
function resolvePath(path: string, context: SafeContext, state: Record<string, Scalar>): unknown {
|
||||
const normalized = path.replace(/^\{\{\s*|\s*\}\}$/g, "");
|
||||
const parts = normalized.split(".");
|
||||
let value: unknown = parts[0] === "state" ? state : context;
|
||||
const start = parts[0] === "state" ? 1 : 0;
|
||||
for (let index = start; index < parts.length; index += 1) {
|
||||
if (!value || typeof value !== "object" || !Object.prototype.hasOwnProperty.call(value, parts[index])) return undefined;
|
||||
value = (value as Record<string, unknown>)[parts[index]];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function interpolate(value: string, context: SafeContext, state: Record<string, Scalar>): string {
|
||||
return value.replace(/\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}/g, (_match, path: string) => {
|
||||
const resolved = resolvePath(path, context, state);
|
||||
return typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean" ? String(resolved) : "";
|
||||
});
|
||||
}
|
||||
|
||||
function resolveActionArgs(definition: SkinPluginActionDefinition, context: SafeContext, state: Record<string, Scalar>): Record<string, Scalar> {
|
||||
const args: Record<string, Scalar> = {};
|
||||
for (const [key, value] of Object.entries(definition.args)) {
|
||||
if (typeof value !== "string") { args[key] = value; continue; }
|
||||
const exact = /^\{\{\s*([a-z][a-z0-9]*(?:\.[a-z][a-zA-Z0-9]*){0,5})\s*\}\}$/.exec(value);
|
||||
const resolved = exact ? resolvePath(exact[1], context, state) : interpolate(value, context, state);
|
||||
if (typeof resolved === "string" || typeof resolved === "number" || typeof resolved === "boolean") args[key] = resolved;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function dispatch(component: SkinPluginComponent, actionId: string, context: SafeContext, state: Record<string, Scalar>): void {
|
||||
const definition = component.actions[actionId];
|
||||
if (!definition || !isSkinPluginComponentApproved(props.skinId, props.skinVersion, component)) return;
|
||||
const args = resolveActionArgs(definition, context, state);
|
||||
if (definition.type === "ui.setState") {
|
||||
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && "value" in args) state[args.key] = args.value;
|
||||
return;
|
||||
}
|
||||
if (definition.type === "ui.toggleState") {
|
||||
if (typeof args.key === "string" && component.state && Object.hasOwn(component.state, args.key) && typeof state[args.key] === "boolean") {
|
||||
state[args.key] = !state[args.key];
|
||||
}
|
||||
return;
|
||||
}
|
||||
const handler = props.actions[definition.type];
|
||||
if (handler) void Promise.resolve(handler(args, component)).catch(() => undefined);
|
||||
}
|
||||
|
||||
function dispatchRuntimeCallback(component: SkinPluginComponent, handlerId: string, eventName: string, event: Event, state: Record<string, Scalar>): void {
|
||||
if (!component.runtimeCallbacks) return;
|
||||
const callbackEvent: Record<string, unknown> = { componentId: component.id, handlerId, eventName };
|
||||
if (typeof KeyboardEvent !== "undefined" && event instanceof KeyboardEvent) callbackEvent.key = event.key;
|
||||
const mayReadUserInput = props.extensionPermissions.includes("ui.input.read");
|
||||
if (mayReadUserInput && (eventName === "input" || eventName === "change") && event.target instanceof HTMLInputElement) {
|
||||
if (["password", "file", "hidden"].includes(event.target.type)) return;
|
||||
if (event.target.type === "checkbox") callbackEvent.checked = event.target.checked;
|
||||
else if (event.target.value.length <= 2_048) callbackEvent.value = event.target.value;
|
||||
} else if (mayReadUserInput && (eventName === "input" || eventName === "change") && event.target instanceof HTMLTextAreaElement) {
|
||||
if (event.target.value.length <= 2_048) callbackEvent.value = event.target.value;
|
||||
} else if (mayReadUserInput && (eventName === "input" || eventName === "change") && event.target instanceof HTMLSelectElement
|
||||
&& event.target.value.length <= 2_048) {
|
||||
callbackEvent.value = event.target.value;
|
||||
}
|
||||
try {
|
||||
const input = parseSkinExtensionUiInput({ schemaVersion: 1, state: { ...state }, event: callbackEvent });
|
||||
emit("extension-event", { skinId: props.skinId, componentId: component.id, input });
|
||||
} catch {
|
||||
// Overlarge or malformed local state stays local and is not passed to the extension guest.
|
||||
}
|
||||
}
|
||||
|
||||
function assetUrl(path: string): string | undefined {
|
||||
return assetUrls.resolve(path, props.assets);
|
||||
}
|
||||
|
||||
function layoutComponentPath(component: SkinPluginComponent): string {
|
||||
return props.componentNamespace ? `runtime_plugin_${props.componentNamespace}__${component.id}` : component.id;
|
||||
}
|
||||
|
||||
function layoutPart(component: SkinPluginComponent, node: SkinPluginNode, nodePath: string): string {
|
||||
const interactive = ["a", "button", "input", "select", "summary", "textarea"].includes(node.tag ?? "")
|
||||
|| node.widget === "voice.screen-share-start"
|
||||
|| node.attributes?.role === "button"
|
||||
|| ["click", "dblclick", "contextmenu", "keydown", "keyup", "pointerdown", "pointerup", "drop"]
|
||||
.some((eventName) => Boolean(node.events?.[eventName as keyof typeof node.events]));
|
||||
const part = node.part ? `part-${node.part}` : nodePath;
|
||||
const componentPath = layoutComponentPath(component);
|
||||
return `skin.${component.page}.${componentPath}.${interactive ? "control-" : ""}${part}`;
|
||||
}
|
||||
|
||||
function renderNode(component: SkinPluginComponent, node: SkinPluginNode, context: SafeContext, state: Record<string, Scalar>, budget: { remaining: number }, skipRepeat = false, nodePath = "node-root"): VNodeChild {
|
||||
if (budget.remaining <= 0) return null;
|
||||
budget.remaining -= 1;
|
||||
if (node.widget) {
|
||||
if (node.when) {
|
||||
const value = resolvePath(node.when.path, context, state);
|
||||
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;
|
||||
return h("div", {
|
||||
class: ["ws-plugin-host-widget", node.className],
|
||||
"data-ws-plugin-widget": node.widget,
|
||||
"data-ws-plugin-part": node.part ? `${component.id}.${node.part}` : component.id,
|
||||
"data-ws-part": layoutPart(component, node, nodePath),
|
||||
"aria-label": component.accessibleName,
|
||||
}, [widget(node.options)]);
|
||||
}
|
||||
if (!node.tag) {
|
||||
const text = interpolate(node.text ?? "", context, state);
|
||||
return node.part ? h("span", {
|
||||
class: "ws-plugin-node",
|
||||
"data-ws-plugin-part": `${component.id}.${node.part}`,
|
||||
"data-ws-part": layoutPart(component, node, nodePath),
|
||||
}, text) : text;
|
||||
}
|
||||
if (!skipRepeat && node.repeat) {
|
||||
const values = resolvePath(node.repeat.path, context, state);
|
||||
if (!Array.isArray(values)) return null;
|
||||
const repeatLimit = props.document.schemaVersion >= 3 ? SKIN_PLUGIN_REPEAT_LIMIT : 100;
|
||||
return h(Fragment, null, values.slice(0, repeatLimit).map((value) => renderNode(component, node, { ...context, [node.repeat!.as]: value }, state, budget, true, nodePath)));
|
||||
}
|
||||
if (node.when) {
|
||||
const value = resolvePath(node.when.path, context, state);
|
||||
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) {
|
||||
const url = assetUrl(node.asset);
|
||||
if (url) attrs.src = url;
|
||||
}
|
||||
if (node.className || attrs.class) {
|
||||
attrs.class = ["ws-plugin-node", node.className, attrs.class].filter(Boolean).join(" ");
|
||||
} else attrs.class = "ws-plugin-node";
|
||||
const componentPath = props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id;
|
||||
attrs["data-ws-plugin-part"] = node.part ? `${componentPath}.${node.part}` : componentPath;
|
||||
attrs["data-ws-part"] = layoutPart(component, node, nodePath);
|
||||
if (node.bindValue) attrs.value = state[node.bindValue];
|
||||
|
||||
for (const [eventName, actionId] of Object.entries(node.events ?? {})) {
|
||||
const propName = eventProps[eventName];
|
||||
if (!propName) continue;
|
||||
attrs[propName] = (event: Event) => {
|
||||
if (!event.isTrusted) return;
|
||||
if (!component.runtimeCallbacks && (eventName === "keydown" || eventName === "keyup") && event instanceof KeyboardEvent
|
||||
&& event.key !== "Enter" && event.key !== " " && event.key !== "Escape") return;
|
||||
if (eventName === "contextmenu" || eventName === "dragover") event.preventDefault();
|
||||
if (node.bindValue && eventName === "input" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)) {
|
||||
state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value;
|
||||
} else if (node.bindValue && eventName === "change" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLSelectElement || event.target instanceof HTMLTextAreaElement)) {
|
||||
state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value;
|
||||
}
|
||||
if (eventName === "submit") event.preventDefault();
|
||||
if (component.runtimeCallbacks) dispatchRuntimeCallback(component, actionId, eventName, event, state);
|
||||
else dispatch(component, actionId, context, state);
|
||||
};
|
||||
}
|
||||
if (node.bindValue && !node.events?.input && !node.events?.change) {
|
||||
attrs[node.tag === "input" ? "onInput" : "onChange"] = (event: Event) => {
|
||||
if (!event.isTrusted) return;
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLInputElement) state[node.bindValue!] = target.type === "checkbox" ? target.checked : target.value;
|
||||
else if (target instanceof HTMLTextAreaElement) state[node.bindValue!] = target.value;
|
||||
else if (target instanceof HTMLSelectElement) state[node.bindValue!] = target.value;
|
||||
};
|
||||
}
|
||||
if (node.tag === "form" && !node.events?.submit) attrs.onSubmit = (event: Event) => event.preventDefault();
|
||||
const children = (node.children ?? []).map((child, index) => renderNode(component, child, context, state, budget, false, `${nodePath}-${index}`));
|
||||
// Custom element names are inert host-rendered placeholders. Never instantiate a page-registered
|
||||
// custom element from generated output, since its connectedCallback would run with page privileges.
|
||||
const tag = node.tag.includes("-") ? "div" : node.tag;
|
||||
if (tag !== node.tag) attrs["data-ws-generated-element"] = node.tag;
|
||||
return h(tag, attrs, children);
|
||||
}
|
||||
|
||||
function accept(): void {
|
||||
approveSkinPluginComponents(props.skinId, props.skinVersion, pendingApproval.value);
|
||||
denied.value = false;
|
||||
manageOpen.value = false;
|
||||
refresh.value += 1;
|
||||
}
|
||||
|
||||
function openAccessManager(): void {
|
||||
denied.value = false;
|
||||
manageOpen.value = true;
|
||||
}
|
||||
|
||||
function closeOrDisable(): void {
|
||||
if (pendingApproval.value.length) denied.value = true;
|
||||
manageOpen.value = false;
|
||||
}
|
||||
|
||||
function revokeAll(): void {
|
||||
revokeSkinPluginApprovals(props.skinId);
|
||||
denied.value = true;
|
||||
manageOpen.value = false;
|
||||
refresh.value += 1;
|
||||
}
|
||||
|
||||
onUnmounted(() => assetUrls.clear());
|
||||
|
||||
return () => {
|
||||
const nodes: VNodeChild[] = renderedComponents.value.map((component) => h("div", {
|
||||
key: `${props.skinId}:${component.id}`,
|
||||
class: ["ws-plugin-component", component.mode === "surface" && "ws-plugin-surface"],
|
||||
"data-ws-plugin-component": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-plugin-name": component.name,
|
||||
"data-ws-plugin-part": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-part": `skin.${component.page}.${layoutComponentPath(component)}`,
|
||||
...(props.componentNamespace ? { "data-ws-runtime-plugin": props.componentNamespace } : {}),
|
||||
...(component.mode === "surface" ? { "data-ws-plugin-surface": component.page } : {}),
|
||||
"aria-label": component.accessibleName,
|
||||
}
|
||||
if (!node.tag) {
|
||||
const text = interpolate(node.text ?? "", context, state);
|
||||
return node.part ? h("span", {
|
||||
class: "ws-plugin-node",
|
||||
"data-ws-plugin-part": `${component.id}.${node.part}`,
|
||||
"data-ws-part": layoutPart(component, node, nodePath),
|
||||
}, text) : text;
|
||||
}
|
||||
if (!skipRepeat && node.repeat) {
|
||||
const values = resolvePath(node.repeat.path, context, state);
|
||||
if (!Array.isArray(values)) return null;
|
||||
const repeatLimit = props.document.schemaVersion >= 3 ? SKIN_PLUGIN_REPEAT_LIMIT : 100;
|
||||
return h(Fragment, null, values.slice(0, repeatLimit).map((value) => renderNode(component, node, { ...context, [node.repeat!.as]: value }, state, budget, true, nodePath)));
|
||||
}
|
||||
if (node.when) {
|
||||
const value = resolvePath(node.when.path, context, state);
|
||||
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) {
|
||||
const url = assetUrl(node.asset);
|
||||
if (url) attrs.src = url;
|
||||
}
|
||||
if (node.className || attrs.class) {
|
||||
attrs.class = ["ws-plugin-node", node.className, attrs.class].filter(Boolean).join(" ");
|
||||
} else attrs.class = "ws-plugin-node";
|
||||
const componentPath = props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id;
|
||||
attrs["data-ws-plugin-part"] = node.part ? `${componentPath}.${node.part}` : componentPath;
|
||||
attrs["data-ws-part"] = layoutPart(component, node, nodePath);
|
||||
if (node.bindValue) attrs.value = state[node.bindValue];
|
||||
|
||||
for (const [eventName, actionId] of Object.entries(node.events ?? {})) {
|
||||
const propName = eventProps[eventName];
|
||||
if (!propName) continue;
|
||||
attrs[propName] = (event: Event) => {
|
||||
if (!event.isTrusted) return;
|
||||
if (!component.runtimeCallbacks && (eventName === "keydown" || eventName === "keyup") && event instanceof KeyboardEvent
|
||||
&& event.key !== "Enter" && event.key !== " " && event.key !== "Escape") return;
|
||||
if (eventName === "contextmenu" || eventName === "dragover") event.preventDefault();
|
||||
if (node.bindValue && eventName === "input" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement)) {
|
||||
state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value;
|
||||
} else if (node.bindValue && eventName === "change" && (event.target instanceof HTMLInputElement || event.target instanceof HTMLSelectElement || event.target instanceof HTMLTextAreaElement)) {
|
||||
state[node.bindValue] = event.target instanceof HTMLInputElement && event.target.type === "checkbox" ? event.target.checked : event.target.value;
|
||||
}
|
||||
if (eventName === "submit") event.preventDefault();
|
||||
if (component.runtimeCallbacks) dispatchRuntimeCallback(component, actionId, eventName, event, state);
|
||||
else dispatch(component, actionId, context, state);
|
||||
};
|
||||
}
|
||||
if (node.bindValue && !node.events?.input && !node.events?.change) {
|
||||
attrs[node.tag === "input" ? "onInput" : "onChange"] = (event: Event) => {
|
||||
if (!event.isTrusted) return;
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLInputElement) state[node.bindValue!] = target.type === "checkbox" ? target.checked : target.value;
|
||||
else if (target instanceof HTMLTextAreaElement) state[node.bindValue!] = target.value;
|
||||
else if (target instanceof HTMLSelectElement) state[node.bindValue!] = target.value;
|
||||
};
|
||||
}
|
||||
if (node.tag === "form" && !node.events?.submit) attrs.onSubmit = (event: Event) => event.preventDefault();
|
||||
const children = (node.children ?? []).map((child, index) => renderNode(component, child, context, state, budget, false, `${nodePath}-${index}`));
|
||||
// Custom element names are inert host-rendered placeholders. Never instantiate a page-registered
|
||||
// custom element from generated output, since its connectedCallback would run with page privileges.
|
||||
const tag = node.tag.includes("-") ? "div" : node.tag;
|
||||
if (tag !== node.tag) attrs["data-ws-generated-element"] = node.tag;
|
||||
return h(tag, attrs, children);
|
||||
}
|
||||
|
||||
function accept(): void {
|
||||
approveSkinPluginComponents(props.skinId, props.skinVersion, pendingApproval.value);
|
||||
denied.value = false;
|
||||
manageOpen.value = false;
|
||||
refresh.value += 1;
|
||||
}
|
||||
|
||||
function openAccessManager(): void {
|
||||
denied.value = false;
|
||||
manageOpen.value = true;
|
||||
}
|
||||
|
||||
function closeOrDisable(): void {
|
||||
if (pendingApproval.value.length) denied.value = true;
|
||||
manageOpen.value = false;
|
||||
}
|
||||
|
||||
function revokeAll(): void {
|
||||
revokeSkinPluginApprovals(props.skinId);
|
||||
denied.value = true;
|
||||
manageOpen.value = false;
|
||||
refresh.value += 1;
|
||||
}
|
||||
|
||||
onUnmounted(() => assetUrls.clear());
|
||||
|
||||
return () => {
|
||||
const nodes: VNodeChild[] = renderedComponents.value.map((component) => h("div", {
|
||||
key: `${props.skinId}:${component.id}`,
|
||||
class: ["ws-plugin-component", component.mode === "surface" && "ws-plugin-surface"],
|
||||
"data-ws-plugin-component": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-plugin-name": component.name,
|
||||
"data-ws-plugin-part": props.componentNamespace ? `${props.componentNamespace}.${component.id}` : component.id,
|
||||
"data-ws-part": `skin.${component.page}.${layoutComponentPath(component)}`,
|
||||
...(props.componentNamespace ? { "data-ws-runtime-plugin": props.componentNamespace } : {}),
|
||||
...(component.mode === "surface" ? { "data-ws-plugin-surface": component.page } : {}),
|
||||
"aria-label": component.accessibleName,
|
||||
}, [renderNode(component, component.root, props.data, localState(component, props.data), { remaining: SKIN_PLUGIN_RENDER_NODE_LIMIT })]));
|
||||
const hasPermissions = matchingComponents.value.some((component) => component.permissions.length > 0);
|
||||
const showConsent = pendingApproval.value.length > 0 || manageOpen.value;
|
||||
const accessToggle = hasPermissions ? h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-access-toggle",
|
||||
"aria-label": "管理皮肤组件权限 / Manage skin component access",
|
||||
onClick: openAccessManager,
|
||||
}, "权限 / Access")]) : null;
|
||||
const surfaceRecovery = activeSurface.value && props.manageSurfaceRecovery ? h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-recovery",
|
||||
"aria-label": "返回 WebSpeak 标准界面 / Return to the built-in interface",
|
||||
onClick: () => { surfaceSuppressed.value = true; },
|
||||
}, "标准界面 / Built-in UI")]) : null;
|
||||
const skinRecovery = activeSurface.value && props.manageSurfaceRecovery ? h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-reset",
|
||||
"aria-label": "恢复内置皮肤 / Restore the built-in skin",
|
||||
onClick: () => emit("restore-skin"),
|
||||
}, "恢复内置皮肤 / Reset skin")]) : null;
|
||||
const recoveryControls = [
|
||||
...(surfaceRecovery ? [surfaceRecovery] : []),
|
||||
...(skinRecovery ? [skinRecovery] : []),
|
||||
];
|
||||
if (!showConsent) return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : []), ...recoveryControls]);
|
||||
|
||||
const requested = accessComponents.value;
|
||||
const hasMissing = pendingApproval.value.length > 0;
|
||||
const consent = h(Teleport, { to: "body" }, [h("div", { class: "ws-plugin-consent-backdrop", "data-ws-plugin-consent": "true" }, [
|
||||
h("section", { class: "ws-plugin-consent", role: "dialog", "aria-modal": "true", "aria-labelledby": "ws-plugin-consent-title" }, [
|
||||
h("h2", { id: "ws-plugin-consent-title" }, "皮肤组件权限 / Skin component access"),
|
||||
h("p", null, "此皮肤包含会读取公开语音界面数据或请求宿主动作的组件。只有你批准的组件才会启用。/ This skin requests limited access for its components. Only approved components will run."),
|
||||
...requested.map((component) => h("div", { class: "ws-plugin-consent-item", key: component.id }, [
|
||||
h("strong", null, component.name),
|
||||
h("ul", null, component.permissions.map((permission) => h("li", { key: permission }, permissionLabel(permission)))),
|
||||
])),
|
||||
h("p", { class: "ws-plugin-consent-note" }, "页面可以替换公开客户端外观;内置控件仍由 WebSpeak 处理。皮肤不能运行脚本、访问网络或存储,也不能读取连接地址、密码和身份材料。/ A surface can replace the public client UI while built-in controls remain host-owned. Skins cannot run code, access network or storage, or read connection targets, passwords, or identity material."),
|
||||
h("div", { class: "ws-plugin-consent-actions" }, [
|
||||
...(hasMissing ? [h("button", { type: "button", class: "secondary", onClick: closeOrDisable }, "暂不启用 / Keep disabled")]
|
||||
: [h("button", { type: "button", class: "secondary", onClick: revokeAll }, "撤销全部授权 / Revoke all access")]),
|
||||
h("button", { type: "button", class: "primary", onClick: hasMissing ? accept : () => { manageOpen.value = false; } }, hasMissing ? "批准所列权限 / Approve listed access" : "关闭 / Close"),
|
||||
]),
|
||||
]),
|
||||
])]);
|
||||
return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : []), ...recoveryControls, consent]);
|
||||
};
|
||||
},
|
||||
});
|
||||
const hasPermissions = matchingComponents.value.some((component) => component.permissions.length > 0);
|
||||
const showConsent = (PROMPT_FOR_SKIN_PERMISSIONS && pendingApproval.value.length > 0) || manageOpen.value;
|
||||
const accessToggle = hasPermissions && editorMode.isEnabled.value ? h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-access-toggle",
|
||||
"aria-label": "管理皮肤组件权限 / Manage skin component access",
|
||||
onClick: openAccessManager,
|
||||
}, "权限 / Access")]) : null;
|
||||
const surfaceRecovery = activeSurface.value && props.manageSurfaceRecovery && editorMode.isEnabled.value ? h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-recovery",
|
||||
"aria-label": "返回 WebSpeak 标准界面 / Return to the built-in interface",
|
||||
onClick: () => { surfaceSuppressed.value = true; },
|
||||
}, "标准界面 / Built-in UI")]) : null;
|
||||
const skinRecovery = activeSurface.value && props.manageSurfaceRecovery && editorMode.isEnabled.value ? h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-reset",
|
||||
"aria-label": "恢复内置皮肤 / Restore the built-in skin",
|
||||
onClick: () => emit("restore-skin"),
|
||||
}, "恢复内置皮肤 / Reset skin")]) : null;
|
||||
const recoveryControls = [
|
||||
...(surfaceRecovery ? [surfaceRecovery] : []),
|
||||
...(skinRecovery ? [skinRecovery] : []),
|
||||
];
|
||||
if (!showConsent) return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : []), ...recoveryControls]);
|
||||
|
||||
const requested = accessComponents.value;
|
||||
const hasMissing = PROMPT_FOR_SKIN_PERMISSIONS && pendingApproval.value.length > 0;
|
||||
const consent = h(Teleport, { to: "body" }, [h("div", { class: "ws-plugin-consent-backdrop", "data-ws-plugin-consent": "true" }, [
|
||||
h("section", { class: "ws-plugin-consent", role: "dialog", "aria-modal": "true", "aria-labelledby": "ws-plugin-consent-title" }, [
|
||||
h("h2", { id: "ws-plugin-consent-title" }, "皮肤组件权限 / Skin component access"),
|
||||
h("p", null, "此皮肤包含会读取公开语音界面数据或请求宿主动作的组件。只有你批准的组件才会启用。/ This skin requests limited access for its components. Only approved components will run."),
|
||||
...requested.map((component) => h("div", { class: "ws-plugin-consent-item", key: component.id }, [
|
||||
h("strong", null, component.name),
|
||||
h("ul", null, component.permissions.map((permission) => h("li", { key: permission }, permissionLabel(permission)))),
|
||||
])),
|
||||
h("p", { class: "ws-plugin-consent-note" }, "页面可以替换公开客户端外观;内置控件仍由 WebSpeak 处理。皮肤不能运行脚本、访问网络或存储,也不能读取连接地址、密码和身份材料。/ A surface can replace the public client UI while built-in controls remain host-owned. Skins cannot run code, access network or storage, or read connection targets, passwords, or identity material."),
|
||||
h("div", { class: "ws-plugin-consent-actions" }, [
|
||||
...(hasMissing ? [h("button", { type: "button", class: "secondary", onClick: closeOrDisable }, "暂不启用 / Keep disabled")]
|
||||
: [h("button", { type: "button", class: "secondary", onClick: revokeAll }, "撤销全部授权 / Revoke all access")]),
|
||||
h("button", { type: "button", class: "primary", onClick: hasMissing ? accept : () => { manageOpen.value = false; } }, hasMissing ? "批准所列权限 / Approve listed access" : "关闭 / Close"),
|
||||
]),
|
||||
]),
|
||||
])]);
|
||||
return h(Fragment, null, [...nodes, ...(accessToggle ? [accessToggle] : []), ...recoveryControls, consent]);
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -1,456 +1,461 @@
|
||||
import { computed, defineComponent, h, nextTick, onMounted, onUnmounted, ref, shallowRef, Teleport, watch, type PropType, type VNodeChild } from "vue";
|
||||
import type { SkinExtensionSessionStatus } from "../../../src/shared/skin-extension.js";
|
||||
import { computeSkinRuntimePluginDigest, createSkinRuntimePluginApproval, isSkinRuntimePluginApproved, type SkinRuntimePluginApproval } from "../../../src/shared/skin-runtime-plugin-approval.js";
|
||||
import type { SkinRuntimePlugin, SkinRuntimePluginDocument, SkinRuntimePluginPage } from "../../../src/shared/skin-runtime-plugins.js";
|
||||
import { parseSkinExtensionUiInput, type SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
|
||||
import { computed, defineComponent, h, nextTick, onMounted, onUnmounted, ref, shallowRef, Teleport, watch, type PropType, type VNodeChild } from "vue";
|
||||
import type { SkinExtensionSessionStatus } from "../../../src/shared/skin-extension.js";
|
||||
import { computeSkinRuntimePluginDigest, createSkinRuntimePluginApproval, isSkinRuntimePluginApproved, type SkinRuntimePluginApproval } from "../../../src/shared/skin-runtime-plugin-approval.js";
|
||||
import type { SkinRuntimePlugin, SkinRuntimePluginDocument, SkinRuntimePluginPage } from "../../../src/shared/skin-runtime-plugins.js";
|
||||
import { parseSkinExtensionUiInput, type SkinExtensionUiInput } from "../../../src/shared/skin-extension-ui-input.js";
|
||||
import { SKIN_PLUGIN_ACTION_PERMISSIONS, SKIN_PLUGIN_PERMISSIONS, skinPluginActionPermission, type SkinPluginAction, type SkinPluginDocument, type SkinPluginHostWidget, type SkinPluginWidgetOptions } from "../../../src/shared/skin-plugin.js";
|
||||
import { SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS } from "../../../src/shared/skin-runtime-plugin-context.js";
|
||||
import SkinPluginOutlet from "./SkinPluginOutlet.js";
|
||||
import { approveSkinRuntimePlugin, getSkinRuntimePluginApproval, revokeSkinRuntimePluginApprovals } from "../services/skin-runtime-plugin-approval.js";
|
||||
import { createSkinRuntimePluginSession } from "../services/skin-runtime-plugin-session.js";
|
||||
import { createSkinRuntimePluginWasmSandbox } from "../services/skin-runtime-plugin-wasm.js";
|
||||
import { skinRuntimePluginWasmGovernor } from "../services/skin-runtime-plugin-wasm-governor.js";
|
||||
import type { SkinExtensionWasmSandboxHandle } from "../services/skin-extension-wasm-sandbox.js";
|
||||
import { resolveSkinCssAssets } from "../services/skin-pack.js";
|
||||
|
||||
const EMPTY_DOCUMENT: SkinPluginDocument = { schemaVersion: 3, components: [] };
|
||||
const SUPPORTED_PERMISSIONS = new Set([
|
||||
...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS,
|
||||
...SKIN_PLUGIN_ACTION_PERMISSIONS,
|
||||
"ui.surface.replace",
|
||||
"ui.input.read",
|
||||
]);
|
||||
type HostActionHandler = (args: Record<string, string | number | boolean>) => void | Promise<void>;
|
||||
|
||||
type Session = ReturnType<typeof createSkinRuntimePluginSession>;
|
||||
type RunHandle = { result: Promise<{ uiOutput: string | null }>; close(reason?: string): void };
|
||||
|
||||
function isSupported(plugin: SkinRuntimePlugin): boolean {
|
||||
return plugin.runtime === "wasm"
|
||||
&& plugin.permissions.every((permission) => SUPPORTED_PERMISSIONS.has(permission));
|
||||
}
|
||||
|
||||
function pluginReason(plugin: SkinRuntimePlugin): string {
|
||||
if (plugin.runtime !== "wasm") return "JavaScript plugins are not enabled. / JavaScript 插件尚未启用。";
|
||||
const permission = plugin.permissions.find((candidate) => !SUPPORTED_PERMISSIONS.has(candidate));
|
||||
return permission
|
||||
? `This runtime does not implement ${permission}. / 当前运行时尚未实现 ${permission}。`
|
||||
: "";
|
||||
}
|
||||
|
||||
function createRun(
|
||||
skinId: string,
|
||||
skinVersion: string,
|
||||
plugin: SkinRuntimePlugin,
|
||||
approval: SkinRuntimePluginApproval,
|
||||
files: Readonly<Record<string, Blob>>,
|
||||
context: unknown,
|
||||
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>,
|
||||
input: SkinExtensionUiInput,
|
||||
): RunHandle {
|
||||
let sandbox: SkinExtensionWasmSandboxHandle | null = null;
|
||||
let cancelled = false;
|
||||
let releaseSlot: (() => void) | null = null;
|
||||
const abortController = new AbortController();
|
||||
const result = (async () => {
|
||||
releaseSlot = await skinRuntimePluginWasmGovernor.acquire(abortController.signal);
|
||||
try {
|
||||
if (cancelled) throw new Error("Plugin run was closed before startup.");
|
||||
const nextSandbox = await createSkinRuntimePluginWasmSandbox({
|
||||
skinId,
|
||||
skinVersion,
|
||||
plugin,
|
||||
approval,
|
||||
files,
|
||||
uiInput: input,
|
||||
context,
|
||||
readSessionStatus,
|
||||
});
|
||||
if (cancelled) {
|
||||
nextSandbox.close("page-or-skin-changed");
|
||||
throw new Error("Plugin run was closed before startup.");
|
||||
}
|
||||
sandbox = nextSandbox;
|
||||
await nextSandbox.ready;
|
||||
const outcome = await nextSandbox.result;
|
||||
return { uiOutput: outcome.uiOutput };
|
||||
} finally {
|
||||
releaseSlot?.();
|
||||
releaseSlot = null;
|
||||
}
|
||||
})();
|
||||
return {
|
||||
result,
|
||||
close(reason) {
|
||||
cancelled = true;
|
||||
abortController.abort(reason);
|
||||
sandbox?.close(reason);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: "SkinRuntimePluginHost",
|
||||
props: {
|
||||
skinId: { type: String, required: true },
|
||||
skinVersion: { type: String, required: true },
|
||||
plugins: { type: Object as PropType<SkinRuntimePluginDocument | undefined>, default: undefined },
|
||||
files: { type: Object as PropType<Record<string, Blob>>, default: () => ({}) },
|
||||
styles: { type: Object as PropType<Record<string, string>>, default: () => ({}) },
|
||||
assets: { type: Object as PropType<Record<string, Blob>>, default: () => ({}) },
|
||||
page: { type: String as PropType<SkinRuntimePluginPage>, required: true },
|
||||
mountRevision: { type: String, default: "" },
|
||||
context: { type: Object as PropType<Record<string, unknown>>, default: () => ({}) },
|
||||
actions: { type: Object as PropType<Partial<Record<SkinPluginAction, HostActionHandler>>>, default: () => ({}) },
|
||||
import { PROMPT_FOR_SKIN_PERMISSIONS } from "../services/skin-permission-policy.js";
|
||||
import { useSkinEditorMode } from "../services/skin-editor-mode.js";
|
||||
import { createSkinRuntimePluginSession } from "../services/skin-runtime-plugin-session.js";
|
||||
import { createSkinRuntimePluginWasmSandbox } from "../services/skin-runtime-plugin-wasm.js";
|
||||
import { skinRuntimePluginWasmGovernor } from "../services/skin-runtime-plugin-wasm-governor.js";
|
||||
import type { SkinExtensionWasmSandboxHandle } from "../services/skin-extension-wasm-sandbox.js";
|
||||
import { resolveSkinCssAssets } from "../services/skin-pack.js";
|
||||
|
||||
const EMPTY_DOCUMENT: SkinPluginDocument = { schemaVersion: 3, components: [] };
|
||||
const SUPPORTED_PERMISSIONS = new Set([
|
||||
...SKIN_RUNTIME_PLUGIN_DATA_PERMISSIONS,
|
||||
...SKIN_PLUGIN_ACTION_PERMISSIONS,
|
||||
"ui.surface.replace",
|
||||
"ui.input.read",
|
||||
]);
|
||||
type HostActionHandler = (args: Record<string, string | number | boolean>) => void | Promise<void>;
|
||||
|
||||
type Session = ReturnType<typeof createSkinRuntimePluginSession>;
|
||||
type RunHandle = { result: Promise<{ uiOutput: string | null }>; close(reason?: string): void };
|
||||
|
||||
function isSupported(plugin: SkinRuntimePlugin): boolean {
|
||||
return plugin.runtime === "wasm"
|
||||
&& plugin.permissions.every((permission) => SUPPORTED_PERMISSIONS.has(permission));
|
||||
}
|
||||
|
||||
function pluginReason(plugin: SkinRuntimePlugin): string {
|
||||
if (plugin.runtime !== "wasm") return "JavaScript plugins are not enabled. / JavaScript 插件尚未启用。";
|
||||
const permission = plugin.permissions.find((candidate) => !SUPPORTED_PERMISSIONS.has(candidate));
|
||||
return permission
|
||||
? `This runtime does not implement ${permission}. / 当前运行时尚未实现 ${permission}。`
|
||||
: "";
|
||||
}
|
||||
|
||||
function createRun(
|
||||
skinId: string,
|
||||
skinVersion: string,
|
||||
plugin: SkinRuntimePlugin,
|
||||
approval: SkinRuntimePluginApproval,
|
||||
files: Readonly<Record<string, Blob>>,
|
||||
context: unknown,
|
||||
readSessionStatus: (signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>,
|
||||
input: SkinExtensionUiInput,
|
||||
): RunHandle {
|
||||
let sandbox: SkinExtensionWasmSandboxHandle | null = null;
|
||||
let cancelled = false;
|
||||
let releaseSlot: (() => void) | null = null;
|
||||
const abortController = new AbortController();
|
||||
const result = (async () => {
|
||||
releaseSlot = await skinRuntimePluginWasmGovernor.acquire(abortController.signal);
|
||||
try {
|
||||
if (cancelled) throw new Error("Plugin run was closed before startup.");
|
||||
const nextSandbox = await createSkinRuntimePluginWasmSandbox({
|
||||
skinId,
|
||||
skinVersion,
|
||||
plugin,
|
||||
approval,
|
||||
files,
|
||||
uiInput: input,
|
||||
context,
|
||||
readSessionStatus,
|
||||
});
|
||||
if (cancelled) {
|
||||
nextSandbox.close("page-or-skin-changed");
|
||||
throw new Error("Plugin run was closed before startup.");
|
||||
}
|
||||
sandbox = nextSandbox;
|
||||
await nextSandbox.ready;
|
||||
const outcome = await nextSandbox.result;
|
||||
return { uiOutput: outcome.uiOutput };
|
||||
} finally {
|
||||
releaseSlot?.();
|
||||
releaseSlot = null;
|
||||
}
|
||||
})();
|
||||
return {
|
||||
result,
|
||||
close(reason) {
|
||||
cancelled = true;
|
||||
abortController.abort(reason);
|
||||
sandbox?.close(reason);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default defineComponent({
|
||||
name: "SkinRuntimePluginHost",
|
||||
props: {
|
||||
skinId: { type: String, required: true },
|
||||
skinVersion: { type: String, required: true },
|
||||
plugins: { type: Object as PropType<SkinRuntimePluginDocument | undefined>, default: undefined },
|
||||
files: { type: Object as PropType<Record<string, Blob>>, default: () => ({}) },
|
||||
styles: { type: Object as PropType<Record<string, string>>, default: () => ({}) },
|
||||
assets: { type: Object as PropType<Record<string, Blob>>, default: () => ({}) },
|
||||
page: { type: String as PropType<SkinRuntimePluginPage>, required: true },
|
||||
mountRevision: { type: String, default: "" },
|
||||
context: { type: Object as PropType<Record<string, unknown>>, default: () => ({}) },
|
||||
actions: { type: Object as PropType<Partial<Record<SkinPluginAction, HostActionHandler>>>, default: () => ({}) },
|
||||
widgets: { type: Object as PropType<Partial<Record<SkinPluginHostWidget, (options?: SkinPluginWidgetOptions) => VNodeChild>>>, default: () => ({}) },
|
||||
readSessionStatus: { type: Function as PropType<(signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>>, required: true },
|
||||
},
|
||||
emits: {
|
||||
"surface-change": (_active: boolean) => typeof _active === "boolean",
|
||||
"restore-skin": () => true,
|
||||
readSessionStatus: { type: Function as PropType<(signal: AbortSignal) => SkinExtensionSessionStatus | Promise<SkinExtensionSessionStatus>>, required: true },
|
||||
},
|
||||
emits: {
|
||||
"surface-change": (_active: boolean) => typeof _active === "boolean",
|
||||
"restore-skin": () => true,
|
||||
},
|
||||
setup(props, { emit }) {
|
||||
const editorMode = useSkinEditorMode();
|
||||
const digests = ref<Record<string, string>>({});
|
||||
const digestErrors = ref<Record<string, string>>({});
|
||||
const revision = ref(0);
|
||||
const managerOpen = ref(false);
|
||||
const denied = ref(new Set<string>());
|
||||
const inMemoryApprovals = new Map<string, SkinRuntimePluginApproval>();
|
||||
const sessions = new Map<string, Session>();
|
||||
const stylesByPlugin = new Map<string, { element: HTMLStyleElement; objectUrls: string[] }>();
|
||||
const outputs = ref<Record<string, string | null>>({});
|
||||
const surfaces = ref(new Set<string>());
|
||||
const suppressedSurfaces = ref(new Set<string>());
|
||||
const mountTargets = shallowRef<Record<string, Element>>({});
|
||||
let digestRun = 0;
|
||||
let disposed = false;
|
||||
let contextRefreshTimer: number | undefined;
|
||||
|
||||
const pagePlugins = computed(() => props.plugins?.plugins.filter((plugin) => plugin.page === props.page) ?? []);
|
||||
const approved = (plugin: SkinRuntimePlugin): SkinRuntimePluginApproval | null => {
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) return null;
|
||||
const memoryGrant = inMemoryApprovals.get(plugin.id);
|
||||
if (memoryGrant && isSkinRuntimePluginApproved(memoryGrant, props.skinId, props.skinVersion, plugin, digest)) return memoryGrant;
|
||||
return getSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest);
|
||||
};
|
||||
const pending = computed(() => {
|
||||
revision.value;
|
||||
return pagePlugins.value.filter((plugin) => isSupported(plugin) && !approved(plugin) && !denied.value.has(plugin.id));
|
||||
});
|
||||
const activeSurface = computed(() => pagePlugins.value.some((plugin) => plugin.mode === "surface"
|
||||
&& surfaces.value.has(plugin.id) && !suppressedSurfaces.value.has(plugin.id)));
|
||||
|
||||
function refreshMountTargets(): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const targets: Record<string, Element> = Object.create(null) as Record<string, Element>;
|
||||
for (const plugin of pagePlugins.value) {
|
||||
if (!plugin.mount) continue;
|
||||
const target = document.querySelector(`[data-ws-skin-mount="${plugin.mount}"]`);
|
||||
if (target) targets[plugin.id] = target;
|
||||
}
|
||||
mountTargets.value = targets;
|
||||
}
|
||||
|
||||
function publishSurfaceState(): void {
|
||||
emit("surface-change", activeSurface.value);
|
||||
}
|
||||
|
||||
function removeStyle(pluginId: string): void {
|
||||
const style = stylesByPlugin.get(pluginId);
|
||||
if (!style) return;
|
||||
style.element.remove();
|
||||
style.objectUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
stylesByPlugin.delete(pluginId);
|
||||
}
|
||||
|
||||
function stopPlugin(pluginId: string, reason: string): void {
|
||||
sessions.get(pluginId)?.close(reason);
|
||||
sessions.delete(pluginId);
|
||||
outputs.value = { ...outputs.value, [pluginId]: null };
|
||||
surfaces.value.delete(pluginId);
|
||||
suppressedSurfaces.value.delete(pluginId);
|
||||
removeStyle(pluginId);
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
function stopAll(reason: string): void {
|
||||
if (contextRefreshTimer !== undefined) {
|
||||
window.clearTimeout(contextRefreshTimer);
|
||||
contextRefreshTimer = undefined;
|
||||
}
|
||||
for (const pluginId of [...sessions.keys()]) stopPlugin(pluginId, reason);
|
||||
for (const pluginId of [...stylesByPlugin.keys()]) removeStyle(pluginId);
|
||||
outputs.value = {};
|
||||
surfaces.value = new Set();
|
||||
suppressedSurfaces.value = new Set();
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
function pluginStyleAssets(plugin: SkinRuntimePlugin): Record<string, Blob> {
|
||||
const ownPrefix = `plugins/${plugin.id}/assets/`;
|
||||
return Object.fromEntries(Object.entries(props.assets).filter(([path]) => path.startsWith("assets/") || path.startsWith(ownPrefix)));
|
||||
}
|
||||
|
||||
function installStyle(plugin: SkinRuntimePlugin): void {
|
||||
removeStyle(plugin.id);
|
||||
const css = props.styles[plugin.id];
|
||||
if (!css) return;
|
||||
const resolved = resolveSkinCssAssets(css, pluginStyleAssets(plugin));
|
||||
const element = document.createElement("style");
|
||||
element.dataset.wsRuntimePluginStyle = plugin.id;
|
||||
element.textContent = resolved.css;
|
||||
document.head.append(element);
|
||||
stylesByPlugin.set(plugin.id, { element, objectUrls: resolved.objectUrls });
|
||||
}
|
||||
|
||||
function outputAssets(plugin: SkinRuntimePlugin): Record<string, Blob> {
|
||||
const result: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
|
||||
const prefix = `plugins/${plugin.id}/assets/`;
|
||||
for (const path of plugin.assets) {
|
||||
const relative = path.slice(prefix.length);
|
||||
const blob = props.assets[path];
|
||||
if (blob) result[`assets/${relative}`] = blob;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function onRuntimeError(pluginId: string): void {
|
||||
if (disposed) return;
|
||||
stopPlugin(pluginId, "runtime-error");
|
||||
digestErrors.value = { ...digestErrors.value, [pluginId]: "The plugin stopped safely. / 插件已安全停止。" };
|
||||
}
|
||||
|
||||
function startPlugin(plugin: SkinRuntimePlugin, grant: SkinRuntimePluginApproval): void {
|
||||
if (sessions.has(plugin.id) || !isSupported(plugin)) return;
|
||||
const session = createSkinRuntimePluginSession({
|
||||
plugin,
|
||||
createRun: (input) => createRun(props.skinId, props.skinVersion, plugin, grant, props.files, props.context, props.readSessionStatus, input),
|
||||
onAction: async (action) => {
|
||||
const permission = skinPluginActionPermission(action.type);
|
||||
const currentGrant = approved(plugin);
|
||||
if (!permission || !plugin.permissions.includes(permission) || !currentGrant
|
||||
|| sessions.get(plugin.id) !== session || disposed) {
|
||||
throw new Error("The plugin action is no longer approved.");
|
||||
}
|
||||
const handler = props.actions[action.type];
|
||||
if (!handler) throw new Error("The host does not provide this action.");
|
||||
await handler(action.args);
|
||||
},
|
||||
onOutput: () => {
|
||||
installStyle(plugin);
|
||||
outputs.value = { ...outputs.value, [plugin.id]: session.output };
|
||||
digestErrors.value = { ...digestErrors.value, [plugin.id]: "" };
|
||||
},
|
||||
onError: () => onRuntimeError(plugin.id),
|
||||
});
|
||||
sessions.set(plugin.id, session);
|
||||
void session.start().then((started) => {
|
||||
if (!started && sessions.get(plugin.id) === session) onRuntimeError(plugin.id);
|
||||
}).catch(() => onRuntimeError(plugin.id));
|
||||
}
|
||||
|
||||
function reconcile(): void {
|
||||
if (disposed) return;
|
||||
const currentIds = new Set(pagePlugins.value.map((plugin) => plugin.id));
|
||||
for (const pluginId of [...sessions.keys()]) if (!currentIds.has(pluginId)) stopPlugin(pluginId, "page-changed");
|
||||
for (const plugin of pagePlugins.value) {
|
||||
const grant = approved(plugin);
|
||||
if (grant && isSupported(plugin)) startPlugin(plugin, grant);
|
||||
}
|
||||
}
|
||||
|
||||
function approvePending(): void {
|
||||
for (const plugin of pending.value) {
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) continue;
|
||||
approveSkinRuntimePlugin(props.skinId, props.skinVersion, plugin, digest);
|
||||
const stored = getSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest);
|
||||
inMemoryApprovals.set(plugin.id, stored ?? createSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest));
|
||||
}
|
||||
denied.value = new Set([...denied.value].filter((id) => !pending.value.some((plugin) => plugin.id === id)));
|
||||
managerOpen.value = false;
|
||||
revision.value += 1;
|
||||
reconcile();
|
||||
}
|
||||
|
||||
function keepDisabled(): void {
|
||||
denied.value = new Set([...denied.value, ...pending.value.map((plugin) => plugin.id)]);
|
||||
managerOpen.value = false;
|
||||
}
|
||||
|
||||
function revokeAll(): void {
|
||||
revokeSkinRuntimePluginApprovals(props.skinId);
|
||||
for (const plugin of props.plugins?.plugins ?? []) inMemoryApprovals.delete(plugin.id);
|
||||
denied.value = new Set((props.plugins?.plugins ?? []).filter(isSupported).map((plugin) => plugin.id));
|
||||
stopAll("approval-revoked");
|
||||
managerOpen.value = false;
|
||||
revision.value += 1;
|
||||
}
|
||||
|
||||
function openManager(): void {
|
||||
managerOpen.value = true;
|
||||
}
|
||||
|
||||
function dispatch(pluginId: string, value: unknown): void {
|
||||
if (!value || typeof value !== "object") return;
|
||||
const input = (value as Record<string, unknown>).input;
|
||||
const session = sessions.get(pluginId);
|
||||
if (session && input) void session.dispatch(input);
|
||||
}
|
||||
|
||||
function surfaceChanged(pluginId: string, active: boolean): void {
|
||||
if (active) surfaces.value.add(pluginId);
|
||||
else surfaces.value.delete(pluginId);
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
function toggleSurface(pluginId: string): void {
|
||||
const next = new Set(suppressedSurfaces.value);
|
||||
if (next.has(pluginId)) next.delete(pluginId);
|
||||
else next.add(pluginId);
|
||||
suppressedSurfaces.value = next;
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
watch(() => [props.skinId, props.skinVersion, props.plugins, props.files], async () => {
|
||||
const currentRun = ++digestRun;
|
||||
stopAll("skin-changed");
|
||||
inMemoryApprovals.clear();
|
||||
denied.value = new Set();
|
||||
managerOpen.value = false;
|
||||
digests.value = {};
|
||||
digestErrors.value = {};
|
||||
const plugins = props.plugins?.plugins ?? [];
|
||||
const nextDigests: Record<string, string> = Object.create(null) as Record<string, string>;
|
||||
const nextErrors: Record<string, string> = Object.create(null) as Record<string, string>;
|
||||
await Promise.all(plugins.map(async (plugin) => {
|
||||
try { nextDigests[plugin.id] = await computeSkinRuntimePluginDigest(plugin, props.files); }
|
||||
catch { nextErrors[plugin.id] = "The package files could not be verified. / 无法校验插件文件。"; }
|
||||
}));
|
||||
if (disposed || currentRun !== digestRun) return;
|
||||
const digestErrors = ref<Record<string, string>>({});
|
||||
const revision = ref(0);
|
||||
const managerOpen = ref(false);
|
||||
const denied = ref(new Set<string>());
|
||||
const inMemoryApprovals = new Map<string, SkinRuntimePluginApproval>();
|
||||
const sessions = new Map<string, Session>();
|
||||
const stylesByPlugin = new Map<string, { element: HTMLStyleElement; objectUrls: string[] }>();
|
||||
const outputs = ref<Record<string, string | null>>({});
|
||||
const surfaces = ref(new Set<string>());
|
||||
const suppressedSurfaces = ref(new Set<string>());
|
||||
const mountTargets = shallowRef<Record<string, Element>>({});
|
||||
let digestRun = 0;
|
||||
let disposed = false;
|
||||
let contextRefreshTimer: number | undefined;
|
||||
|
||||
const pagePlugins = computed(() => props.plugins?.plugins.filter((plugin) => plugin.page === props.page) ?? []);
|
||||
const approved = (plugin: SkinRuntimePlugin): SkinRuntimePluginApproval | null => {
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) return null;
|
||||
const memoryGrant = inMemoryApprovals.get(plugin.id);
|
||||
if (memoryGrant && isSkinRuntimePluginApproved(memoryGrant, props.skinId, props.skinVersion, plugin, digest)) return memoryGrant;
|
||||
return getSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest);
|
||||
};
|
||||
const pending = computed(() => {
|
||||
revision.value;
|
||||
return pagePlugins.value.filter((plugin) => isSupported(plugin) && !approved(plugin) && !denied.value.has(plugin.id));
|
||||
});
|
||||
const activeSurface = computed(() => pagePlugins.value.some((plugin) => plugin.mode === "surface"
|
||||
&& surfaces.value.has(plugin.id) && !suppressedSurfaces.value.has(plugin.id)));
|
||||
|
||||
function refreshMountTargets(): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const targets: Record<string, Element> = Object.create(null) as Record<string, Element>;
|
||||
for (const plugin of pagePlugins.value) {
|
||||
if (!plugin.mount) continue;
|
||||
const target = document.querySelector(`[data-ws-skin-mount="${plugin.mount}"]`);
|
||||
if (target) targets[plugin.id] = target;
|
||||
}
|
||||
mountTargets.value = targets;
|
||||
}
|
||||
|
||||
function publishSurfaceState(): void {
|
||||
emit("surface-change", activeSurface.value);
|
||||
}
|
||||
|
||||
function removeStyle(pluginId: string): void {
|
||||
const style = stylesByPlugin.get(pluginId);
|
||||
if (!style) return;
|
||||
style.element.remove();
|
||||
style.objectUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
stylesByPlugin.delete(pluginId);
|
||||
}
|
||||
|
||||
function stopPlugin(pluginId: string, reason: string): void {
|
||||
sessions.get(pluginId)?.close(reason);
|
||||
sessions.delete(pluginId);
|
||||
outputs.value = { ...outputs.value, [pluginId]: null };
|
||||
surfaces.value.delete(pluginId);
|
||||
suppressedSurfaces.value.delete(pluginId);
|
||||
removeStyle(pluginId);
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
function stopAll(reason: string): void {
|
||||
if (contextRefreshTimer !== undefined) {
|
||||
window.clearTimeout(contextRefreshTimer);
|
||||
contextRefreshTimer = undefined;
|
||||
}
|
||||
for (const pluginId of [...sessions.keys()]) stopPlugin(pluginId, reason);
|
||||
for (const pluginId of [...stylesByPlugin.keys()]) removeStyle(pluginId);
|
||||
outputs.value = {};
|
||||
surfaces.value = new Set();
|
||||
suppressedSurfaces.value = new Set();
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
function pluginStyleAssets(plugin: SkinRuntimePlugin): Record<string, Blob> {
|
||||
const ownPrefix = `plugins/${plugin.id}/assets/`;
|
||||
return Object.fromEntries(Object.entries(props.assets).filter(([path]) => path.startsWith("assets/") || path.startsWith(ownPrefix)));
|
||||
}
|
||||
|
||||
function installStyle(plugin: SkinRuntimePlugin): void {
|
||||
removeStyle(plugin.id);
|
||||
const css = props.styles[plugin.id];
|
||||
if (!css) return;
|
||||
const resolved = resolveSkinCssAssets(css, pluginStyleAssets(plugin));
|
||||
const element = document.createElement("style");
|
||||
element.dataset.wsRuntimePluginStyle = plugin.id;
|
||||
element.textContent = resolved.css;
|
||||
document.head.append(element);
|
||||
stylesByPlugin.set(plugin.id, { element, objectUrls: resolved.objectUrls });
|
||||
}
|
||||
|
||||
function outputAssets(plugin: SkinRuntimePlugin): Record<string, Blob> {
|
||||
const result: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
|
||||
const prefix = `plugins/${plugin.id}/assets/`;
|
||||
for (const path of plugin.assets) {
|
||||
const relative = path.slice(prefix.length);
|
||||
const blob = props.assets[path];
|
||||
if (blob) result[`assets/${relative}`] = blob;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function onRuntimeError(pluginId: string): void {
|
||||
if (disposed) return;
|
||||
stopPlugin(pluginId, "runtime-error");
|
||||
digestErrors.value = { ...digestErrors.value, [pluginId]: "The plugin stopped safely. / 插件已安全停止。" };
|
||||
}
|
||||
|
||||
function startPlugin(plugin: SkinRuntimePlugin, grant: SkinRuntimePluginApproval): void {
|
||||
if (sessions.has(plugin.id) || !isSupported(plugin)) return;
|
||||
const session = createSkinRuntimePluginSession({
|
||||
plugin,
|
||||
createRun: (input) => createRun(props.skinId, props.skinVersion, plugin, grant, props.files, props.context, props.readSessionStatus, input),
|
||||
onAction: async (action) => {
|
||||
const permission = skinPluginActionPermission(action.type);
|
||||
const currentGrant = approved(plugin);
|
||||
if (!permission || !plugin.permissions.includes(permission) || !currentGrant
|
||||
|| sessions.get(plugin.id) !== session || disposed) {
|
||||
throw new Error("The plugin action is no longer approved.");
|
||||
}
|
||||
const handler = props.actions[action.type];
|
||||
if (!handler) throw new Error("The host does not provide this action.");
|
||||
await handler(action.args);
|
||||
},
|
||||
onOutput: () => {
|
||||
installStyle(plugin);
|
||||
outputs.value = { ...outputs.value, [plugin.id]: session.output };
|
||||
digestErrors.value = { ...digestErrors.value, [plugin.id]: "" };
|
||||
},
|
||||
onError: () => onRuntimeError(plugin.id),
|
||||
});
|
||||
sessions.set(plugin.id, session);
|
||||
void session.start().then((started) => {
|
||||
if (!started && sessions.get(plugin.id) === session) onRuntimeError(plugin.id);
|
||||
}).catch(() => onRuntimeError(plugin.id));
|
||||
}
|
||||
|
||||
function reconcile(): void {
|
||||
if (disposed) return;
|
||||
const currentIds = new Set(pagePlugins.value.map((plugin) => plugin.id));
|
||||
for (const pluginId of [...sessions.keys()]) if (!currentIds.has(pluginId)) stopPlugin(pluginId, "page-changed");
|
||||
for (const plugin of pagePlugins.value) {
|
||||
const grant = approved(plugin);
|
||||
if (grant && isSupported(plugin)) startPlugin(plugin, grant);
|
||||
}
|
||||
}
|
||||
|
||||
function approvePending(): void {
|
||||
for (const plugin of pending.value) {
|
||||
const digest = digests.value[plugin.id];
|
||||
if (!digest) continue;
|
||||
approveSkinRuntimePlugin(props.skinId, props.skinVersion, plugin, digest);
|
||||
const stored = getSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest);
|
||||
inMemoryApprovals.set(plugin.id, stored ?? createSkinRuntimePluginApproval(props.skinId, props.skinVersion, plugin, digest));
|
||||
}
|
||||
denied.value = new Set([...denied.value].filter((id) => !pending.value.some((plugin) => plugin.id === id)));
|
||||
managerOpen.value = false;
|
||||
revision.value += 1;
|
||||
reconcile();
|
||||
}
|
||||
|
||||
function keepDisabled(): void {
|
||||
denied.value = new Set([...denied.value, ...pending.value.map((plugin) => plugin.id)]);
|
||||
managerOpen.value = false;
|
||||
}
|
||||
|
||||
function revokeAll(): void {
|
||||
revokeSkinRuntimePluginApprovals(props.skinId);
|
||||
for (const plugin of props.plugins?.plugins ?? []) inMemoryApprovals.delete(plugin.id);
|
||||
denied.value = new Set((props.plugins?.plugins ?? []).filter(isSupported).map((plugin) => plugin.id));
|
||||
stopAll("approval-revoked");
|
||||
managerOpen.value = false;
|
||||
revision.value += 1;
|
||||
}
|
||||
|
||||
function openManager(): void {
|
||||
managerOpen.value = true;
|
||||
}
|
||||
|
||||
function dispatch(pluginId: string, value: unknown): void {
|
||||
if (!value || typeof value !== "object") return;
|
||||
const input = (value as Record<string, unknown>).input;
|
||||
const session = sessions.get(pluginId);
|
||||
if (session && input) void session.dispatch(input);
|
||||
}
|
||||
|
||||
function surfaceChanged(pluginId: string, active: boolean): void {
|
||||
if (active) surfaces.value.add(pluginId);
|
||||
else surfaces.value.delete(pluginId);
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
function toggleSurface(pluginId: string): void {
|
||||
const next = new Set(suppressedSurfaces.value);
|
||||
if (next.has(pluginId)) next.delete(pluginId);
|
||||
else next.add(pluginId);
|
||||
suppressedSurfaces.value = next;
|
||||
publishSurfaceState();
|
||||
}
|
||||
|
||||
watch(() => [props.skinId, props.skinVersion, props.plugins, props.files], async () => {
|
||||
const currentRun = ++digestRun;
|
||||
stopAll("skin-changed");
|
||||
inMemoryApprovals.clear();
|
||||
denied.value = new Set();
|
||||
managerOpen.value = false;
|
||||
digests.value = {};
|
||||
digestErrors.value = {};
|
||||
const plugins = props.plugins?.plugins ?? [];
|
||||
const nextDigests: Record<string, string> = Object.create(null) as Record<string, string>;
|
||||
const nextErrors: Record<string, string> = Object.create(null) as Record<string, string>;
|
||||
await Promise.all(plugins.map(async (plugin) => {
|
||||
try { nextDigests[plugin.id] = await computeSkinRuntimePluginDigest(plugin, props.files); }
|
||||
catch { nextErrors[plugin.id] = "The package files could not be verified. / 无法校验插件文件。"; }
|
||||
}));
|
||||
if (disposed || currentRun !== digestRun) return;
|
||||
digests.value = nextDigests;
|
||||
digestErrors.value = nextErrors;
|
||||
revision.value += 1;
|
||||
reconcile();
|
||||
if (PROMPT_FOR_SKIN_PERMISSIONS) reconcile();
|
||||
else approvePending();
|
||||
}, { immediate: true });
|
||||
|
||||
watch(() => [props.page, digests.value, revision.value], reconcile, { deep: true });
|
||||
watch(() => props.context, () => {
|
||||
if (disposed) return;
|
||||
if (contextRefreshTimer !== undefined) window.clearTimeout(contextRefreshTimer);
|
||||
contextRefreshTimer = window.setTimeout(() => {
|
||||
contextRefreshTimer = undefined;
|
||||
for (const session of sessions.values()) void session.refresh();
|
||||
}, 100);
|
||||
}, { deep: true });
|
||||
watch(activeSurface, publishSurfaceState, { flush: "sync" });
|
||||
onMounted(() => { void nextTick(refreshMountTargets); });
|
||||
watch([() => props.page, () => props.mountRevision, activeSurface], () => { void nextTick(refreshMountTargets); }, { flush: "post" });
|
||||
onUnmounted(() => {
|
||||
disposed = true;
|
||||
digestRun += 1;
|
||||
stopAll("host-unmounted");
|
||||
});
|
||||
|
||||
return () => {
|
||||
const currentPlugins = pagePlugins.value;
|
||||
const nodes: VNodeChild[] = [];
|
||||
for (const plugin of currentPlugins) {
|
||||
const generatedOutput = suppressedSurfaces.value.has(plugin.id) ? null : outputs.value[plugin.id] ?? null;
|
||||
const pluginAssets = outputAssets(plugin);
|
||||
const layoutRoot = h("div", {
|
||||
key: `${props.skinId}:${plugin.id}:layout-root:${props.page}`,
|
||||
class: "ws-runtime-plugin-root",
|
||||
"data-ws-runtime-plugin-root": plugin.id,
|
||||
"data-ws-part": `skin.${props.page}.runtime_plugin_root_${plugin.id}`,
|
||||
}, [h(SkinPluginOutlet, {
|
||||
key: `${props.skinId}:${plugin.id}:${props.page}`,
|
||||
skinId: props.skinId,
|
||||
skinVersion: props.skinVersion,
|
||||
document: EMPTY_DOCUMENT,
|
||||
extensionOutput: generatedOutput,
|
||||
extensionMode: plugin.mode,
|
||||
componentNamespace: plugin.id,
|
||||
manageSurfaceRecovery: false,
|
||||
page: props.page,
|
||||
data: {},
|
||||
assets: pluginAssets,
|
||||
actions: {},
|
||||
extensionPermissions: plugin.permissions,
|
||||
widgets: props.widgets,
|
||||
onExtensionEvent: (event: unknown) => dispatch(plugin.id, event),
|
||||
onSurfaceChange: (active: boolean) => surfaceChanged(plugin.id, active),
|
||||
onRestoreSkin: () => emit("restore-skin"),
|
||||
})]);
|
||||
const mountTarget = plugin.mount ? mountTargets.value[plugin.id] : undefined;
|
||||
nodes.push(mountTarget ? h(Teleport, { to: mountTarget }, [layoutRoot]) : layoutRoot);
|
||||
}
|
||||
|
||||
const controls: VNodeChild[] = [];
|
||||
if (currentPlugins.length) {
|
||||
controls.push(h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-access-toggle",
|
||||
"aria-label": "管理运行时插件权限 / Manage runtime plugin access",
|
||||
onClick: openManager,
|
||||
}, "插件权限 / Plugin access")]));
|
||||
}
|
||||
for (const plugin of currentPlugins) {
|
||||
if (plugin.mode !== "surface" || !outputs.value[plugin.id]) continue;
|
||||
const suppressed = suppressedSurfaces.value.has(plugin.id);
|
||||
controls.push(h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-recovery",
|
||||
"aria-label": suppressed ? "恢复自定义界面 / Restore custom interface" : "返回 WebSpeak 标准界面 / Return to built-in interface",
|
||||
onClick: () => toggleSurface(plugin.id),
|
||||
}, suppressed ? "恢复自定义界面 / Restore custom UI" : "标准界面 / Built-in UI")]));
|
||||
controls.push(h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-reset",
|
||||
"aria-label": "恢复内置皮肤 / Restore the built-in skin",
|
||||
onClick: () => emit("restore-skin"),
|
||||
}, "恢复内置皮肤 / Reset skin")]));
|
||||
}
|
||||
|
||||
const showConsent = pending.value.length > 0 || managerOpen.value;
|
||||
watch(editorMode.isEnabled, (enabled) => { if (!enabled) managerOpen.value = false; });
|
||||
watch(() => props.context, () => {
|
||||
if (disposed) return;
|
||||
if (contextRefreshTimer !== undefined) window.clearTimeout(contextRefreshTimer);
|
||||
contextRefreshTimer = window.setTimeout(() => {
|
||||
contextRefreshTimer = undefined;
|
||||
for (const session of sessions.values()) void session.refresh();
|
||||
}, 100);
|
||||
}, { deep: true });
|
||||
watch(activeSurface, publishSurfaceState, { flush: "sync" });
|
||||
onMounted(() => { void nextTick(refreshMountTargets); });
|
||||
watch([() => props.page, () => props.mountRevision, activeSurface], () => { void nextTick(refreshMountTargets); }, { flush: "post" });
|
||||
onUnmounted(() => {
|
||||
disposed = true;
|
||||
digestRun += 1;
|
||||
stopAll("host-unmounted");
|
||||
});
|
||||
|
||||
return () => {
|
||||
const currentPlugins = pagePlugins.value;
|
||||
const nodes: VNodeChild[] = [];
|
||||
for (const plugin of currentPlugins) {
|
||||
const generatedOutput = suppressedSurfaces.value.has(plugin.id) ? null : outputs.value[plugin.id] ?? null;
|
||||
const pluginAssets = outputAssets(plugin);
|
||||
const layoutRoot = h("div", {
|
||||
key: `${props.skinId}:${plugin.id}:layout-root:${props.page}`,
|
||||
class: "ws-runtime-plugin-root",
|
||||
"data-ws-runtime-plugin-root": plugin.id,
|
||||
"data-ws-part": `skin.${props.page}.runtime_plugin_root_${plugin.id}`,
|
||||
}, [h(SkinPluginOutlet, {
|
||||
key: `${props.skinId}:${plugin.id}:${props.page}`,
|
||||
skinId: props.skinId,
|
||||
skinVersion: props.skinVersion,
|
||||
document: EMPTY_DOCUMENT,
|
||||
extensionOutput: generatedOutput,
|
||||
extensionMode: plugin.mode,
|
||||
componentNamespace: plugin.id,
|
||||
manageSurfaceRecovery: false,
|
||||
page: props.page,
|
||||
data: {},
|
||||
assets: pluginAssets,
|
||||
actions: {},
|
||||
extensionPermissions: plugin.permissions,
|
||||
widgets: props.widgets,
|
||||
onExtensionEvent: (event: unknown) => dispatch(plugin.id, event),
|
||||
onSurfaceChange: (active: boolean) => surfaceChanged(plugin.id, active),
|
||||
onRestoreSkin: () => emit("restore-skin"),
|
||||
})]);
|
||||
const mountTarget = plugin.mount ? mountTargets.value[plugin.id] : undefined;
|
||||
nodes.push(mountTarget ? h(Teleport, { to: mountTarget }, [layoutRoot]) : layoutRoot);
|
||||
}
|
||||
|
||||
const controls: VNodeChild[] = [];
|
||||
if (currentPlugins.length && editorMode.isEnabled.value) {
|
||||
controls.push(h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-access-toggle",
|
||||
"aria-label": "管理运行时插件权限 / Manage runtime plugin access",
|
||||
onClick: openManager,
|
||||
}, "插件权限 / Plugin access")]));
|
||||
}
|
||||
for (const plugin of currentPlugins) {
|
||||
if (!editorMode.isEnabled.value || plugin.mode !== "surface" || !outputs.value[plugin.id]) continue;
|
||||
const suppressed = suppressedSurfaces.value.has(plugin.id);
|
||||
controls.push(h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-recovery",
|
||||
"aria-label": suppressed ? "恢复自定义界面 / Restore custom interface" : "返回 WebSpeak 标准界面 / Return to built-in interface",
|
||||
onClick: () => toggleSurface(plugin.id),
|
||||
}, suppressed ? "恢复自定义界面 / Restore custom UI" : "标准界面 / Built-in UI")]));
|
||||
controls.push(h(Teleport, { to: "body" }, [h("button", {
|
||||
type: "button",
|
||||
class: "ws-plugin-surface-reset",
|
||||
"aria-label": "恢复内置皮肤 / Restore the built-in skin",
|
||||
onClick: () => emit("restore-skin"),
|
||||
}, "恢复内置皮肤 / Reset skin")]));
|
||||
}
|
||||
|
||||
const showConsent = (PROMPT_FOR_SKIN_PERMISSIONS && pending.value.length > 0) || managerOpen.value;
|
||||
if (!showConsent) return h("div", { class: "ws-runtime-plugin-host" }, [...nodes, ...controls]);
|
||||
|
||||
const showApproval = pending.value.length > 0;
|
||||
const listed = showApproval ? pending.value : currentPlugins;
|
||||
const consent = h(Teleport, { to: "body" }, [h("div", { class: "ws-plugin-consent-backdrop", "data-ws-runtime-plugin-consent": "true" }, [
|
||||
h("section", { class: "ws-plugin-consent", role: "dialog", "aria-modal": "true", "aria-labelledby": "ws-runtime-plugin-consent-title" }, [
|
||||
h("h2", { id: "ws-runtime-plugin-consent-title" }, showApproval ? "运行时插件授权 / Runtime plugin approval" : "运行时插件权限 / Runtime plugin access"),
|
||||
h("p", null, "插件只在隔离的 Wasm Worker 中运行。每次执行均有时限和内存上限;插件不能访问网络、存储、连接地址、密码或身份材料。/ Plugins run in a bounded Wasm worker and cannot access network, storage, connection targets, passwords, or identity material."),
|
||||
...listed.map((plugin) => {
|
||||
const grant = approved(plugin);
|
||||
const error = digestErrors.value[plugin.id];
|
||||
const unsupported = pluginReason(plugin);
|
||||
const status = error || unsupported || (grant ? "已授权 / Approved" : "等待授权 / Approval required");
|
||||
return h("div", { class: "ws-plugin-consent-item", key: plugin.id }, [
|
||||
h("strong", null, `${plugin.name} · ${plugin.mode === "surface" ? "整页界面 / surface" : "组件 / widget"}`),
|
||||
h("ul", null, [
|
||||
...plugin.permissions.map((permission) => h("li", { key: permission }, [
|
||||
h("code", null, permission),
|
||||
h("span", null, ` — ${SKIN_PLUGIN_PERMISSIONS[permission].description}`),
|
||||
])),
|
||||
h("li", { key: "status" }, status),
|
||||
]),
|
||||
]);
|
||||
}),
|
||||
h("p", { class: "ws-plugin-consent-note" }, "插件在隔离的 Wasm worker 中运行;界面与数据能力由 WebSpeak 按下列权限控制。宿主动作只能由可信的明确用户操作触发,并仍会按当前会话和参数校验。数据字段只按清单中的读取权限投影,授权绑定到此皮肤版本、插件清单和所有插件文件的 SHA-256。/ Plugins run in an isolated Wasm worker. WebSpeak gates UI and data capabilities by the permissions below. Host actions require a trusted explicit user event and are still validated against the current session and arguments. Data is projected by the read permissions in the descriptor, and approval is bound to this skin version, descriptor, and every plugin file by SHA-256."),
|
||||
h("div", { class: "ws-plugin-consent-actions" }, showApproval
|
||||
? [
|
||||
h("button", { type: "button", class: "secondary", onClick: keepDisabled }, "暂不启用 / Keep disabled"),
|
||||
h("button", { type: "button", class: "primary", disabled: listed.some((plugin) => !digests.value[plugin.id] || Boolean(digestErrors.value[plugin.id])) || listed.some((plugin) => !isSupported(plugin)), onClick: approvePending }, "批准所列插件 / Approve listed plugins"),
|
||||
]
|
||||
: [
|
||||
h("button", { type: "button", class: "secondary", onClick: revokeAll }, "撤销全部授权 / Revoke all access"),
|
||||
h("button", { type: "button", class: "primary", onClick: () => { managerOpen.value = false; } }, "关闭 / Close"),
|
||||
]),
|
||||
]),
|
||||
])]);
|
||||
return h("div", { class: "ws-runtime-plugin-host" }, [...nodes, ...controls, consent]);
|
||||
};
|
||||
},
|
||||
});
|
||||
const showApproval = PROMPT_FOR_SKIN_PERMISSIONS && pending.value.length > 0;
|
||||
const listed = showApproval ? pending.value : currentPlugins;
|
||||
const consent = h(Teleport, { to: "body" }, [h("div", { class: "ws-plugin-consent-backdrop", "data-ws-runtime-plugin-consent": "true" }, [
|
||||
h("section", { class: "ws-plugin-consent", role: "dialog", "aria-modal": "true", "aria-labelledby": "ws-runtime-plugin-consent-title" }, [
|
||||
h("h2", { id: "ws-runtime-plugin-consent-title" }, showApproval ? "运行时插件授权 / Runtime plugin approval" : "运行时插件权限 / Runtime plugin access"),
|
||||
h("p", null, "插件只在隔离的 Wasm Worker 中运行。每次执行均有时限和内存上限;插件不能访问网络、存储、连接地址、密码或身份材料。/ Plugins run in a bounded Wasm worker and cannot access network, storage, connection targets, passwords, or identity material."),
|
||||
...listed.map((plugin) => {
|
||||
const grant = approved(plugin);
|
||||
const error = digestErrors.value[plugin.id];
|
||||
const unsupported = pluginReason(plugin);
|
||||
const status = error || unsupported || (grant ? "已授权 / Approved" : "等待授权 / Approval required");
|
||||
return h("div", { class: "ws-plugin-consent-item", key: plugin.id }, [
|
||||
h("strong", null, `${plugin.name} · ${plugin.mode === "surface" ? "整页界面 / surface" : "组件 / widget"}`),
|
||||
h("ul", null, [
|
||||
...plugin.permissions.map((permission) => h("li", { key: permission }, [
|
||||
h("code", null, permission),
|
||||
h("span", null, ` — ${SKIN_PLUGIN_PERMISSIONS[permission].description}`),
|
||||
])),
|
||||
h("li", { key: "status" }, status),
|
||||
]),
|
||||
]);
|
||||
}),
|
||||
h("p", { class: "ws-plugin-consent-note" }, "插件在隔离的 Wasm worker 中运行;界面与数据能力由 WebSpeak 按下列权限控制。宿主动作只能由可信的明确用户操作触发,并仍会按当前会话和参数校验。数据字段只按清单中的读取权限投影,授权绑定到此皮肤版本、插件清单和所有插件文件的 SHA-256。/ Plugins run in an isolated Wasm worker. WebSpeak gates UI and data capabilities by the permissions below. Host actions require a trusted explicit user event and are still validated against the current session and arguments. Data is projected by the read permissions in the descriptor, and approval is bound to this skin version, descriptor, and every plugin file by SHA-256."),
|
||||
h("div", { class: "ws-plugin-consent-actions" }, showApproval
|
||||
? [
|
||||
h("button", { type: "button", class: "secondary", onClick: keepDisabled }, "暂不启用 / Keep disabled"),
|
||||
h("button", { type: "button", class: "primary", disabled: listed.some((plugin) => !digests.value[plugin.id] || Boolean(digestErrors.value[plugin.id])) || listed.some((plugin) => !isSupported(plugin)), onClick: approvePending }, "批准所列插件 / Approve listed plugins"),
|
||||
]
|
||||
: [
|
||||
h("button", { type: "button", class: "secondary", onClick: revokeAll }, "撤销全部授权 / Revoke all access"),
|
||||
h("button", { type: "button", class: "primary", onClick: () => { managerOpen.value = false; } }, "关闭 / Close"),
|
||||
]),
|
||||
]),
|
||||
])]);
|
||||
return h("div", { class: "ws-runtime-plugin-host" }, [...nodes, ...controls, consent]);
|
||||
};
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user