Merge PR #57: integrate host chrome theming and skin recovery

This commit is contained in:
illusia committed 2026-11-14 18:59:15 +08:00
commit 6a35d9be3d
46 files changed
+3129 -131

No files matched your search

+252
View File
@@ -0,0 +1,252 @@
<template>
<!-- Host chrome is intentionally outside .ws-skin-root so a v3 surface
replacement cannot delete the recovery path or the authorization UI. -->
<Teleport to="body">
<div class="ws-host-chrome" data-ws-host-chrome>
<div
v-if="!isHostPartHidden('host.watermark')"
class="ws-host-watermark"
data-ws-part="host.watermark"
aria-hidden="true"
>WebSpeak</div>
<p
v-if="!isHostPartHidden('host.hint')"
class="ws-host-hint"
data-ws-part="host.hint"
>{{ copy.hint }}</p>
<div
v-if="!isHostPartHidden('host.voice-status-decoration')"
class="ws-host-voice-status-decoration"
data-ws-part="host.voice-status-decoration"
aria-hidden="true"
><span></span><span></span></div>
</div>
</Teleport>
<!-- Trusted recovery entry. It lives in a closed shadow root and a manual
popover, so no compiled skin selector can target it (shadow boundary)
and no normal stacking context can cover it (top layer). It carries no
`data-ws-part`: there is intentionally no skin hook for this control. -->
<Teleport v-if="layer" :to="layer.container">
<div
ref="recoveryPopover"
popover="manual"
class="ws-host-recovery"
data-ws-host-recovery
role="region"
:aria-label="copy.recovery"
>
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
<button
type="button"
data-ws-recovery-action="built-in"
:title="copy.shortcut"
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
type="button"
v-if="pluginLibraryAvailable"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
>{{ copy.library }}</button>
</div>
</Teleport>
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import type { SiteLanguage } from "../../../src/site-copy.js";
import { hostChromeCopy } from "../i18n/host-chrome.js";
import {
isHostPartHidden,
isHostPartVisuallyReachable,
isRecoveryShortcut,
isThirdPartySkinActive,
openPluginLibrary,
requestBuiltInSkin,
} from "../services/host-chrome.js";
import {
createHostOwnedLayer,
syncRecoveryPopover,
type HostOwnedLayer,
} from "../services/host-owned-layer.js";
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
import { thirdPartyAllowed } from "../services/instance-authorization.js";
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: boolean }>(), { connected: false });
const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
// Styles live inside the closed shadow root: the component's scoped stylesheet
// in <head> cannot cross the shadow boundary.
const RECOVERY_LAYER_CSS = `
:host { font: 11px/1.2 ui-sans-serif, system-ui, sans-serif; }
.ws-host-recovery {
position: fixed;
inset: auto auto calc(38px + env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
margin: 0;
align-items: center;
flex-wrap: wrap;
gap: 4px;
max-width: calc(100vw - 24px);
padding: 4px 5px 4px 9px;
border: 1px solid #9db6b2;
border-radius: 999px;
background: color-mix(in srgb, #ffffff 92%, transparent);
color: #31524f;
box-shadow: 0 6px 18px #0f2a2626;
pointer-events: auto;
}
.ws-host-recovery:popover-open { display: flex; }
.ws-host-recovery-mark { font-size: 12px; line-height: 1; }
.ws-host-recovery button {
display: inline-flex;
align-items: center;
min-height: 28px;
padding: 4px 9px;
border: 1px solid #9db6b2;
border-radius: 999px;
background: #fff;
color: #31524f;
font: inherit;
cursor: pointer;
white-space: nowrap;
}
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
border-color: #b45309;
background: #fff7ed;
color: #7c2d12;
}
.ws-host-recovery button:hover { filter: brightness(.96); }
.ws-host-recovery button:focus-visible { outline: 2px solid #4c8f88; outline-offset: 2px; }
@media (prefers-reduced-motion: reduce) { .ws-host-recovery button { transition: none; } }
`;
const layer: HostOwnedLayer | null = createHostOwnedLayer("recovery", RECOVERY_LAYER_CSS);
// CSS-only hiding is invisible to `isHostPartHidden`, so sample the launcher's
// live geometry. A one-second interval is enough for a recovery fallback and
// stays cheaper than a MutationObserver on the whole document. While a
// third-party skin is active the entry is persistent and this sample only
// matters for the official-skin fallback.
const launcherReachable = ref(true);
const showRecovery = computed(() => shouldShowRecovery({
connected: props.connected && Boolean(props.pluginLibraryAvailable),
thirdPartyAllowed: thirdPartyAllowed.value,
thirdPartySkinActive: isThirdPartySkinActive(),
launcherHiddenByConfig: isHostPartHidden("host.plugins.launcher"),
launcherReachable: launcherReachable.value,
}));
// The documented shortcut can summon the same host-owned entry even while a
// bundled skin is active (for example after a broken third-party skin was
// already reset). It never renders decoration on its own.
const shortcutOpen = ref(false);
const recoveryPopover = ref<HTMLElement | null>(null);
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
}
function useBuiltInSkin() {
shortcutOpen.value = false;
requestBuiltInSkin();
}
function openLibrary() {
shortcutOpen.value = false;
openPluginLibrary();
}
function onKeydown(event: KeyboardEvent) {
if (event.defaultPrevented || event.repeat || !thirdPartyAllowed.value) return;
if (isRecoveryShortcut(event)) {
event.preventDefault();
shortcutOpen.value = true;
void nextTick(() => recoveryPopover.value?.querySelector("button")?.focus());
return;
}
if (event.key === "Escape" && shortcutOpen.value) shortcutOpen.value = false;
}
let reachabilityTimer: ReturnType<typeof setInterval> | undefined;
function refreshLauncherReachability() {
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
}
watch([recoveryVisible, recoveryPopover], () => { void nextTick(syncPopover); }, { flush: "post" });
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
onMounted(() => {
refreshLauncherReachability();
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
window.addEventListener("resize", refreshLauncherReachability);
window.addEventListener("keydown", onKeydown);
void nextTick(syncPopover);
});
onBeforeUnmount(() => {
if (reachabilityTimer) clearInterval(reachabilityTimer);
window.removeEventListener("resize", refreshLauncherReachability);
window.removeEventListener("keydown", onKeydown);
layer?.dispose();
});
</script>
<style scoped>
.ws-host-chrome {
position: fixed;
inset: 0;
z-index: 0;
overflow: hidden;
pointer-events: none;
}
.ws-host-watermark {
position: absolute;
top: clamp(8px, 6vh, 64px);
right: clamp(12px, 3vw, 64px);
color: #8ab9cf;
font: 800 clamp(40px, 7vw, 104px)/1 ui-sans-serif, system-ui, sans-serif;
letter-spacing: -.06em;
opacity: .14;
user-select: none;
white-space: nowrap;
}
.ws-host-hint {
position: absolute;
bottom: calc(10px + env(safe-area-inset-bottom));
left: 14px;
max-width: min(46vw, 420px);
margin: 0;
color: #6d8b88;
font: 11px/1.4 ui-sans-serif, system-ui, sans-serif;
opacity: .8;
user-select: none;
}
.ws-host-voice-status-decoration {
position: absolute;
top: 0;
right: 0;
display: flex;
align-items: center;
gap: 8px;
width: min(28vw, 320px);
height: 28px;
padding: 0 12px;
opacity: .28;
}
.ws-host-voice-status-decoration span {
display: block;
height: 6px;
border-radius: 3px;
background: #95b6b1;
}
.ws-host-voice-status-decoration span:first-child { width: 64px; }
.ws-host-voice-status-decoration span:last-child { flex: 1; opacity: .6; }
@media (max-width: 640px) {
.ws-host-hint { max-width: 62vw; }
.ws-host-voice-status-decoration { display: none; }
}
</style>
+18 -9
View File
@@ -1,5 +1,9 @@
<template>
<Teleport to="body">
<!-- The authorization dialog is host-owned trusted UI: it is rendered in a
closed shadow root and promoted with showModal(), so compiled skin CSS
cannot select, restyle, cover or disable it. It deliberately carries no
`data-ws-part`; there is no skin hook for this dialog. -->
<Teleport v-if="layer" :to="layer.container">
<dialog ref="dialog" class="ws-instance-authorization" @cancel.prevent="cancel" @close="authorizationRequested = false">
<form @submit.prevent="save">
<div class="ws-authorization-mark" aria-hidden="true">◈</div>
@@ -20,6 +24,18 @@ import { computed, onBeforeUnmount, ref, watch } from 'vue';
import type { SiteLanguage } from '../../../src/site-copy.js';
import { authorizationDecision, authorizationLanguage, authorizationRequested, setInstanceAuthorization } from '../services/instance-authorization.js';
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
import { createHostOwnedLayer, type HostOwnedLayer } from '../services/host-owned-layer.js';
const AUTHORIZATION_LAYER_CSS = `
:host { font: 14px/1.75 system-ui, -apple-system, "Segoe UI", sans-serif; }
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:inherit;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto;pointer-events:auto}
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
`;
const layer: HostOwnedLayer | null = createHostOwnedLayer('authorization', AUTHORIZATION_LAYER_CSS);
const props = defineProps<{ language: SiteLanguage }>();
const dialog = ref<HTMLDialogElement | null>(null), checked = ref(false), firstVisit = ref(false);
const copy = computed(() => instanceAuthorizationCopy[props.language]);
@@ -34,12 +50,5 @@ function finish() { authorizationRequested.value = false; dialog.value?.close();
function save() { if (firstVisit.value && !checked.value) return; setInstanceAuthorization(checked.value); finish(); }
function decline() { setInstanceAuthorization(false); finish(); }
function cancel() { if (firstVisit.value) decline(); else finish(); }
onBeforeUnmount(() => dialog.value?.close());
onBeforeUnmount(() => { dialog.value?.close(); layer?.dispose(); });
</script>
<style>
.ws-instance-authorization{box-sizing:border-box;width:min(570px,calc(100vw - 32px));max-height:calc(100dvh - 32px);margin:auto;padding:30px;border:1px solid #dbe3f1;border-radius:20px;background:#fff;color:#25324b;font:14px/1.75 system-ui,-apple-system,"Segoe UI",sans-serif;box-shadow:0 24px 90px #101c4140;color-scheme:light;overflow:auto}
.ws-instance-authorization::backdrop{background:#10182d8c;backdrop-filter:blur(5px)}
.ws-instance-authorization form{margin:0}.ws-instance-authorization h2{margin:12px 0 16px;font-size:23px;line-height:1.4;color:#202e49}.ws-instance-authorization p{margin:12px 0;color:#526079}.ws-authorization-mark{display:grid;place-items:center;width:43px;height:43px;border-radius:13px;background:#edf0ff;color:#5265df;font-size:28px}
.ws-instance-authorization label{display:flex;align-items:flex-start;gap:12px;margin:22px 0;padding:15px;background:#f4f6fc;border:1px solid #dce3f3;border-radius:12px;cursor:pointer}.ws-instance-authorization input{appearance:auto;flex:none;width:18px;height:18px;margin:4px 0 0;accent-color:#5265df}.ws-instance-authorization footer{display:flex;justify-content:flex-end;gap:10px;flex-wrap:wrap;margin-top:24px}.ws-instance-authorization button{appearance:none;min-height:42px;padding:9px 16px;border:1px solid #d9e1ef;border-radius:10px;background:#f4f6fc;color:#43516d;font:600 14px/1.5 system-ui;cursor:pointer}.ws-instance-authorization .ws-authorization-primary{background:#5265df;color:#fff;border-color:#5265df}.ws-instance-authorization button:disabled{opacity:.45;cursor:not-allowed}.ws-instance-authorization button:focus-visible,.ws-instance-authorization input:focus-visible{outline:2px solid #5265df;outline-offset:3px}
@media(max-width:600px){.ws-instance-authorization{padding:22px}.ws-instance-authorization footer button{flex:1}}
</style>
+2 -1
View File
@@ -11,7 +11,7 @@
:aria-controls="menuId"
@click.stop="toggle"
>
<Icon class="language-current-icon" name="translate" :size="24" />
<Icon class="language-current-icon" name="translate" :size="24" :data-ws-icon-slot="skinIcon ? 'language.trigger' : undefined" />
<span class="language-current-flag" aria-hidden="true">{{ currentLanguage.flag }}</span>
<span class="language-current-code">{{ currentLanguage.code }}</span>
<Icon name="chevron-down" :size="13" />
@@ -50,6 +50,7 @@ import Icon from "./Icon.vue";
type Language = "zh" | "en" | "de" | "ru" | "ja";
const props = withDefaults(defineProps<{
skinIcon?: boolean;
modelValue: Language;
menuLabel?: string;
}>(), {
+17 -6
View File
@@ -1,15 +1,15 @@
<template>
<Teleport to="#webspeak-plugin-toolbar">
<Teleport v-if="toolbarTarget" :to="toolbarTarget">
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-toolbar">
<button ref="launcher" class="header-action ws-plugin-toolbar-trigger" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @click="toggle">
<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
<button v-if="!isHostPartHidden('host.plugins.launcher')" ref="launcher" class="header-action ws-plugin-toolbar-trigger" data-ws-part="host.plugins.launcher" type="button" :title="tr('title')" :aria-label="tr('title')" :aria-expanded="visible" @click="toggle">
<svg viewBox="0 0 24 24" data-ws-icon-slot="host.plugins.launcher" aria-hidden="true"><path d="M4 4h6v6H4zM14 4h6v6h-6zM4 14h6v6H4zM14 14h6v6h-6z" /></svg>
</button>
<button v-for="entry in pinnedApps" :key="entry.manifest.id" class="header-action ws-plugin-toolbar-shortcut" type="button" :title="entry.manifest.name" :aria-label="entry.manifest.name" :disabled="busy || entry.runtime.state === 'failed'" @click="launch(entry.manifest.id)">{{ entry.manifest.name.slice(0, 1).toUpperCase() }}</button>
</div>
</Teleport>
<Teleport to="body">
<div v-if="thirdPartyAllowed && connected && sessionToken" class="ws-plugin-overlay" :data-plugin-theme="theme">
<section v-show="visible" ref="windowElement" class="ws-plugin-window" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
<section v-show="visible" ref="windowElement" class="ws-plugin-window" data-ws-part="host.plugins.overlay" :class="{ 'is-maximized': maximized, 'is-dragging': dragging }" :style="position" role="dialog" :aria-label="current && appView ? current.manifest.name : tr('title')" tabindex="-1" @keydown.esc.stop="minimize">
<header class="ws-plugin-titlebar" @pointerdown="startDrag" @lostpointercapture="endDrag" @dblclick="toggleMaximize">
<span class="ws-plugin-mark" aria-hidden="true">◈</span>
<div class="ws-plugin-window-title"><strong>{{ current && appView ? current.manifest.name : tr('title') }}</strong><small>WebSpeak</small></div>
@@ -54,7 +54,8 @@ import { pluginTranslations, type PluginTextKey } from '../i18n/plugins.js';
import { pluginWindowTranslations } from '../i18n/plugin-window.js';
import type { SiteLanguage } from '../../../src/site-copy.js';
import { thirdPartyAllowed } from '../services/instance-authorization.js';
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage }>();
import { isHostPartHidden, pluginLibraryRequests } from '../services/host-chrome.js';
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage; toolbarTarget: HTMLElement | null }>();
const tr = (key: PluginTextKey) => pluginTranslations[props.language][key];
const ui = computed(() => pluginWindowTranslations[props.language]);
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
@@ -153,10 +154,20 @@ watch(thirdPartyAllowed, allowed => {
else if (props.connected) void refresh();
}, { flush: 'sync' });
watch(() => props.language, appearance); watch(theme, appearance);
// Trusted recovery entry (host chrome / skin menu) keeps the application
// library reachable when a skin hides the toolbar launcher.
watch(pluginLibraryRequests, () => {
if (!thirdPartyAllowed.value || !props.connected || !props.sessionToken) return;
detectTheme();
visible.value = true;
appView.value = false;
if (!current.value) void refresh();
void nextTick(() => { fitWindow(); windowElement.value?.focus(); });
});
onMounted(() => {
detectTheme(); window.addEventListener('message', message); window.addEventListener('resize', fitWindow); window.addEventListener('pointermove', moveDrag); window.addEventListener('pointerup', endDrag); window.addEventListener('pointercancel', endDrag); window.addEventListener('blur', endDrag);
if (props.connected && thirdPartyAllowed.value) void refresh();
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-theme'] });
observer = new MutationObserver(detectTheme); observer.observe(document.documentElement, { attributes: true, subtree: true, attributeFilter: ['data-ws-skin', 'data-ws-host-skin', 'data-theme'] });
});
onBeforeUnmount(() => { stop(); endDrag(); observer?.disconnect(); resizeObserver?.disconnect(); window.removeEventListener('message', message); window.removeEventListener('resize', fitWindow); window.removeEventListener('pointermove', moveDrag); window.removeEventListener('pointerup', endDrag); window.removeEventListener('pointercancel', endDrag); window.removeEventListener('blur', endDrag); });
</script>
@@ -1,6 +1,6 @@
<template>
<Teleport to="body">
<section v-if="error" class="skin-load-recovery" role="alert">
<section v-if="error" class="skin-load-recovery" data-ws-part="app.skin-load-recovery" role="alert">
<p>{{ labels.skinLoadError(error.skinId) }}</p>
<button type="button" @click="$emit('use-built-in')">{{ labels.skinUseBuiltIn }}</button>
</section>
+10 -1
View File
@@ -13,7 +13,7 @@
:aria-controls="menuId"
@click.stop="toggle"
>
<Icon :name="selectedOption.icon || 'compass'" :size="15" />
<Icon :name="selectedOption.icon || 'compass'" :size="15" data-ws-icon-slot="skin.trigger" />
<span>{{ menuLabel }}</span>
<Icon name="chevron-down" :size="12" />
</button>
@@ -38,6 +38,9 @@
<button type="button" class="skin-option skin-authorization" role="option" :aria-selected="false" @click="authorization">
<Icon name="shield" :size="16" /><span>{{ authorizationCopy.menu }}</span><small>{{ thirdPartyAllowed ? authorizationCopy.enabled : authorizationCopy.disabled }}</small>
</button>
<button v-if="thirdPartyAllowed && pluginLibraryAvailable" type="button" class="skin-option skin-library" data-ws-part="skin.library" role="option" :aria-selected="false" @click="openLibrary">
<Icon name="grid" :size="16" /><span>{{ libraryLabel }}</span>
</button>
</div>
</div>
</template>
@@ -47,6 +50,8 @@ import { computed, onMounted, onUnmounted, ref } from "vue";
import Icon from "./Icon.vue";
import { authorizationLanguage, canUseSkin, openInstanceAuthorization, thirdPartyAllowed } from '../services/instance-authorization.js';
import { instanceAuthorizationCopy } from '../i18n/instance-authorization.js';
import { hostChromeCopy } from '../i18n/host-chrome.js';
import { openPluginLibrary } from '../services/host-chrome.js';
export interface SkinOption {
value: string;
@@ -58,6 +63,7 @@ const props = defineProps<{
modelValue: string;
menuLabel: string;
options: SkinOption[];
pluginLibraryAvailable?: boolean;
}>();
const emit = defineEmits<{
@@ -67,7 +73,9 @@ const emit = defineEmits<{
const options = computed(() => props.options.filter(option => canUseSkin(option.value)));
const authorizationCopy = computed(() => instanceAuthorizationCopy[authorizationLanguage.value]);
const libraryLabel = computed(() => hostChromeCopy[authorizationLanguage.value]?.library ?? hostChromeCopy.en.library);
function authorization() { close(); openInstanceAuthorization(); }
function openLibrary() { close(); openPluginLibrary(); }
const selectedOption = computed(() => options.value.find((option) => option.value === props.modelValue) ?? options.value[0] ?? {
value: props.modelValue,
label: props.menuLabel,
@@ -101,6 +109,7 @@ onUnmounted(() => document.removeEventListener("pointerdown", onDocumentPointerD
}
.skin-authorization{margin-top:6px;border-top:1px solid #8bdad8!important}
.skin-authorization small{margin-left:auto;font-size:10px;opacity:.75}
.skin-library{opacity:.9}
.skin-trigger {
display: inline-flex;
@@ -14,7 +14,8 @@
@click.stop="togglePerformancePanel"
><Icon
name="activity"
:size="16" /><span class="performance-trigger-label">{{ t("voiceStatus") }}</span
:size="16"
data-ws-icon-slot="voice.performance" /><span class="performance-trigger-label">{{ t("voiceStatus") }}</span
><small v-if="performanceStats.ready">{{ voiceTransportLabel }}</small
><Icon
name="chevron-down"
@@ -92,6 +92,7 @@
<Icon
name="settings"
:size="15"
data-ws-icon-slot="home.toolbar.settings"
/><span>{{ t("adminConsole") }}</span>
</a>
<SkinSwitcher
@@ -101,7 +102,7 @@
:options="skinOptions"
@change="emit('skinChange', $event)"
/>
<LanguageSwitcher
<LanguageSwitcher skin-icon
v-model="language"
class="join-language-switcher"
:menu-label="t('languageMenu')"
+13
View File
@@ -4,6 +4,7 @@ import { listInstalledSkins, loadLocalPreferences, saveLocalPreferences } from "
import { BUILTIN_SKIN_CATALOG, getPublicDefaultSkinId, isPublicSkinEnabled, listPublicSkins, type SkinCatalogEntry } from "../services/skin-catalog.js";
import { activateSkin, BUILTIN_DARK_SKIN, BUILTIN_LIGHT_SKIN, clearCustomSkinStyle, getStoredSkinId } from "../services/skin-runtime.js";
import { createSkinOperation } from "../services/skin-operation.js";
import { setSkinHostChromeParts, setHostChromeActiveSkin, hostBuiltInSkinRequests } from "../services/host-chrome.js";
import { getStoredTheme, isDarkTheme, saveTheme, type ThemeMode } from "../services/theme.js";
import type { InstalledSkin } from "../services/skin-pack.js";
@@ -36,6 +37,14 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
return current = createSkinOperation({ timeoutMs });
}
onScopeDispose(() => { disposed = true; cancel(); });
// Host decorations depend on the active skin's chrome.json opt-in. Built-in
// skins leave `activeSkin` empty, which keeps host chrome hidden by default.
// Only `visibleParts` opts in: chrome.json hiddenParts/icons generate host
// CSS containing `data-ws-part="host.…"`, so inspecting the combined stylesheet
// would wrongly treat every hiddenParts-only pack as host-chrome themed.
watch(activeSkin, (skin) => setSkinHostChromeParts(skin?.chromeData), { immediate: true, flush: "sync" });
// The recovery affordance is persistent while a non-bundled skin is applied.
watch(activeSkinId, (id) => setHostChromeActiveSkin(id), { immediate: true, flush: "sync" });
async function apply(id: string, operation: ReturnType<typeof createSkinOperation>, persist = true, updateTheme = false, clearLoadError = true) {
operation.check();
@@ -134,6 +143,10 @@ export function usePublicSkin(options: PublicSkinOptions = {}) {
skinReady.value = true;
void select(fallbackId());
}, { flush: 'sync' });
// Host-owned recovery's guaranteed action: reset to the built-in skin. It is
// independent of the skinnable plugin overlay, so it also works when that
// overlay is hidden with `display: none`.
watch(hostBuiltInSkinRequests, () => { if (!disposed) void switchToBuiltIn(); }, { flush: 'sync' });
return { activeSkin, activeSkinId, skinReady, skinLoadError,
installedSkins: computed(() => installedSkins.value.filter(skin => canUseSkin(skin.id))),
catalogSkins: computed(() => catalogSkins.value.filter(skin => canUseSkin(skin.id))),
@@ -1,6 +1,7 @@
import { computed, reactive, ref, type Ref } from "vue";
import { DEFAULT_TEAM_SPEAK_PORT, splitTeamSpeakTarget } from "../services/teamspeak-target.js";
import { APP_VERSION } from "../services/app-version.js";
import { setInstanceHiddenParts } from "../services/host-chrome.js";
import type { Language } from "../i18n/web-client.js";
interface RelayOption {
@@ -58,7 +59,11 @@ export function useWebClientPublicConfig({
visitorNumber?: unknown;
visitorTotal?: unknown;
accelerationRelays?: unknown;
hiddenHostParts?: unknown;
};
setInstanceHiddenParts(Array.isArray(config.hiddenHostParts)
? config.hiddenHostParts.filter((part): part is string => typeof part === "string")
: []);
if (typeof config.version === "string" && config.version.trim()) appVersion.value = config.version.trim();
visitorNumber.value = Number.isSafeInteger(config.visitorNumber) && Number(config.visitorNumber) > 0 ? Number(config.visitorNumber) : null;
visitorTotal.value = Number.isSafeInteger(config.visitorTotal) && Number(config.visitorTotal) > 0 ? Number(config.visitorTotal) : null;
+41
View File
@@ -0,0 +1,41 @@
import type { SiteLanguage } from "../../../src/site-copy.js";
/** All five public languages implement the same host chrome labels. */
const en = {
hint: "Audio controls remain available in the toolbar and voice workspace.",
library: "Application library",
recovery: "Restore application library",
useBuiltIn: "Use built-in skin",
shortcut: "Restore the built-in skin (Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS)",
};
export const hostChromeCopy: Record<SiteLanguage, typeof en> = {
en,
zh: {
hint: "音频控制始终保留在工具栏和语音工作区中。",
library: "应用库",
recovery: "恢复应用库",
useBuiltIn: "使用内置皮肤",
shortcut: "恢复内置皮肤(Ctrl+Alt+Shift+R,macOS 为 ⌘+⌥+⇧+R)",
},
de: {
hint: "Audiosteuerung bleibt in der Werkzeugleiste und im Sprachbereich verfügbar.",
library: "Anwendungsbibliothek",
recovery: "Anwendungsbibliothek wiederherstellen",
useBuiltIn: "Integrierten Skin verwenden",
shortcut: "Integrierten Skin wiederherstellen (Strg+Alt+Umschalt+R, unter macOS ⌘+⌥+⇧+R)",
},
ru: {
hint: "Управление звуком остаётся доступным на панели инструментов и в голосовой области.",
library: "Библиотека приложений",
recovery: "Восстановить библиотеку приложений",
useBuiltIn: "Использовать встроенную тему",
shortcut: "Восстановить встроенную тему (Ctrl+Alt+Shift+R, в macOS ⌘+⌥+⇧+R)",
},
ja: {
hint: "音声コントロールはツールバーと音声ワークスペースで常に利用できます。",
library: "アプリライブラリ",
recovery: "アプリライブラリを復元",
useBuiltIn: "組み込みスキンを使用",
shortcut: "組み込みスキンを復元(Ctrl+Alt+Shift+R、macOS は ⌘+⌥+⇧+R)",
},
};
+13
View File
@@ -0,0 +1,13 @@
/**
* Browser-facing re-exports for the static host chrome preview page.
*
* Vite serves modules below `web/`, while the host-chrome policy lives in the
* repository-level `src/shared` tree. Keeping the bridge here lets the preview
* use exactly the same opt-in and reachability rules as the Vue client.
*/
export {
DEFAULT_HIDDEN_HOST_PARTS,
resolveHiddenHostParts,
} from "../../../src/shared/skin-chrome.js";
export type { SkinChromeDocument } from "../../../src/shared/skin-chrome.js";
export { isHostPartReachable, shouldShowRecovery } from "./host-chrome-visibility.js";
@@ -0,0 +1,80 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isBundledSkin } from "./host-chrome.js";
import { isHostPartReachable, shouldShowRecovery, type HostPartVisibilitySnapshot } from "./host-chrome-visibility.js";
const snapshot = (overrides: Partial<HostPartVisibilitySnapshot> = {}): HostPartVisibilitySnapshot => ({
display: "inline-flex",
visibility: "visible",
opacity: "1",
pointerEvents: "auto",
rect: { width: 120, height: 40, left: 600, top: 700, right: 720, bottom: 740 },
viewport: { width: 1280, height: 800 },
...overrides,
});
test("a rendered, on-screen host part is reachable", () => {
assert.equal(isHostPartReachable(snapshot()), true);
// Partially off-screen is still usable.
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: -40, top: 700, right: 80, bottom: 740 } })), true);
});
test("CSS-only hiding makes a host part unreachable", () => {
for (const hidden of [
snapshot({ display: "none" }),
snapshot({ visibility: "hidden" }),
snapshot({ visibility: "collapse" }),
snapshot({ opacity: "0" }),
snapshot({ pointerEvents: "none" }),
snapshot({ clipPath: "inset(50%)" }),
snapshot({ clipPath: "circle(0px)" }),
snapshot({ clip: "rect(0px, 0px, 0px, 0px)" }),
snapshot({ rect: { width: 0, height: 0, left: 0, top: 0, right: 0, bottom: 0 } }),
]) {
assert.equal(isHostPartReachable(hidden), false);
}
// Decorative clipping that leaves a usable area does not trigger recovery.
assert.equal(isHostPartReachable(snapshot({ clipPath: "inset(2px)" })), true);
assert.equal(isHostPartReachable(snapshot({ clipPath: "none" })), true);
});
test("a host part moved entirely outside the viewport is unreachable", () => {
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: -9999, top: 700, right: -9879, bottom: 740 } })), false);
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: 600, top: 900, right: 720, bottom: 940 } })), false);
assert.equal(isHostPartReachable(snapshot({ rect: { width: 120, height: 40, left: 1400, top: 700, right: 1520, bottom: 740 } })), false);
});
test("bundled and third-party skins are classified for the recovery affordance", () => {
// Official Day/Night and the bundled ILLUSIA/KAAK packs stay quiet.
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
assert.equal(isBundledSkin(id), true, String(id));
}
for (const id of ["community.hostile-fixture", "community.some-open-skin", "builtin.future"]) {
// `builtin.*` is reserved for future host packs; everything else is third-party.
assert.equal(isBundledSkin(id), id.startsWith("builtin."), id);
}
});
test("the recovery entry is persistent for third-party skins only", () => {
const base = {
connected: true,
thirdPartyAllowed: true,
thirdPartySkinActive: false,
launcherHiddenByConfig: false,
launcherReachable: true,
};
assert.equal(shouldShowRecovery(base), false);
// A non-bundled skin keeps a small host-owned affordance visible even when
// the launcher is reachable: if the skin hides/covers it, recovery is there.
assert.equal(shouldShowRecovery({ ...base, thirdPartySkinActive: true }), true);
assert.equal(shouldShowRecovery({ ...base, thirdPartySkinActive: true, connected: false }), true);
// Bundled/official skins never gain the affordance while the launcher works.
assert.equal(shouldShowRecovery({ ...base, thirdPartySkinActive: false, launcherReachable: false, connected: false }), false);
// Declarative hiding (chrome.json / instance setting) on a bundled skin.
assert.equal(shouldShowRecovery({ ...base, launcherHiddenByConfig: true }), true);
// CSS-only hiding discovered at runtime.
assert.equal(shouldShowRecovery({ ...base, launcherReachable: false }), true);
// Never show a recovery entry without authorization.
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, thirdPartySkinActive: true }), false);
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, launcherHiddenByConfig: true }), false);
});
@@ -0,0 +1,84 @@
/**
* Pure visibility decisions used by the host chrome recovery entry.
*
* The actual DOM reads live in `host-chrome.ts`; keeping the predicates here
* makes them testable without a browser and keeps the preview page and the Vue
* client on the same rules.
*/
export interface HostPartRect {
width: number;
height: number;
left: number;
top: number;
right: number;
bottom: number;
}
export interface HostPartVisibilitySnapshot {
display: string;
visibility: string;
opacity: string;
pointerEvents: string;
/** Optional: computed `clip-path`; strong clipping makes a control unusable. */
clipPath?: string;
/** Optional: legacy computed `clip` (for example `rect(0 0 0 0)`). */
clip?: string;
rect: HostPartRect;
viewport: { width: number; height: number };
}
function isClippedAway(clipPath: string, clip: string): boolean {
const path = clipPath.toLowerCase();
// `inset(50%)` collapses both axes; a three-digit/100 percentage does too.
if (/inset\(\s*(?:[5-9]\d|100)%/.test(path)) return true;
// Large pixel insets are the unit-based variant of the same escape.
if (/inset\(\s*\d{3,}px/.test(path)) return true;
if (/(?:circle|ellipse)\(\s*0(?:px)?\s*[,)]/.test(path)) return true;
const legacy = clip.toLowerCase();
return /rect\(\s*0(?:px)?[\s,]+0(?:px)?[\s,]+0(?:px)?[\s,]+0(?:px)?\s*\)/.test(legacy);
}
/**
* A host part is reachable when it is rendered, visible, interactive and at
* least partially inside the viewport. CSS-only hiding (display, visibility,
* opacity, pointer-events, clipping, off-screen margins/transforms) therefore
* counts as unavailable even when no chrome.json declared the part hidden.
*/
export function isHostPartReachable(snapshot: HostPartVisibilitySnapshot): boolean {
if (snapshot.display === "none") return false;
if (snapshot.visibility === "hidden" || snapshot.visibility === "collapse") return false;
const opacity = Number.parseFloat(snapshot.opacity);
if (Number.isFinite(opacity) && opacity <= 0.01) return false;
if (snapshot.pointerEvents === "none") return false;
if (isClippedAway(snapshot.clipPath ?? "none", snapshot.clip ?? "auto")) return false;
const { rect, viewport } = snapshot;
if (!(rect.width > 0) || !(rect.height > 0)) return false;
if (rect.right <= 0 || rect.bottom <= 0) return false;
if (rect.left >= viewport.width || rect.top >= viewport.height) return false;
return true;
}
export interface RecoveryVisibilityInput {
connected: boolean;
thirdPartyAllowed: boolean;
/** A non-bundled skin is applied, so the recovery affordance is persistent. */
thirdPartySkinActive: boolean;
/** The part is hidden declaratively (chrome.json hiddenParts / instance setting). */
launcherHiddenByConfig: boolean;
/** The launcher element is currently rendered and reachable in the DOM. */
launcherReachable: boolean;
}
/**
* The recovery entry is a small, persistent host-owned affordance while a
* third-party skin is active, so a hostile skin can never remove the only way
* back. Official/built-in skins (Day, Night, ILLUSIA, KAAK) never grow it
* automatically: for them it remains a fallback that only appears when the
* normal launcher is declared or observed unavailable while connected.
*/
export function shouldShowRecovery(input: RecoveryVisibilityInput): boolean {
if (!input.thirdPartyAllowed) return false;
if (input.thirdPartySkinActive) return true;
return input.connected && (input.launcherHiddenByConfig || !input.launcherReachable);
}
+118
View File
@@ -0,0 +1,118 @@
import { computed, readonly, ref, shallowRef } from "vue";
import { DECORATIVE_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
import { resolveHiddenHostParts, type SkinChromeDocument } from "../../../src/shared/skin-chrome.js";
import { isHostPartReachable } from "./host-chrome-visibility.js";
/**
* Host-owned state shared by Teleported host chrome components. Skin CSS can
* never mutate this state: it is only written by the host from a validated
* instance setting or a validated chrome.json document.
*/
const instanceHiddenParts = ref<ReadonlySet<string>>(new Set());
const skinChrome = shallowRef<SkinChromeDocument | undefined>(undefined);
const activeSkin = ref<string | undefined>(undefined);
/**
* Skins bundled with WebSpeak. They are never treated as "third-party" for the
* recovery affordance, so official Day/Night/ILLUSIA/KAAK stay decoration-free
* and gain no extra host chrome.
*/
const BUNDLED_SKIN_IDS: ReadonlySet<string> = new Set([
"builtin.light",
"builtin.dark",
"community.illusia-voice",
"community.kaak-voice",
]);
/** The id of the skin currently applied by `usePublicSkin`. */
export function setHostChromeActiveSkin(id: string | undefined): void {
activeSkin.value = id;
}
export function isBundledSkin(id: string | undefined): boolean {
return !id || id.startsWith("builtin.") || BUNDLED_SKIN_IDS.has(id);
}
/** True while a non-bundled (open / third-party) skin is applied. */
export function isThirdPartySkinActive(): boolean {
return !isBundledSkin(activeSkin.value);
}
/**
* Decorations (`host.watermark`, `host.hint`, `host.voice-status-decoration`)
* are hidden unless the active skin opts in with `chrome.json#visibleParts`,
* so official and built-in skins stay identical to production.
*/
const hiddenParts = computed(() => resolveHiddenHostParts(skinChrome.value, [...instanceHiddenParts.value]));
/** Instance-level default, supplied by /api/public-config. */
export function setInstanceHiddenParts(parts: readonly string[]): void {
instanceHiddenParts.value = new Set(parts.filter((part) => DECORATIVE_PART_IDS.has(part)));
}
/** The active skin's validated chrome.json (or undefined for built-in skins). */
export function setSkinHostChromeParts(document: SkinChromeDocument | undefined): void {
skinChrome.value = document;
}
export function isHostPartHidden(part: string): boolean {
return hiddenParts.value.has(part);
}
/**
* Read the live DOM to find out whether a host part can actually be used.
* Declarative hiding (`v-if`) removes the element entirely; CSS-only hiding
* leaves it in place, so this also checks computed style and on-screen bounds.
*/
export function isHostPartVisuallyReachable(part: string): boolean {
if (typeof document === "undefined" || typeof window === "undefined") return true;
const element = document.querySelector(`[data-ws-part="${part}"]`);
if (!element) return false;
const style = window.getComputedStyle(element);
const rect = element.getBoundingClientRect();
return isHostPartReachable({
display: style.display,
visibility: style.visibility,
opacity: style.opacity,
pointerEvents: style.pointerEvents,
clipPath: style.clipPath,
clip: style.clip,
rect: { width: rect.width, height: rect.height, left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom },
viewport: { width: window.innerWidth, height: window.innerHeight },
});
}
/** A monotonically increasing request counter; PluginPanel watches it. */
const libraryRequests = ref(0);
export const pluginLibraryRequests = readonly(libraryRequests);
export function openPluginLibrary(): void {
libraryRequests.value += 1;
}
/**
* Recovery's guaranteed escape hatch: reset to the built-in Day/Night skin.
* `usePublicSkin` watches this counter, so it works even when the skinnable
* plugin overlay is `display: none`.
*/
const builtInSkinRequests = ref(0);
export const hostBuiltInSkinRequests = readonly(builtInSkinRequests);
export function requestBuiltInSkin(): void {
builtInSkinRequests.value += 1;
}
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key">;
/**
* The documented recovery shortcut: Ctrl+Alt+Shift+R, or ⌘+⌥+⇧+R on macOS.
* The letter is matched case-insensitively, but every modifier is required so
* ordinary app shortcuts (Ctrl+R, Alt+R, Ctrl+Shift+R) keep their meaning.
*/
export function isRecoveryShortcut(event: RecoveryShortcutEvent): boolean {
return (event.ctrlKey || event.metaKey)
&& event.altKey
&& event.shiftKey
&& event.key.toLowerCase() === "r";
}
+135
View File
@@ -0,0 +1,135 @@
/**
* Closed-shadow, top-layer rendering layer for trusted host UI.
*
* Skin CSS is compiled to two scopes: `.ws-skin-root[data-ws-skin="…"] …` and
* `:root[data-ws-host-skin="…"] [data-ws-part="host.…"] …`. Content rendered in
* this layer satisfies neither:
*
* - it lives inside a closed shadow root, so no author selector can reach its
* internals (open or closed, author CSS never crosses a shadow boundary);
* - its host element carries no `data-ws-part`, so it never matches the
* document-level host-chrome scope either;
* - whichever of its children is promoted to the top layer (`<dialog>`
* `showModal()` / a `popover="manual"` element) paints above every normal
* stacking context, including `z-index: 2147483647`.
*
* The host element is also a fixed, pointer-transparent wrapper so a browser
* without the Popover API still shows the UI above ordinary content.
*/
export type HostOwnedLayerName = "recovery" | "authorization";
/**
* The CSS 32-bit maximum stacking value. A compiled skin may legitimately use
* `z-index: 2147483647` on a fullscreen part, so the pre-Popover fallback must
* not sit below it. At equal maximum stacking the host layer still paints on
* top: it is appended to `document.body` after `#app`, and later siblings win
* when the stacking level ties. The top-layer paths (`showPopover()` /
* `showModal()`) still outrank both.
*/
export const HOST_OWNED_LAYER_Z_INDEX = 2147483647;
export interface HostOwnedLayer {
readonly name: HostOwnedLayerName;
readonly host: HTMLElement;
/** Closed shadow root; only the host that created the layer holds this. */
readonly shadow: ShadowRoot;
/** Teleport target for the layer's Vue subtree. */
readonly container: HTMLElement;
dispose(): void;
}
const layers = new Set<HostOwnedLayer>();
/** Diagnostics / tests: enumerate live host-owned layers in this realm. */
export function hostOwnedLayers(): readonly HostOwnedLayer[] {
return [...layers];
}
/**
* Create a detached-from-skin-DOM host with a closed shadow root and inject the
* layer's stylesheet inside it. Returns `null` in a non-DOM environment.
*/
export function createHostOwnedLayer(name: HostOwnedLayerName, css: string): HostOwnedLayer | null {
if (typeof document === "undefined" || !document.body) return null;
const host = document.createElement("div");
host.setAttribute("data-ws-host-layer", name);
// The wrapper itself must never intercept clicks meant for the page; the
// promoted child re-enables pointer events for its own controls.
host.style.cssText = `position:fixed;inset:0;z-index:${HOST_OWNED_LAYER_Z_INDEX};pointer-events:none;overflow:visible;`;
const shadow = host.attachShadow({ mode: "closed" });
const style = document.createElement("style");
style.textContent = css;
const container = document.createElement("div");
container.setAttribute("data-ws-host-layer-content", name);
shadow.append(style, container);
document.body.append(host);
const layer: HostOwnedLayer = {
name,
host,
shadow,
container,
dispose() {
layers.delete(layer);
host.remove();
},
};
layers.add(layer);
return layer;
}
type PopoverCapableElement = HTMLElement & {
showPopover?: () => void;
hidePopover?: () => void;
matches?: (selector: string) => boolean;
};
/**
* Elements that already used the display fallback must never flap back to the
* Popover API: re-entering it could re-apply the UA `[popover] { display: none
* !important }` rule and hide the capsule again.
*/
const popoverFallbacks = new WeakSet<HTMLElement>();
/**
* Show or hide a manual recovery popover, with a display-based fallback.
*
* A closed `[popover]` is `display: none !important` in the UA stylesheet and
* has no `:popover-open` box, so simply setting `style.display` leaves it
* invisible. The fallback therefore removes the `popover` attribute before
* assigning `display`. The same path is used when the Popover API is missing
* or when top-layer promotion throws (for example in a constrained embed).
*/
export function syncRecoveryPopover(element: HTMLElement | null | undefined, visible: boolean): void {
if (!element) return;
const enterFallback = (): void => {
popoverFallbacks.add(element);
element.removeAttribute("popover");
element.style.display = visible ? "flex" : "none";
};
if (popoverFallbacks.has(element)) {
element.style.display = visible ? "flex" : "none";
return;
}
const candidate = element as PopoverCapableElement;
if (typeof candidate.showPopover !== "function") {
// Pre-Popover browsers: the fixed host layer is the only fallback.
enterFallback();
return;
}
try {
const open = candidate.matches?.(":popover-open") ?? false;
if (visible && !open) candidate.showPopover();
else if (!visible && open) candidate.hidePopover?.();
} catch {
// Constrained embeds may reject top-layer promotion. The fixed host layer
// is still there, but only the display fallback can actually reveal it.
enterFallback();
}
}
@@ -0,0 +1,128 @@
import assert from "node:assert/strict";
import test from "node:test";
import { isRecoveryShortcut } from "./host-chrome.js";
import { HOST_OWNED_LAYER_Z_INDEX, syncRecoveryPopover } from "./host-owned-layer.js";
type ShortcutEvent = {
ctrlKey: boolean;
metaKey: boolean;
altKey: boolean;
shiftKey: boolean;
key: string;
};
const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
ctrlKey: false,
metaKey: false,
altKey: false,
shiftKey: false,
key: "",
...overrides,
});
test("the recovery shortcut requires the full Ctrl/Cmd+Alt+Shift+R chord", () => {
assert.equal(isRecoveryShortcut(shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "r" })), true);
// macOS uses the Meta/Command key in place of Ctrl.
assert.equal(isRecoveryShortcut(shortcut({ metaKey: true, altKey: true, shiftKey: true, key: "R" })), true);
for (const rejected of [
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "x" }),
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "Enter" }),
// Ordinary app/browser shortcuts must stay available.
shortcut({ ctrlKey: true, key: "r" }),
shortcut({ altKey: true, key: "r" }),
shortcut({ ctrlKey: true, shiftKey: true, key: "r" }),
shortcut({ ctrlKey: true, altKey: true, key: "r" }),
shortcut({ ctrlKey: false, altKey: true, shiftKey: true, key: "r" }),
]) {
assert.equal(isRecoveryShortcut(rejected), false, JSON.stringify(rejected));
}
});
interface FakePopover {
style: { display: string };
showPopover?: () => void;
hidePopover?: () => void;
matches?: (selector: string) => boolean;
removedAttributes: string[];
removeAttribute(name: string): void;
}
const fakePopover = (overrides: Partial<FakePopover> = {}): FakePopover => {
const element: FakePopover = {
style: { display: "" },
removedAttributes: [],
removeAttribute(name: string) {
element.removedAttributes.push(name);
},
matches: () => false,
...overrides,
};
return element;
};
const asElement = (element: FakePopover) => element as unknown as HTMLElement;
test("a missing showPopover uses the display fallback, visible and hidden", () => {
const element = fakePopover();
syncRecoveryPopover(asElement(element), true);
assert.equal(element.style.display, "flex", "the capsule must be laid out without the Popover API");
syncRecoveryPopover(asElement(element), false);
assert.equal(element.style.display, "none");
syncRecoveryPopover(asElement(element), true);
assert.equal(element.style.display, "flex");
});
test("a throwing showPopover drops the popover attribute and shows the capsule", () => {
let calls = 0;
const element = fakePopover({
showPopover() {
calls += 1;
throw new Error("top-layer promotion rejected");
},
});
syncRecoveryPopover(asElement(element), true);
assert.deepEqual(element.removedAttributes, ["popover"], "the UA display:none rule must be removed");
assert.equal(element.style.display, "flex");
assert.notEqual(element.style.display, "none");
assert.equal(calls, 1);
// Once fallback is in use the element must not flap back to showPopover().
syncRecoveryPopover(asElement(element), false);
assert.equal(element.style.display, "none");
syncRecoveryPopover(asElement(element), true);
assert.equal(element.style.display, "flex");
assert.equal(calls, 1);
});
test("a working showPopover/hidePopover keeps the top-layer path", () => {
let open = false;
let shown = 0;
let hidden = 0;
const element = fakePopover({
showPopover() {
shown += 1;
open = true;
},
hidePopover() {
hidden += 1;
open = false;
},
matches: (selector) => selector === ":popover-open" && open,
});
syncRecoveryPopover(asElement(element), true);
assert.equal(shown, 1);
assert.equal(element.style.display, "", "the top-layer path must not force display");
syncRecoveryPopover(asElement(element), true);
assert.equal(shown, 1, "an already-open popover is not reopened");
syncRecoveryPopover(asElement(element), false);
assert.equal(hidden, 1);
assert.deepEqual(element.removedAttributes, [], "a working popover keeps its attribute");
});
test("the pre-Popover host layer uses the CSS 32-bit maximum z-index", () => {
assert.equal(HOST_OWNED_LAYER_Z_INDEX, 2147483647);
});
+76 -2
View File
@@ -105,15 +105,19 @@ test("all public skin parts are documented and the admin console is outside skin
const [components, adminComponents] = await Promise.all([
componentSources("../components/web-client/"), componentSources("../components/admin/"),
]);
const [webClient, demo, skinSwitcher, languageSwitcher, admin, documentation] = await Promise.all([
const [webClient, demo, skinSwitcher, languageSwitcher, hostChrome, pluginPanel, authorization, recoveryNotice, admin, documentation] = await Promise.all([
readFile(new URL("../views/WebClient.vue", import.meta.url), "utf8"),
readFile(new URL("../views/DemoView.vue", import.meta.url), "utf8"),
readFile(new URL("../components/SkinSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../components/LanguageSwitcher.vue", import.meta.url), "utf8"),
readFile(new URL("../components/HostChrome.vue", import.meta.url), "utf8"),
readFile(new URL("../components/PluginPanel.vue", import.meta.url), "utf8"),
readFile(new URL("../components/InstanceAuthorization.vue", import.meta.url), "utf8"),
readFile(new URL("../components/SkinLoadRecoveryNotice.vue", import.meta.url), "utf8"),
readFile(new URL("../views/AdminView.vue", import.meta.url), "utf8"),
readFile(new URL("../../../docs/SKIN_DEVELOPMENT.md", import.meta.url), "utf8"),
]);
const publicParts = new Set([...`${webClient}\n${components}\n${demo}\n${skinSwitcher}\n${languageSwitcher}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
const publicParts = new Set([...`${webClient}\n${components}\n${demo}\n${skinSwitcher}\n${languageSwitcher}\n${hostChrome}\n${pluginPanel}\n${authorization}\n${recoveryNotice}`.matchAll(/data-ws-part="([^"]+)"/g)].map((match) => match[1]));
for (const part of publicParts) assert.ok(documentation.includes(`\`${part}\``), `Undocumented skin part: ${part}`);
assert.match(skinSwitcher, /data-ws-skin-id/);
assert.match(skinSwitcher, /data-ws-state/);
@@ -1097,3 +1101,73 @@ function makeSkinV4(
const bytes = zipSync(packageFiles);
return new File([bytes.slice().buffer as ArrayBuffer], "skin-v4.wskin", { type: "application/octet-stream" });
}
function makeChromeSkin(
chrome: unknown,
options: { schemaVersion?: number; css?: string; icons?: Record<string, Uint8Array>; manifestChanges?: Record<string, unknown> } = {},
): File {
const schemaVersion = options.schemaVersion ?? 3;
const icons = options.icons ?? { "assets/icons/language.png": new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10, 1, 2, 3]) };
const packageFiles: Record<string, Uint8Array> = {
"manifest.json": strToU8(JSON.stringify({
...manifest,
schemaVersion,
...(schemaVersion >= 3 ? { packageType: "open-skin" } : {}),
chrome: "chrome.json",
...options.manifestChanges,
})),
"skin.css": strToU8(options.css ?? '[data-ws-part="host.plugins.launcher"] { background: #1d4f9c; }'),
"chrome.json": strToU8(JSON.stringify(chrome)),
...icons,
};
const bytes = zipSync(packageFiles);
return new File([bytes.slice().buffer as ArrayBuffer], "skin-chrome.wskin", { type: "application/octet-stream" });
}
test("open skins can theme host chrome and declare hidden parts plus bitmap icon overrides", async () => {
const skin = await importSkinPack(makeChromeSkin({
schemaVersion: 1,
hiddenParts: ["host.watermark", "host.hint"],
icons: { "language.trigger": "assets/icons/language.png" },
}));
assert.deepEqual(skin.chromeData?.hiddenParts, ["host.watermark", "host.hint"]);
assert.equal(skin.chrome, "chrome.json");
assert.match(skin.css, /:root\[data-ws-host-skin="ocean-night"\] \[data-ws-part="host\.plugins\.launcher"\]/);
assert.match(skin.css, /:root\[data-ws-host-skin="ocean-night"\] \[data-ws-part="host\.watermark"\] \{ display: none !important; \}/);
assert.match(skin.css, /\[data-ws-icon-slot="language\.trigger"\] \{ background-image: url\("wskin-asset:assets%2Ficons%2Flanguage\.png"\)/);
const resolved = resolveSkinCssAssets(skin.css, skin.assets);
assert.match(resolved.css, /blob:/);
resolved.objectUrls.forEach((url) => URL.revokeObjectURL(url));
});
test("chrome.json rejects protected hidden parts, unsafe icon paths, oversized bitmaps and old schema versions", async () => {
const protectedPart = makeChromeSkin({ schemaVersion: 1, hiddenParts: ["voice.audio-dock"], icons: { "language.trigger": "assets/icons/language.png" } });
await assert.rejects(importSkinPack(protectedPart), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_CHROME_HIDDEN_INVALID");
const badPath = makeChromeSkin({ schemaVersion: 1, icons: { "language.trigger": "../icons/language.png" } });
await assert.rejects(importSkinPack(badPath), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_ICON_PATH");
const missingIcon = makeChromeSkin({ schemaVersion: 1, icons: { "language.trigger": "assets/icons/missing.png" } }, { icons: {} });
await assert.rejects(importSkinPack(missingIcon), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_ICON_MISSING");
const oversized = makeChromeSkin({ schemaVersion: 1, icons: { "language.trigger": "assets/icons/language.png" } }, {
icons: { "assets/icons/language.png": new Uint8Array(64 * 1024 + 1) },
});
await assert.rejects(importSkinPack(oversized), (error: unknown) => error instanceof SkinPackError && error.code === "SKIN_ICON_SIZE");
await assert.rejects(importSkinPack(makeChromeSkin({ schemaVersion: 1 }, { schemaVersion: 1 })),
(error: unknown) => error instanceof SkinPackError);
await assert.rejects(importSkinPack(makeChromeSkin({ schemaVersion: 1 }, { schemaVersion: 2 })),
(error: unknown) => error instanceof SkinPackError && error.code === "SKIN_MANIFEST_INVALID");
});
test("open skin CSS cannot escape the host scope or hide essential controls", async () => {
await assert.rejects(
importSkinPack(makeChromeSkin({ schemaVersion: 1 }, { css: 'html [data-ws-part="host.watermark"] { color: red; }' })),
(error: unknown) => error instanceof SkinPackError && /cannot target html or body/.test(error.message),
);
await assert.rejects(
importSkinPack(makeChromeSkin({ schemaVersion: 1 }, { css: '[data-ws-part="voice.audio-dock"] { display: none; }' })),
(error: unknown) => error instanceof SkinPackError && /must remain available/.test(error.message),
);
});
+45 -9
View File
@@ -1,6 +1,14 @@
import { parseSkinWorkspacePolicy, type SkinWorkspacePolicy } from "../../../src/shared/skin-workspace.js";
import { unzipSync } from "fflate";
import { compileSkinCss as compileSharedSkinCss, rewriteSkinCssAssets, SkinCssValidationError } from "../../../src/shared/skin-css.js";
import {
compileSkinChromeCss,
parseSkinChromeDocument,
SKIN_CHROME_MAX_BYTES,
SkinChromeError,
validateSkinChromeAssets,
type SkinChromeDocument,
} from "../../../src/shared/skin-chrome.js";
import { parseSkinLayoutJson, type SkinLayoutDocument } from "../../../src/shared/skin-layout.js";
import { listSkinPluginAssetPaths, parseSkinPluginJson, type SkinPluginDocument } from "../../../src/shared/skin-plugin.js";
@@ -39,6 +47,7 @@ export interface SkinManifest {
content?: string;
components?: string;
plugins?: string;
chrome?: string;
workspace?: SkinWorkspacePolicy;
minAppVersion: string;
preview?: string;
@@ -75,6 +84,7 @@ export interface InstalledSkin extends SkinManifest {
runtimePluginFiles?: Record<string, Blob>;
runtimePluginStyles?: Record<string, string>;
previewBlob?: Blob;
chromeData?: SkinChromeDocument;
warnings: string[];
installedAt: number;
}
@@ -145,7 +155,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
const assets: Record<string, Blob> = Object.create(null) as Record<string, Blob>;
const runtimePluginPaths = runtimePlugins ? listSkinRuntimePluginFilePaths(runtimePlugins) : [];
const runtimePluginPathSet = new Set(runtimePluginPaths.map((path) => path.toLowerCase()));
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.preview]
const manifestPathSet = ["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome, manifest.preview]
.filter((path): path is string => Boolean(path)).map((path) => path.toLowerCase());
if (runtimePluginPaths.some((path) => manifestPathSet.includes(path))) {
throw new SkinPackError("Plugin files cannot reuse skin manifest, CSS, content, component, or preview paths.", "SKIN_RUNTIME_PLUGIN_FILE_DUPLICATE");
@@ -184,7 +194,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
}
for (const [path, bytes] of files) {
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins].includes(path)
if (["manifest.json", manifest.entry, manifest.layout, manifest.content, manifest.components, manifest.plugins, manifest.chrome].includes(path)
|| runtimePluginPathSet.has(path.toLowerCase())) continue;
const mimeType = assetMimeType(path);
if (!mimeType) throw new SkinPackError(`Unsupported package file: ${path}`, "SKIN_FILE_UNSUPPORTED");
@@ -233,6 +243,26 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
catch (error) { throw new SkinPackError("layout.json is invalid: " + (error instanceof Error ? error.message : "unknown layout error"), "SKIN_LAYOUT_INVALID"); }
}
let chromeData: SkinChromeDocument | undefined;
if (manifest.chrome) {
const chromeBytes = files.get(manifest.chrome);
if (!chromeBytes || chromeBytes.byteLength > SKIN_CHROME_MAX_BYTES) {
throw new SkinPackError("chrome.json is missing or exceeds 32 KiB.", "SKIN_CHROME_SIZE");
}
try {
chromeData = parseSkinChromeDocument(decoder.decode(chromeBytes));
validateSkinChromeAssets(chromeData, (path) => {
const asset = assets[path];
return asset ? { bytes: asset.size, mime: asset.type } : undefined;
});
} catch (error) {
const chromeError = error instanceof SkinChromeError
? error
: new SkinChromeError(error instanceof Error ? error.message : "Invalid chrome.json.", "SKIN_CHROME_INVALID");
throw new SkinPackError(chromeError.message, chromeError.code);
}
}
let previewBlob: Blob | undefined;
if (manifest.preview) {
const previewBytes = files.get(manifest.preview);
@@ -248,9 +278,12 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
&& runtimePlugins?.plugins.some((plugin) => plugin.mode === "surface" && plugin.page === component.page));
if (hasConflictingSurface) throw new SkinPackError("A page cannot declare both a v3 and v4 surface.", "SKIN_PLUGIN_SURFACE_DUPLICATE");
// Host-owned additions are appended after author CSS so they win ties, and
// use wskin-asset markers resolved by resolveSkinCssAssets at activation.
const chromeCss = chromeData ? compileSkinChromeCss(chromeData, manifest.id) : "";
return {
...manifest,
css: compiled.css,
css: chromeCss ? `${compiled.css}\n${chromeCss}` : compiled.css,
assets,
contentData,
layoutData,
@@ -259,6 +292,7 @@ export async function importSkinPack(file: File): Promise<InstalledSkin> {
runtimePluginFiles,
runtimePluginStyles,
previewBlob,
...(chromeData ? { chromeData } : {}),
warnings: [...compiled.warnings, ...runtimePluginWarnings],
installedAt: Date.now(),
};
@@ -407,7 +441,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
if (schemaVersion !== 1 && schemaVersion !== 2 && schemaVersion !== 3 && schemaVersion !== 4) throw new SkinPackError("This skin package version is not supported.", "SKIN_SCHEMA_VERSION");
if (schemaVersion >= 2) {
const fields = new Set(["schemaVersion", "packageType", "id", "name", "version", "author", "license", "description", "entry", "layout", "permissions", "content", "minAppVersion", "preview"]);
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); fields.add("workspace"); }
if (schemaVersion >= 3) { fields.delete("permissions"); fields.add("components"); fields.add("workspace"); fields.add("chrome"); }
if (schemaVersion === 4) fields.add("plugins");
const unknown = Object.keys(raw).find((key) => !fields.has(key));
if (unknown) throw new SkinPackError(`Version 2 skin manifest contains an unsupported field: ${unknown}.`, "SKIN_MANIFEST_INVALID");
@@ -427,8 +461,8 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
if (schemaVersion === 4 && raw.packageType !== "open-skin") {
throw new SkinPackError("Version 4 skin packages must declare the open-skin type.", "SKIN_MANIFEST_INVALID");
}
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined || raw.components !== undefined || raw.plugins !== undefined)) {
throw new SkinPackError("Version 1 skin packages cannot declare layout or plugin fields.", "SKIN_SCHEMA_VERSION");
if (schemaVersion === 1 && (raw.layout !== undefined || raw.packageType !== undefined || raw.permissions !== undefined || raw.components !== undefined || raw.plugins !== undefined || raw.chrome !== undefined)) {
throw new SkinPackError("Version 1 skin packages cannot declare layout, chrome or plugin fields.", "SKIN_SCHEMA_VERSION");
}
let workspace: SkinWorkspacePolicy | undefined;
try { workspace = parseSkinWorkspacePolicy(raw.workspace, schemaVersion); }
@@ -439,17 +473,18 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
const layout = schemaVersion >= 2 ? stringField("layout", 120, schemaVersion === 2)! : undefined;
const components = schemaVersion >= 3 ? stringField("components", 120, false) : undefined;
const plugins = schemaVersion === 4 ? stringField("plugins", 120)! : undefined;
const chrome = schemaVersion >= 3 ? stringField("chrome", 120, false) : undefined;
const content = stringField("content", 120, false);
const preview = stringField("preview", 120, false);
for (const path of [entry, layout, content, components, plugins, preview].filter((item): item is string => Boolean(item))) {
for (const path of [entry, layout, content, components, plugins, chrome, preview].filter((item): item is string => Boolean(item))) {
if (path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => !part || part === "." || part === "..")) throw new SkinPackError(`manifest.json has an unsafe path: ${path}`, "SKIN_PATH_INVALID");
}
const semver = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
const version = stringField("version", 32)!;
const minAppVersion = stringField("minAppVersion", 32)!;
if (!semver.test(version) || !semver.test(minAppVersion)) throw new SkinPackError("Skin and minimum app versions must use semantic version format.", "SKIN_MANIFEST_INVALID");
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
if (!entry.toLowerCase().endsWith(".css") || (layout && !layout.toLowerCase().endsWith(".json")) || (content && !content.toLowerCase().endsWith(".json")) || (components && !components.toLowerCase().endsWith(".json")) || (plugins && !plugins.toLowerCase().endsWith(".json")) || (chrome && !chrome.toLowerCase().endsWith(".json")) || (preview && !assetMimeType(preview)?.startsWith("image/"))) throw new SkinPackError("The CSS entry, layout, content, chrome, plugin, or preview path is invalid.", "SKIN_MANIFEST_INVALID");
const declaredFiles = ["manifest.json", entry, ...(layout ? [layout] : []), ...(content ? [content] : []), ...(components ? [components] : []), ...(plugins ? [plugins] : []), ...(chrome ? [chrome] : []), ...(preview ? [preview] : [])].map((item) => item.toLowerCase());
if (new Set(declaredFiles).size !== declaredFiles.length) throw new SkinPackError("Manifest files must use separate package paths.", "SKIN_MANIFEST_INVALID");
return {
schemaVersion,
@@ -465,6 +500,7 @@ function parseManifest(bytes: Uint8Array): SkinManifest {
content,
components,
plugins,
chrome,
minAppVersion,
...(workspace ? { workspace } : {}),
preview,
+6
View File
@@ -7,6 +7,7 @@ import { getBundledSkinPackageUrl, isPublicSkinEnabled } from "./skin-catalog.js
import { createSkinOperation, type SkinLoadOptions } from "./skin-operation.js";
import { setSkinLayoutPackage } from "./skin-layout-runtime.js";
import { canUseSkin } from './instance-authorization.js';
import { HOST_SKIN_ATTRIBUTE } from '../../../src/shared/skin-visual-parts.js';
export const ACTIVE_SKIN_KEY = "webspeak:active-skin";
export const BUILTIN_LIGHT_SKIN = "builtin.light";
@@ -112,6 +113,10 @@ async function prepareAndActivate(id: string, expectedVersion: string | undefine
document.querySelectorAll<HTMLElement>(".ws-skin-root").forEach((clientRoot) => {
clientRoot.dataset.wsSkin = skin!.id;
});
// Host chrome lives outside `.ws-skin-root` (Teleport to body). A
// document-level marker lets compiled host rules reach it, but only while
// this exact skin is active; removing the skin removes the marker.
document.documentElement.setAttribute(HOST_SKIN_ATTRIBUTE, skin!.id);
markCoreControls();
let style = document.getElementById(CUSTOM_STYLE_ID) as HTMLStyleElement | null;
@@ -155,6 +160,7 @@ export function clearCustomSkinStyle(): void {
function removeCustomSkinStyle(): void {
document.getElementById(CUSTOM_STYLE_ID)?.remove();
document.getElementById(CUSTOM_BASE_STYLE_ID)?.remove();
document.documentElement.removeAttribute(HOST_SKIN_ATTRIBUTE);
activeAssetUrls.forEach((url) => URL.revokeObjectURL(url));
activeAssetUrls = [];
}
+3 -1
View File
@@ -12,7 +12,7 @@
/>
<header class="demo-header" data-ws-part="demo.header">
<div class="demo-brand" data-ws-part="demo.brand"><span><Icon name="waveform" :size="21" /></span><div><strong>WebSpeak</strong><small>{{ copy.browserClient }}</small></div></div>
<div class="demo-tools" data-ws-part="demo.header-tools"><span class="demo-badge" data-ws-part="demo.badge">{{ copy.demoBadge }}</span><SkinSwitcher v-model="activeSkinId" data-ws-part="demo.skin-switcher" :menu-label="copy.skinSelector" :options="skinOptions" @change="onSkinChange" /><LanguageSwitcher v-model="language" data-ws-part="demo.language-switcher" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/" data-ws-part="demo.home-link">{{ copy.back }}</a></div>
<div class="demo-tools" data-ws-part="demo.header-tools"><span class="demo-badge" data-ws-part="demo.badge">{{ copy.demoBadge }}</span><SkinSwitcher v-model="activeSkinId" data-ws-part="demo.skin-switcher" :menu-label="copy.skinSelector" :options="skinOptions" @change="onSkinChange" /><LanguageSwitcher skin-icon v-model="language" data-ws-part="demo.language-switcher" :menu-label="copy.languageMenu" @change="persistLanguage" /><a href="/" data-ws-part="demo.home-link">{{ copy.back }}</a></div>
</header>
<div v-if="reconnecting" class="demo-reconnect" data-ws-part="demo.reconnect" role="status"><Icon name="refresh" :size="17" /><span>{{ copy.reconnecting }}</span><button type="button" data-ws-part="demo.reconnect.restore" @click="reconnecting = false">{{ copy.restore }}</button></div>
@@ -59,12 +59,14 @@
</div>
<SkinLoadRecoveryNotice :error="skinLoadError" :language="language" @use-built-in="switchToBuiltInAfterLoadError" />
<InstanceAuthorization :language="language" />
<HostChrome :language="language" />
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import Icon from "../components/Icon.vue";
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
import HostChrome from '../components/HostChrome.vue';
import "../styles/skin-plugin.css";
import SkinPluginOutlet from "../components/SkinPluginOutlet.js";
import LanguageSwitcher from "../components/LanguageSwitcher.vue";
+14 -7
View File
@@ -259,15 +259,16 @@
data-ws-part="home.footer"
>
<div class="ws-skin-mount-slot" data-ws-skin-mount="home.footer.before"></div>
<span>WebSpeak</span><span class="footer-separator">·</span
><span>{{ t("teamSpeakClient") }}</span
<span data-ws-part="home.footer.decoration">WebSpeak</span><span class="footer-separator" data-ws-part="home.footer.decoration">·</span
><span data-ws-part="home.footer.decoration">{{ t("teamSpeakClient") }}</span
><span class="footer-spacer"></span
><button
type="button"
class="clear-local-button"
data-ws-part="home.footer.clear"
@click="clearBrowserData"
>{{ t("clearLocalData") }}</button
><span class="footer-separator">·</span><span>{{ t("browserSupport") }}</span>
><span class="footer-separator" data-ws-part="home.footer.decoration">·</span><span data-ws-part="home.footer.decoration">{{ t("browserSupport") }}</span>
</footer>
<!-- QQ community modal -->
@@ -469,7 +470,7 @@
:screen-share-web-rtc-stats="screenShareWebRtcStats"
:t="t"
/>
<div id="webspeak-plugin-toolbar" class="webspeak-plugin-toolbar-host" data-ws-part="voice.plugin-toolbar"></div>
<div id="webspeak-plugin-toolbar" ref="pluginToolbarTarget" class="webspeak-plugin-toolbar-host" data-ws-part="voice.plugin-toolbar"></div>
<button
class="header-action"
:title="t('copyInvite')"
@@ -515,9 +516,10 @@
class="workspace-skin-switcher"
:menu-label="t('skinSelector')"
:options="skinOptions"
:plugin-library-available="voiceState.connected && Boolean(pluginSession)"
@change="onSkinChange"
/>
<LanguageSwitcher
<LanguageSwitcher skin-icon
v-model="language"
class="workspace-language"
:menu-label="t('languageMenu')"
@@ -797,13 +799,14 @@
class="mobile-skin-switcher"
:menu-label="t('skinSelector')"
:options="skinOptions"
:plugin-library-available="voiceState.connected && Boolean(pluginSession)"
@change="onSkinChange"
/>
<div class="language-menu-row"
><Icon
name="globe"
:size="18" /><span>{{ t("languageMenu") }}</span
><LanguageSwitcher
><LanguageSwitcher skin-icon
v-model="language"
:menu-label="t('languageMenu')"
@change="persistLanguage"
@@ -871,7 +874,8 @@
<div class="ws-skin-mount-slot" data-ws-skin-mount="voice.workspace.overlay"></div>
</div>
<PluginPanel :session-token="pluginSession" :gateway-url="pluginVoiceSocket?.url ?? ''" :connected="voiceState.connected" :language="language" />
<PluginPanel :session-token="pluginSession" :gateway-url="pluginVoiceSocket?.url ?? ''" :connected="voiceState.connected" :language="language" :toolbar-target="pluginToolbarTarget" />
<HostChrome :language="language" :connected="voiceState.connected" :plugin-library-available="voiceState.connected && Boolean(pluginSession)" />
<IdentityImportDialog
v-if="identityImportOpen"
v-model="identityImportText"
@@ -1007,6 +1011,7 @@ import { useWebClientChannels, type TreeChannel } from "../composables/useWebCli
import { useWebClientConnection } from "../composables/useWebClientConnection.js";
import { useWebClientMembers } from "../composables/useWebClientMembers.js";
import PluginPanel from "../components/PluginPanel.vue";
import HostChrome from "../components/HostChrome.vue";
import InstanceAuthorization from '../components/InstanceAuthorization.vue';
import WorkspaceInviteDialog from "../components/web-client/WorkspaceInviteDialog.vue";
import { useVoiceWebSocket, type ChannelMember, type ChatMessage } from "../composables/useVoiceWebSocket.js";
@@ -1170,6 +1175,7 @@ const skinPluginDocument = computed<SkinPluginDocument>(() => {
if (!skin) return emptySkinPluginDocument;
return loadSkinPluginAuthoringDocument(skin.id, skin.version) ?? skin.pluginData ?? emptySkinPluginDocument;
});
const pluginToolbarTarget = ref<HTMLElement | null>(null);
const skinPluginSurfaceActive = ref(false);
const skinRuntimePluginSurfaceActive = ref(false);
watch(activeSkin, () => {
@@ -1918,6 +1924,7 @@ const skinPluginWidgets = {
onChange: onSkinChange,
}),
"app.language-switcher": () => h(LanguageSwitcher, {
skinIcon: true,
modelValue: language.value,
"onUpdate:modelValue": (value: Language) => { language.value = value; },
menuLabel: t("languageMenu"),