feat(skin): dock recovery as host-owned toolbar buttons

Add chrome.json slot mode "toolbar" with grouped and per-action recovery buttons, page-specific anchor candidates and sanitized toolbar style tokens. Keep the floating capsule as the bad-anchor fallback, hide the duplicate plugin launcher, and preserve legacy capsule slots. Document the full contract, add a minimal toolbar example package, and cover the new behavior in unit and browser tests.
This commit is contained in:
OddTurtleHead committed 2026-11-26 23:06:43 +08:00
1 parent 9a12e2ee7b
commit 881354e283
33 files changed
+2016 -113

No files matched your search

+353 -61
View File
@@ -28,8 +28,77 @@
<!-- 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. -->
`data-ws-part`: there is intentionally no skin hook for this control.
With an explicit `chrome.json` `mode: "toolbar"` the host paints plain
host buttons instead of the capsule shell. The buttons are still owned,
labelled, focusable and clickable by the host; the skin only supplies
an anchor and style tokens. -->
<Teleport v-if="layer" :to="layer.container">
<!-- One grouped toolbar entry: both actions share an anchor. -->
<div
v-if="groupToolbarConfig"
ref="groupToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="built-in"
:title="copy.shortcut"
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
v-if="pluginLibraryAvailable"
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
>{{ copy.library }}</button>
</div>
<!-- Per-action toolbar entries: each action has its own anchor. -->
<div
v-if="builtInToolbarConfig"
ref="builtInToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="built-in"
:title="copy.shortcut"
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
</div>
<div
v-if="libraryToolbarConfig"
ref="libraryToolbarElement"
popover="manual"
class="ws-host-toolbar"
data-ws-host-recovery-toolbar
role="group"
:aria-label="copy.recovery"
>
<button
type="button"
class="ws-host-toolbar-action"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
>{{ copy.library }}</button>
</div>
<div
ref="recoveryPopover"
popover="manual"
@@ -38,7 +107,7 @@
@focusout="onRecoveryFocusOut"
class="ws-host-recovery"
:class="{ 'ws-host-recovery-compact': compact }"
:data-ws-float="slotMode === 'slotted' ? undefined : floatPosition"
:data-ws-float="capsuleSlotConfig && slotMode === 'slotted' ? undefined : floatPosition"
:tabindex="compact || compactPinned ? 0 : undefined"
data-ws-host-recovery
role="region"
@@ -46,6 +115,7 @@
>
<span class="ws-host-recovery-mark" aria-hidden="true">◈</span>
<button
v-if="capsuleActions.includes('built-in')"
type="button"
class="ws-host-recovery-action"
data-ws-recovery-action="built-in"
@@ -53,9 +123,9 @@
@click="useBuiltInSkin"
>{{ copy.useBuiltIn }}</button>
<button
v-if="capsuleActions.includes('library') && pluginLibraryAvailable"
type="button"
class="ws-host-recovery-action"
v-if="pluginLibraryAvailable"
data-ws-recovery-action="library"
:title="copy.library"
@click="openLibrary"
@@ -65,8 +135,9 @@
</template>
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from "vue";
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch, watchEffect, type Ref } from "vue";
import type { SiteLanguage } from "../../../src/site-copy.js";
import type { SkinChromeSlot } from "../../../src/shared/skin-chrome.js";
import { hostChromeCopy } from "../i18n/host-chrome.js";
import {
activeHostSlot,
@@ -77,6 +148,7 @@ import {
isThirdPartySkinActive,
openPluginLibrary,
requestBuiltInSkin,
setInlineLibraryEntryVisible,
} from "../services/host-chrome.js";
import {
createHostOwnedLayer,
@@ -96,6 +168,9 @@ import {
bindHostControlTheme,
findSkinRoot,
} from "../services/host-control-tokens.js";
import {
resolveHostRecoveryPresentation,
} from "../services/host-recovery-presentation.js";
const props = withDefaults(defineProps<{ language: SiteLanguage; connected?: boolean; pluginLibraryAvailable?: boolean }>(), { connected: false });
const copy = computed(() => hostChromeCopy[props.language] ?? hostChromeCopy.en);
@@ -164,8 +239,55 @@ const RECOVERY_LAYER_CSS = `
min-height: var(--ws-control-hit, 28px);
}
.ws-host-recovery.ws-host-recovery-compact:focus-visible { outline: 2px solid var(--ws-control-accent, #4c8f88); outline-offset: 2px; }
/* Toolbar mode: no capsule shell, margin, border or fixed shadow. The wrapper
only lays the host buttons out; every visible surface comes from the
--ws-toolbar-* variables resolved from the skin's validated tokens. */
.ws-host-toolbar {
position: fixed;
inset: auto;
margin: 0;
padding: 0;
border: 0;
background: transparent;
box-shadow: none;
align-items: center;
justify-content: flex-start;
flex-wrap: wrap;
gap: 4px;
max-width: calc(100vw - 8px);
pointer-events: auto;
}
.ws-host-toolbar:popover-open { display: flex; }
.ws-host-toolbar-action {
display: inline-flex;
align-items: center;
justify-content: center;
box-sizing: border-box;
min-height: var(--ws-toolbar-min-height, var(--ws-control-hit, 28px));
max-width: min(320px, calc(100vw - 8px));
padding: var(--ws-toolbar-padding-y, 6px) var(--ws-toolbar-padding-x, 12px);
border: 1px solid var(--ws-toolbar-border, #9db6b2);
border-radius: var(--ws-toolbar-radius, 6px);
background: var(--ws-toolbar-background, #fff);
color: var(--ws-toolbar-foreground, #31524f);
box-shadow: var(--ws-toolbar-shadow, none);
font-family: var(--ws-toolbar-font, ui-sans-serif, system-ui, sans-serif);
font-size: var(--ws-toolbar-font-size, 11px);
line-height: 1.25;
text-align: center;
white-space: normal;
overflow-wrap: anywhere;
cursor: pointer;
touch-action: manipulation;
}
.ws-host-toolbar-action:hover { filter: brightness(.96); }
.ws-host-toolbar-action:focus-visible {
outline: 2px solid var(--ws-toolbar-focus, var(--ws-control-accent, #4c8f88));
outline-offset: 2px;
}
@media (prefers-reduced-motion: reduce) {
.ws-host-recovery, .ws-host-recovery button { transition: none !important; }
.ws-host-recovery, .ws-host-recovery button, .ws-host-toolbar-action { transition: none !important; }
}
`;
@@ -190,14 +312,32 @@ const showRecovery = computed(() => shouldShowRecovery({
// already reset). It never renders decoration on its own.
const shortcutOpen = ref(false);
const recoveryPopover = ref<HTMLElement | null>(null);
const groupToolbarElement = ref<HTMLElement | null>(null);
const builtInToolbarElement = ref<HTMLElement | null>(null);
const libraryToolbarElement = ref<HTMLElement | null>(null);
let slotBinding: HostSlotBinding | undefined;
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
/**
* Theme the capsule even when the skin does not declare a slot. While a slot
* binding exists it reads the anchor first and owns the tokens; this
* root-level pass covers the slot-less capsule and refreshes itself when the
* skin stylesheet arrives after the stored skin id.
* Optional anchor from the active skin's chrome.json. Only third-party skins
* can declare it; the host still owns the controls and the module falls back
* to the default corner whenever an anchor stops being usable.
*/
const slotConfig = computed(() => activeHostSlot("host.recovery"));
const builtInSlotConfig = computed(() => activeHostSlot("host.recovery.built-in"));
const librarySlotConfig = computed(() => activeHostSlot("host.recovery.library"));
const groupToolbarConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? slotConfig.value : undefined);
const capsuleSlotConfig = computed<SkinChromeSlot | undefined>(() => slotConfig.value?.mode === "toolbar" ? undefined : slotConfig.value);
const builtInToolbarConfig = computed<SkinChromeSlot | undefined>(() => builtInSlotConfig.value?.mode === "toolbar" ? builtInSlotConfig.value : undefined);
const libraryToolbarConfig = computed<SkinChromeSlot | undefined>(() => librarySlotConfig.value?.mode === "toolbar" ? librarySlotConfig.value : undefined);
/**
* Theme the capsule even when the skin does not declare a slot. While a
* capsule slot binding exists it reads the anchor first and owns the tokens;
* this root-level pass covers the slot-less capsule and refreshes itself when
* the skin stylesheet arrives after the stored skin id. Toolbar bindings keep
* their own `--ws-toolbar-*` variables and do not disable this pass, so the
* floating fallback keeps the capsule palette.
*/
const recoveryTheme = layer ? bindHostControlTheme({
layer,
@@ -205,19 +345,43 @@ const recoveryTheme = layer ? bindHostControlTheme({
part: "host.recovery",
defaults: RECOVERY_CONTROL_DEFAULTS,
source: () => findSkinRoot(hostChromeActiveSkinId.value),
// While a slot binding exists it owns the capsule tokens (anchor first).
active: () => !slotBinding,
active: () => !capsuleBinding,
}) : null;
const recoveryVisible = computed(() => showRecovery.value || (shortcutOpen.value && thirdPartyAllowed.value));
/**
* Optional anchor from the active skin's chrome.json. Only third-party skins
* can declare it; the host still owns the capsule and the module falls back to
* the default corner whenever the anchor stops being usable.
*/
const slotConfig = computed(() => activeHostSlot("host.recovery"));
const slotMode = ref<"floating" | "slotted">("floating");
const groupToolbarMode = ref<"floating" | "slotted">("floating");
const builtInToolbarMode = ref<"floating" | "slotted">("floating");
const libraryToolbarMode = ref<"floating" | "slotted">("floating");
const builtInActionState = computed(() => ({
available: Boolean(groupToolbarConfig.value || builtInToolbarConfig.value),
docked: groupToolbarConfig.value
? groupToolbarMode.value === "slotted"
: builtInToolbarMode.value === "slotted",
}));
const libraryActionState = computed(() => ({
available: Boolean(props.pluginLibraryAvailable) && Boolean(groupToolbarConfig.value || libraryToolbarConfig.value),
docked: groupToolbarConfig.value
? groupToolbarMode.value === "slotted"
: libraryToolbarMode.value === "slotted",
}));
const presentation = computed(() => resolveHostRecoveryPresentation({
visible: recoveryVisible.value,
shortcutOpen: shortcutOpen.value,
libraryAvailable: Boolean(props.pluginLibraryAvailable),
builtIn: builtInActionState.value,
library: libraryActionState.value,
}));
const capsuleActions = computed(() => presentation.value.capsuleActions);
// Exactly one application-library entry per page: the host toolbar button is
// the library entry while a toolbar slot exists, so PluginPanel hides its
// ordinary launcher (including while the capsule fallback shows the button).
watchEffect(() => {
setInlineLibraryEntryVisible(presentation.value.suppressLauncher);
});
const compactHold = ref(true);
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
@@ -255,11 +419,15 @@ let floatingElement: HTMLElement | null = null;
/** Sticky `:hover` after a tap on touch screens must not pause avoidance. */
const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches;
const compact = computed(() => !shortcutExpanded.value
&& !compactPinned.value
&& (slotMode.value === "slotted"
? Boolean(slotConfig.value?.compact) && !compactHold.value
: floatCompact.value));
const compact = computed(() => {
if (shortcutExpanded.value || compactPinned.value) return false;
const config = capsuleSlotConfig.value;
if (config) return Boolean(config.compact) && !compactHold.value;
// A toolbar-mode capsule is the fallback entry, not the target look: never
// fold it, otherwise a failed anchor could leave only a small mark.
if (groupToolbarConfig.value || builtInToolbarConfig.value || libraryToolbarConfig.value) return false;
return floatCompact.value;
});
function onRecoveryEscape() {
shortcutOpen.value = false;
@@ -282,25 +450,93 @@ function onRecoveryFocusOut(event: FocusEvent) {
compactPinned.value = false;
}
function syncSlotBinding() {
slotBinding?.dispose();
slotBinding = undefined;
// Disposing a slot clears its inline tokens; restore the root-level theme
// before deciding whether a new anchor should override it.
recoveryTheme?.apply();
// A fresh binding starts floating and reports its first successful dock.
slotMode.value = "floating";
const control = recoveryPopover.value;
const config = slotConfig.value;
if (!control || !config || !layer) return;
slotBinding = bindHostSlot({
let capsuleBinding: HostSlotBinding | undefined;
let toolbarBindings: HostSlotBinding[] = [];
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, presentation.value.capsuleVisible);
}
function syncToolbarPopovers() {
const visible = presentation.value.toolbar.visible;
syncRecoveryPopover(
groupToolbarElement.value,
Boolean(groupToolbarConfig.value) && visible && groupToolbarMode.value === "slotted",
);
syncRecoveryPopover(
builtInToolbarElement.value,
Boolean(builtInToolbarConfig.value) && visible && builtInToolbarMode.value === "slotted",
);
syncRecoveryPopover(
libraryToolbarElement.value,
Boolean(libraryToolbarConfig.value) && Boolean(props.pluginLibraryAvailable)
&& visible && libraryToolbarMode.value === "slotted",
);
}
function bindToolbarEntry(
control: HTMLElement | null,
config: SkinChromeSlot | undefined,
mode: Ref<"floating" | "slotted">,
) {
if (!layer || !control || !config) return;
toolbarBindings.push(bindHostSlot({
layer,
control,
anchor: config.anchor,
skinId: hostChromeActiveSkinId.value,
align: config.align,
onModeChange: change => { slotMode.value = change.mode; },
});
presentation: "toolbar",
// A floating toolbar is a closed popover (display:none). Show it for the
// synchronous measurement/hit test and hide it again unless it docked.
prepare: () => syncRecoveryPopover(control, true),
settle: slotted => {
if (!slotted || !presentation.value.toolbar.visible) syncRecoveryPopover(control, false);
},
onModeChange: change => {
mode.value = change.mode;
syncPopover();
syncToolbarPopovers();
},
}));
}
function syncSlotBindings() {
capsuleBinding?.dispose();
capsuleBinding = undefined;
for (const binding of toolbarBindings) binding.dispose();
toolbarBindings = [];
// Disposing a slot clears its inline tokens; restore the root-level theme
// before deciding whether a new anchor should override it.
recoveryTheme?.apply();
// A fresh binding starts floating and reports its first successful dock.
slotMode.value = "floating";
groupToolbarMode.value = "floating";
builtInToolbarMode.value = "floating";
libraryToolbarMode.value = "floating";
const capsuleConfig = capsuleSlotConfig.value;
if (recoveryPopover.value && capsuleConfig && layer) {
capsuleBinding = bindHostSlot({
layer,
control: recoveryPopover.value,
anchor: capsuleConfig.anchor,
skinId: hostChromeActiveSkinId.value,
align: capsuleConfig.align,
onModeChange: change => { slotMode.value = change.mode; },
});
}
bindToolbarEntry(groupToolbarElement.value, groupToolbarConfig.value, groupToolbarMode);
bindToolbarEntry(builtInToolbarElement.value, builtInToolbarConfig.value, builtInToolbarMode);
if (props.pluginLibraryAvailable) {
bindToolbarEntry(libraryToolbarElement.value, libraryToolbarConfig.value, libraryToolbarMode);
}
syncPopover();
syncToolbarPopovers();
}
function revalidateBindings() {
capsuleBinding?.revalidate();
for (const binding of toolbarBindings) binding.revalidate();
}
function bindFloating() {
@@ -341,10 +577,6 @@ function bindFloating() {
});
}
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
}
function useBuiltInSkin() {
shortcutOpen.value = false;
requestBuiltInSkin();
@@ -364,8 +596,11 @@ function onKeydown(event: KeyboardEvent) {
shortcutOpen.value = true;
shortcutExpanded.value = true;
void nextTick(() => {
// The shortcut always brings back the complete capsule, even while a
// toolbar anchor is healthy.
syncPopover();
slotBinding?.revalidate();
syncToolbarPopovers();
revalidateBindings();
recoveryPopover.value?.querySelector("button")?.focus();
});
}
@@ -376,30 +611,66 @@ function refreshLauncherReachability() {
launcherReachable.value = isHostPartVisuallyReachable("host.plugins.launcher");
}
watch([recoveryVisible, recoveryPopover], () => {
void nextTick(() => {
syncPopover();
slotBinding?.revalidate();
bindFloating();
floatingAvoidance?.revalidate();
});
}, { flush: "post" });
watch(
[recoveryVisible, recoveryPopover, groupToolbarElement, builtInToolbarElement, libraryToolbarElement],
() => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
bindFloating();
floatingAvoidance?.revalidate();
});
},
{ flush: "post" },
);
watch([recoveryPopover, hostChromeActiveSkinId], () => {
void nextTick(() => recoveryTheme?.apply());
}, { flush: "post", immediate: true });
watch([slotConfig, hostChromeActiveSkinId], () => {
void nextTick(() => {
syncPopover();
syncSlotBinding();
});
}, { flush: "post" });
watch(
[
slotConfig,
builtInSlotConfig,
librarySlotConfig,
hostChromeActiveSkinId,
groupToolbarElement,
builtInToolbarElement,
libraryToolbarElement,
() => props.pluginLibraryAvailable,
],
() => {
void nextTick(() => {
syncSlotBindings();
bindFloating();
});
},
{ flush: "post" },
);
// Home <-> voice page and skin switches replace the controls the floating
// capsule was avoiding; re-place it promptly (and back to its default corner
// when that is free) instead of leaving it where the previous screen needed it.
watch([() => props.connected, hostChromeActiveSkinId], () => {
void nextTick(() => floatingAvoidance?.screenChanged());
void nextTick(() => {
revalidateBindings();
floatingAvoidance?.screenChanged();
});
}, { flush: "post" });
watch(thirdPartyAllowed, allowed => { if (!allowed) shortcutOpen.value = false; });
// Opening or closing the shortcut changes which presentation is active; docked
// toolbar buttons must hide while the complete capsule is summoned, and come
// back (if their anchor is still valid) when it closes.
watch(shortcutOpen, () => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
});
}, { flush: "post" });
// A page switch can mount a new `.ws-skin-root` with a different
// `data-ws-page` without changing the skin id. Re-resolve the declared anchor
// candidates promptly instead of waiting for the periodic safety check.
let pageObserver: MutationObserver | undefined;
onMounted(() => {
refreshLauncherReachability();
@@ -407,16 +678,37 @@ onMounted(() => {
window.addEventListener("resize", refreshLauncherReachability);
window.addEventListener("keydown", onKeydown, true);
window.addEventListener("pointerdown", onDocumentPointerDown, true);
if (typeof MutationObserver === "function") {
pageObserver = new MutationObserver(() => {
void nextTick(() => {
syncPopover();
syncToolbarPopovers();
revalidateBindings();
floatingAvoidance?.screenChanged();
});
});
pageObserver.observe(document.documentElement, {
subtree: true,
attributes: true,
attributeFilter: ["data-ws-page", "data-ws-skin"],
});
}
void nextTick(() => {
syncPopover();
syncSlotBinding();
syncSlotBindings();
bindFloating();
});
});
onBeforeUnmount(() => {
if (reachabilityTimer) clearInterval(reachabilityTimer);
if (compactHoldTimer) clearTimeout(compactHoldTimer);
slotBinding?.dispose();
pageObserver?.disconnect();
pageObserver = undefined;
capsuleBinding?.dispose();
capsuleBinding = undefined;
for (const binding of toolbarBindings) binding.dispose();
toolbarBindings = [];
setInlineLibraryEntryVisible(false);
floatingAvoidance?.dispose();
floatingAvoidance = undefined;
floatingElement = null;
+5 -2
View File
@@ -1,7 +1,7 @@
<template>
<Teleport :to="toolbarTarget ?? 'body'">
<div v-if="thirdPartyAllowed && connected && sessionToken" ref="toolbar" class="ws-plugin-toolbar" :class="{ 'ws-plugin-toolbar-fallback': !toolbarTarget }" :data-ws-float="toolbarTarget ? undefined : fallbackPosition" data-ws-part="voice.plugin-launcher" :data-presentation="presentation" :data-theme="theme" @keydown.esc="dismissDrawer">
<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="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @click="toggle">
<button v-if="!isHostPartHidden('host.plugins.launcher') && !inlineLibraryEntry" 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="presentation === 'dialog' ? visible : drawerOpen" :aria-controls="drawerOpen ? drawerId : undefined" @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>
<span v-if="presentation === 'drawer-side'">{{ tr('title') }}</span>
</button>
@@ -68,7 +68,7 @@ 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';
import { isHostPartHidden, isHostPartVisuallyReachable, pluginLibraryRequests } from '../services/host-chrome.js';
import { isHostPartHidden, isHostPartVisuallyReachable, isInlineLibraryEntryVisible, pluginLibraryRequests } from '../services/host-chrome.js';
import type { SkinPluginWidgetOptions } from '../../../src/shared/skin-plugin.js';
import { bindFloatingAvoidance, type FloatingAvoidance, type FloatingPosition } from '../services/host-floating-placement.js';
const props = defineProps<{ sessionToken: string; gatewayUrl: string; connected: boolean; language: SiteLanguage; toolbarTarget: HTMLElement | null; presentation: NonNullable<SkinPluginWidgetOptions['pluginPresentation']> }>();
@@ -77,6 +77,9 @@ const ui = computed(() => pluginWindowTranslations[props.language]);
const windowElement = ref<HTMLElement | null>(null), launcher = ref<HTMLButtonElement | null>(null), frame = ref<HTMLIFrameElement | null>(null);
const available = shallowRef<AvailablePluginApp[]>([]), current = shallowRef<PluginAppLaunch | null>(null);
const toolbar = ref<HTMLElement | null>(null);
// A toolbar-mode recovery slot already renders the host-owned application
// library button; do not render a second launcher on the same page.
const inlineLibraryEntry = computed(() => isInlineLibraryEntryVisible());
// The fallback toolbar floats in a viewport corner the skin knows nothing
// about; move it off any skin control it would cover (runtime only).
const fallbackPosition = ref<FloatingPosition>('bottom-right');
@@ -85,6 +85,41 @@ test("the recovery entry is persistent for third-party skins only", () => {
assert.equal(shouldShowRecovery({ ...base, thirdPartyAllowed: false, launcherHiddenByConfig: true }), false);
});
test("toolbar and per-action recovery slots are exposed for third-party skins", () => {
const document = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
slots: {
"host.recovery.built-in": {
mode: "toolbar",
anchor: ["skin.home.topbar.part-host-actions", "skin.voice.topbar.part-host-actions"],
},
"host.recovery.library": {
mode: "toolbar",
anchor: "skin.voice.topbar.part-host-library",
},
},
}));
setSkinHostChromeParts(document);
setHostChromeActiveSkin("community.toolbar");
try {
assert.deepEqual(activeHostSlot("host.recovery.built-in")?.anchor, [
"skin.home.topbar.part-host-actions",
"skin.voice.topbar.part-host-actions",
]);
assert.equal(activeHostSlot("host.recovery.built-in")?.mode, "toolbar");
assert.equal(activeHostSlot("host.recovery.library")?.mode, "toolbar");
assert.equal(activeHostSlot("host.recovery"), undefined);
// Bundled skins never see the toolbar declaration; their launcher stays.
setHostChromeActiveSkin("builtin.light");
assert.equal(activeHostSlot("host.recovery.built-in"), undefined);
assert.equal(activeHostSlot("host.recovery.library"), undefined);
} finally {
setSkinHostChromeParts(undefined);
setHostChromeActiveSkin(undefined);
}
});
test("slot declarations are honoured for third-party skins only", () => {
const document = parseSkinChromeDocument(JSON.stringify({
schemaVersion: 1,
@@ -97,9 +132,11 @@ test("slot declarations are honoured for third-party skins only", () => {
anchor: "voice.audio-dock",
align: "end",
compact: false,
mode: "capsule",
});
// A part that is not slottable cannot be selected through chrome.json.
assert.equal(activeHostSlot("host.permission"), undefined);
assert.equal(activeHostSlot("host.recovery.library"), undefined);
// Bundled/official skins keep the default floating placement.
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
+17
View File
@@ -104,6 +104,23 @@ export function openPluginLibrary(): void {
libraryRequests.value += 1;
}
/**
* True while a toolbar-mode recovery slot provides the application library.
* PluginPanel then hides its ordinary `host.plugins.launcher` so the same page
* has exactly one application-library entry. The state is host-only: a skin
* can request the slot through chrome.json, but cannot set this flag or click
* the host button.
*/
const inlineLibraryEntry = ref(false);
export function setInlineLibraryEntryVisible(visible: boolean): void {
inlineLibraryEntry.value = visible;
}
export function isInlineLibraryEntryVisible(): boolean {
return inlineLibraryEntry.value;
}
/**
* Recovery's guaranteed escape hatch: reset to the built-in Day/Night skin.
* `usePublicSkin` watches this counter, so it works even when the skinnable
@@ -9,19 +9,30 @@ import {
HOST_CONTROL_MIN_FOREGROUND_CONTRAST,
HOST_CONTROL_MIN_HIT_TARGET,
HOST_CONTROL_SIZE_METRICS,
HOST_TOOLBAR_APPLIED_VARIABLES,
PERMISSION_CONTROL_DEFAULTS,
RECOVERY_CONTROL_DEFAULTS,
SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS,
TOOLBAR_DEFAULT_PADDING_X,
TOOLBAR_DEFAULT_PADDING_Y,
TOOLBAR_DEFAULT_RADIUS,
TOOLBAR_MAX_FONT_SIZE,
TOOLBAR_MAX_HEIGHT,
TOOLBAR_MAX_PADDING,
applyHostControlTokens,
applyHostControlToolbarTokens,
contrastRatio,
fontFamilyNames,
formatRgb,
hasHostControlTokens,
hasHostToolbarTokens,
hostControlTokenKey,
hostControlTokenProperty,
hostToolbarTokenProperty,
parseCssColor,
relativeLuminance,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlRawTokens,
} from "./host-control-tokens.js";
@@ -281,3 +292,142 @@ test("host controls ignore fonts registered by a skin @font-face", () => {
assert.equal(resolve('"ws-community-evil-blank", sans-serif'), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
assert.equal(resolve("Tahoma, ws-community-evil-blank"), SKIN_LOAD_RECOVERY_CONTROL_DEFAULTS.font);
});
const resolveToolbar = (tokens: TokenMap = {}, global: TokenMap = {}) =>
resolveHostControlToolbarTokens(
style({ ...prefixed("host", {}), ...tokens, ...global }),
"host.recovery",
raw => raw,
RECOVERY_CONTROL_DEFAULTS,
);
test("toolbar tokens are independent of the capsule shell and keep host floors", () => {
const defaults = resolveToolbar();
assert.equal(defaults.background, "rgb(255, 255, 255)");
assert.equal(defaults.foreground, "rgb(49, 82, 79)");
assert.equal(defaults.border, "rgb(157, 182, 178)");
assert.equal(defaults.radius, TOOLBAR_DEFAULT_RADIUS, "a capsule radius must not leak into toolbar mode");
assert.equal(defaults.paddingX, TOOLBAR_DEFAULT_PADDING_X);
assert.equal(defaults.paddingY, TOOLBAR_DEFAULT_PADDING_Y);
assert.equal(defaults.minHeight, HOST_CONTROL_MIN_HIT_TARGET);
assert.equal(defaults.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
assert.equal(defaults.shadow, "none", "the capsule shadow must not be copied into toolbar mode");
const custom = resolveToolbar({
"--skin-recovery-toolbar-background": "#102030",
"--skin-recovery-toolbar-foreground": "#ffffff",
"--skin-recovery-toolbar-border": "#47dcc4",
"--skin-recovery-toolbar-radius": "10px",
"--skin-recovery-toolbar-font": "Tahoma, sans-serif",
"--skin-recovery-toolbar-font-size": "15px",
"--skin-recovery-toolbar-padding": "8px 18px",
"--skin-recovery-toolbar-height": "40px",
"--skin-recovery-toolbar-shadow": "0 2px 6px #00000033",
});
assert.equal(custom.background, "rgb(16, 32, 48)");
assert.equal(custom.foreground, "rgb(255, 255, 255)");
assert.equal(custom.border, "rgb(71, 220, 196)");
assert.equal(custom.radius, 10);
assert.equal(custom.font, "Tahoma, sans-serif");
assert.equal(custom.fontSize, 15);
assert.equal(custom.paddingX, 18);
assert.equal(custom.paddingY, 8);
assert.equal(custom.minHeight, 40);
assert.equal(custom.shadow, "0 2px 6px #00000033");
// Global toolbar tokens lose to the per-part set, but still override defaults.
const global = resolveToolbar({}, { "--skin-host-toolbar-background": "#222222", "--skin-host-toolbar-foreground": "#ffffff" });
assert.equal(global.background, "rgb(34, 34, 34)");
assert.equal(global.foreground, "rgb(255, 255, 255)");
});
test("unreadable or invalid toolbar tokens fall back to a visible, readable button", () => {
// Transparent backgrounds are treated as opaque RGB by parseCssColor; the
// result is unreadable against the text and the whole pair reverts.
const transparent = resolveToolbar({
"--skin-recovery-toolbar-background": "rgba(0, 0, 0, 0)",
"--skin-recovery-toolbar-foreground": "#111111",
});
assert.equal(transparent.background, "rgb(255, 255, 255)");
assert.equal(transparent.foreground, "rgb(49, 82, 79)");
assert.ok(contrastRatio(parseCssColor(transparent.foreground)!, parseCssColor(transparent.background)!) >= HOST_CONTROL_MIN_FOREGROUND_CONTRAST);
const lowContrast = resolveToolbar({
"--skin-recovery-toolbar-background": "#777777",
"--skin-recovery-toolbar-foreground": "#888888",
});
assert.equal(lowContrast.background, "rgb(255, 255, 255)");
assert.equal(lowContrast.foreground, "rgb(49, 82, 79)");
const invalid = resolveToolbar({
"--skin-recovery-toolbar-background": "not-a-colour",
"--skin-recovery-toolbar-foreground": "not-a-colour",
"--skin-recovery-toolbar-radius": "999px",
"--skin-recovery-toolbar-font": "url(https://example.invalid/font.woff2)",
"--skin-recovery-toolbar-font-size": "2px",
"--skin-recovery-toolbar-padding": "100px",
"--skin-recovery-toolbar-height": "2px",
"--skin-recovery-toolbar-shadow": "url(https://example.invalid/pixel)",
});
assert.equal(invalid.background, "rgb(255, 255, 255)");
assert.equal(invalid.foreground, "rgb(49, 82, 79)");
assert.equal(invalid.radius, 24, "the toolbar radius is clamped to its own maximum");
assert.equal(invalid.font, RECOVERY_CONTROL_DEFAULTS.font);
assert.equal(invalid.fontSize, HOST_CONTROL_MIN_FONT_SIZE);
// A syntactically valid but oversized padding is clamped, not applied raw.
assert.equal(invalid.paddingX, TOOLBAR_MAX_PADDING);
assert.equal(invalid.paddingY, TOOLBAR_MAX_PADDING);
assert.equal(invalid.minHeight, HOST_CONTROL_MIN_HIT_TARGET);
assert.equal(invalid.shadow, "none");
const oversized = resolveToolbar({
"--skin-recovery-toolbar-font-size": "64px",
"--skin-recovery-toolbar-height": "200px",
"--skin-recovery-toolbar-padding": "100px 100px",
});
assert.equal(oversized.fontSize, TOOLBAR_MAX_FONT_SIZE);
assert.equal(oversized.minHeight, TOOLBAR_MAX_HEIGHT);
assert.equal(oversized.paddingX, TOOLBAR_MAX_PADDING);
assert.equal(oversized.paddingY, TOOLBAR_MAX_PADDING);
});
test("toolbar tokens reject skin fonts and detect declarations", () => {
assert.equal(hostToolbarTokenProperty("host.recovery", "background"), "--skin-recovery-toolbar-background");
assert.equal(hostToolbarTokenProperty("host.recovery", "font-size"), "--skin-recovery-toolbar-font-size");
assert.equal(hasHostToolbarTokens(style({}), "host.recovery"), false);
assert.equal(hasHostToolbarTokens(style({ "--skin-host-toolbar-shadow": "none" }), "host.recovery"), true);
assert.equal(hasHostToolbarTokens(style({ "--skin-recovery-toolbar-padding": "4px" }), "host.recovery"), true);
const webFonts = new Set(["blank glyphs"]);
const font = resolveHostControlToolbarTokens(
style({ "--skin-recovery-toolbar-font": '"Blank Glyphs", sans-serif' }),
"host.recovery",
raw => raw,
RECOVERY_CONTROL_DEFAULTS,
family => webFonts.has(family),
).font;
assert.equal(font, RECOVERY_CONTROL_DEFAULTS.font);
});
test("applying and clearing toolbar tokens writes only toolbar variables", () => {
const values = new Map<string, string>();
const control = {
style: {
setProperty: (name: string, value: string) => { values.set(name, value); },
removeProperty: (name: string) => { values.delete(name); },
},
} as unknown as HTMLElement;
applyHostControlToolbarTokens(control, resolveToolbar({
"--skin-recovery-toolbar-background": "#102030",
"--skin-recovery-toolbar-foreground": "#ffffff",
"--skin-recovery-toolbar-padding": "6px 14px",
"--skin-recovery-toolbar-height": "36px",
}));
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.background), "rgb(16, 32, 48)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.foreground), "rgb(255, 255, 255)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.paddingX), "14px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.paddingY), "6px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.minHeight), "36px");
applyHostControlToolbarTokens(control, null);
assert.equal(values.size, 0);
});
+220
View File
@@ -44,6 +44,36 @@ export const HOST_CONTROL_TOKEN_NAMES = [
export type HostControlTokenName = (typeof HOST_CONTROL_TOKEN_NAMES)[number];
/**
* Extra tokens read only for `mode: "toolbar"` recovery buttons. They make a
* host-owned button able to match a neighbouring top-bar button without
* giving the skin any DOM control:
*
* --skin-recovery-toolbar-<token> (per-part)
* --skin-host-toolbar-<token> (global fallback)
*
* Colours fall back to the normal `--skin-recovery-*` / `--skin-host-*` set;
* radius, padding, height, font size and shadow use toolbar defaults so a
* capsule radius (999px) or the fixed pale built-in button never leaks in.
*/
export const HOST_TOOLBAR_TOKEN_NAMES = [
"background", "foreground", "border", "radius", "font", "font-size", "padding", "height", "shadow",
] as const;
export type HostToolbarTokenName = (typeof HOST_TOOLBAR_TOKEN_NAMES)[number];
export const HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES: Readonly<Record<HostToolbarTokenName, string>> = {
background: "--skin-host-toolbar-background",
foreground: "--skin-host-toolbar-foreground",
border: "--skin-host-toolbar-border",
radius: "--skin-host-toolbar-radius",
font: "--skin-host-toolbar-font",
"font-size": "--skin-host-toolbar-font-size",
padding: "--skin-host-toolbar-padding",
height: "--skin-host-toolbar-height",
shadow: "--skin-host-toolbar-shadow",
};
/** Global token set read from the active skin root (or a slot anchor). */
export const HOST_CONTROL_GLOBAL_TOKEN_PROPERTIES: Readonly<Record<HostControlTokenName, string>> = {
accent: "--skin-host-accent",
@@ -74,6 +104,10 @@ export function hostControlTokenProperty(part: string, token: HostControlTokenNa
return `--skin-${hostControlTokenKey(part)}-${token}`;
}
export function hostToolbarTokenProperty(part: string, token: HostToolbarTokenName): string {
return `--skin-${hostControlTokenKey(part)}-toolbar-${token}`;
}
/** Host-owned variables written inside the closed shadow root. */
export const HOST_CONTROL_APPLIED_VARIABLES = {
accent: "--ws-control-accent",
@@ -88,6 +122,21 @@ export const HOST_CONTROL_APPLIED_VARIABLES = {
builtInBorder: "--ws-control-builtin-border",
} as const;
/** Host-owned variables read by the toolbar-mode button CSS. */
export const HOST_TOOLBAR_APPLIED_VARIABLES = {
background: "--ws-toolbar-background",
foreground: "--ws-toolbar-foreground",
border: "--ws-toolbar-border",
radius: "--ws-toolbar-radius",
font: "--ws-toolbar-font",
fontSize: "--ws-toolbar-font-size",
paddingX: "--ws-toolbar-padding-x",
paddingY: "--ws-toolbar-padding-y",
minHeight: "--ws-toolbar-min-height",
shadow: "--ws-toolbar-shadow",
focus: "--ws-toolbar-focus",
} as const;
export interface HostControlRawTokens {
/** Computed-style colour values; unresolved values are rejected. */
accent?: string;
@@ -130,6 +179,23 @@ export interface HostControlTokens {
builtInBorder?: string;
}
/** Resolved style of a toolbar-mode recovery button (applied to its wrapper). */
export interface HostControlToolbarTokens {
background: string;
foreground: string;
border: string;
radius: number;
font: string;
fontSize: number;
paddingX: number;
paddingY: number;
/** Minimum button height; never below the current size tier hit target. */
minHeight: number;
shadow: string;
/** Focus ring colour, from the readable accent of the control palette. */
focus: string;
}
export interface RgbColor {
r: number;
g: number;
@@ -147,6 +213,23 @@ const ON_ACCENT_DARK: RgbColor = { r: 17, g: 24, b: 39 };
const MAX_RADIUS = 999;
const MAX_FONT_LENGTH = 120;
const FONT_FAMILY_PATTERN = /^[A-Za-z0-9 ,'"-]{1,120}$/;
/** Toolbar-mode geometry limits; a skin cannot shrink below host minimums. */
export const TOOLBAR_DEFAULT_RADIUS = 6;
export const TOOLBAR_MAX_RADIUS = 24;
export const TOOLBAR_DEFAULT_PADDING_X = 12;
export const TOOLBAR_DEFAULT_PADDING_Y = 6;
export const TOOLBAR_MAX_PADDING = 48;
export const TOOLBAR_MAX_HEIGHT = 72;
export const TOOLBAR_MAX_FONT_SIZE = 20;
const MAX_SHADOW_LENGTH = 160;
const LENGTH_PX_PATTERN = /^(-?\d+(?:\.\d+)?)px$/i;
const PADDING_PATTERN = /^(\d+(?:\.\d+)?)px(?:\s+(\d+(?:\.\d+)?)px)?$/i;
/**
* A single box-shadow value: optional `inset`, two to four px offsets/sizes
* and one simple colour. `url()`, `var()`, extra shadows and declarations are
* rejected so a token can never load a resource or escape the inline value.
*/
const SHADOW_PATTERN = /^(?:none|(?:inset\s+)?(?:-?(?:0|(?:\d+(?:\.\d+)?)px)\s+){2,4}(?:#[0-9a-f]{3,8}|rgba?\([^()]*\)|[a-z]+))$/i;
/**
* The skin compiler renames every skin/plugin `@font-face` family to
* `ws-<skin id>[-<plugin id>]-<name>` (see `compileSkinCss` in
@@ -449,6 +532,143 @@ export function applyHostControlTokens(control: HTMLElement, tokens: HostControl
if (tokens.builtInBorder) style.setProperty(HOST_CONTROL_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder);
}
function readToolbarTokenSet(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
resolveProperty: (token: HostToolbarTokenName) => string,
): Partial<Record<HostToolbarTokenName, string>> {
if (!style) return {};
const tokens: Partial<Record<HostToolbarTokenName, string>> = {};
for (const token of HOST_TOOLBAR_TOKEN_NAMES) {
const value = style.getPropertyValue(resolveProperty(token)).trim();
if (value) tokens[token] = value;
}
return tokens;
}
function sanitizeToolbarFontSize(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const size = Number.parseFloat(match[1]);
return Number.isFinite(size)
? Math.min(TOOLBAR_MAX_FONT_SIZE, Math.max(HOST_CONTROL_MIN_FONT_SIZE, fallback, size))
: fallback;
}
function sanitizeToolbarPadding(value: string | undefined): { x: number; y: number } | undefined {
if (!value) return undefined;
const match = PADDING_PATTERN.exec(value.trim());
if (!match) return undefined;
const first = Number.parseFloat(match[1]);
const second = match[2] === undefined ? first : Number.parseFloat(match[2]);
if (!Number.isFinite(first) || !Number.isFinite(second)) return undefined;
const clamp = (size: number) => Math.min(TOOLBAR_MAX_PADDING, Math.max(0, size));
return { x: clamp(second), y: clamp(first) };
}
function sanitizeToolbarHeight(value: string | undefined, fallback: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const height = Number.parseFloat(match[1]);
return Number.isFinite(height)
? Math.min(TOOLBAR_MAX_HEIGHT, Math.max(fallback, height))
: fallback;
}
function sanitizeToolbarShadow(value: string | undefined): string | undefined {
if (!value) return undefined;
const shadow = value.trim().replace(/\s+/g, " ");
if (!shadow || shadow.length > MAX_SHADOW_LENGTH || !SHADOW_PATTERN.test(shadow)) return undefined;
return shadow;
}
/** True when the skin declares at least one toolbar-mode token. */
export function hasHostToolbarTokens(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
part: string,
): boolean {
if (!style) return false;
return HOST_TOOLBAR_TOKEN_NAMES.some((token) =>
Boolean(style.getPropertyValue(hostToolbarTokenProperty(part, token)).trim())
|| Boolean(style.getPropertyValue(HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES[token]).trim())
);
}
/**
* Resolve the toolbar button palette and geometry.
*
* The base control palette is resolved first (background/foreground/accent/
* border/font/size, with every existing readability floor). Toolbar tokens
* then override colours and radius; an unreadable toolbar colour pair falls
* back to the readable base pair, so an invalid or transparent value can never
* make the button invisible. `font-size`, `padding` and `height` may raise the
* button but never go below `HOST_CONTROL_MIN_FONT_SIZE` / the current hit
* target; `shadow` accepts one simple box-shadow value and otherwise becomes
* `none` (no fixed capsule shadow).
*/
export function resolveHostControlToolbarTokens(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
part: string,
probeColor: ColorProbe,
defaults: HostControlDefaults,
isWebFont: WebFontCheck = NO_WEB_FONTS,
): HostControlToolbarTokens {
const base = resolveHostControlTokens(style, part, probeColor, defaults, isWebFont);
const globalTokens = readToolbarTokenSet(style, (token) => HOST_TOOLBAR_GLOBAL_TOKEN_PROPERTIES[token]);
const partTokens = readToolbarTokenSet(style, (token) => hostToolbarTokenProperty(part, token));
const merged = { ...globalTokens, ...partTokens };
const baseBackground = parseCssColor(base.background) ?? defaults.background;
const baseForeground = parseCssColor(base.foreground) ?? defaults.foreground;
const baseBorder = parseCssColor(base.border) ?? defaults.border;
let background = parseCssColor(probeColor(merged.background)) ?? baseBackground;
let foreground = parseCssColor(probeColor(merged.foreground)) ?? baseForeground;
// A toolbar colour pair must keep the same text contrast floor as the
// capsule; on any failure the already-readable base palette wins as a pair.
if (contrastRatio(foreground, background) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
background = baseBackground;
foreground = baseForeground;
}
const border = resolveBorder(merged.border, background, probeColor) ?? baseBorder;
const padding = sanitizeToolbarPadding(merged.padding);
return {
background: formatRgb(background),
foreground: formatRgb(foreground),
border: formatRgb(border),
radius: sanitizeRadius(merged.radius, TOOLBAR_DEFAULT_RADIUS, TOOLBAR_MAX_RADIUS),
font: sanitizeFont(merged.font, base.font, isWebFont),
fontSize: sanitizeToolbarFontSize(merged["font-size"], base.fontSize),
paddingX: padding?.x ?? TOOLBAR_DEFAULT_PADDING_X,
paddingY: padding?.y ?? TOOLBAR_DEFAULT_PADDING_Y,
minHeight: sanitizeToolbarHeight(merged.height, base.hitTarget),
shadow: sanitizeToolbarShadow(merged.shadow) ?? "none",
focus: base.accent,
};
}
/** Apply (or clear) toolbar-mode variables on the button wrapper. */
export function applyHostControlToolbarTokens(
control: HTMLElement,
tokens: HostControlToolbarTokens | null,
): void {
const style = control.style;
for (const property of Object.values(HOST_TOOLBAR_APPLIED_VARIABLES)) style.removeProperty(property);
if (!tokens) return;
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.background, tokens.background);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.foreground, tokens.foreground);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.border, tokens.border);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.font, tokens.font);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.fontSize, `${tokens.fontSize}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.paddingX, `${tokens.paddingX}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.paddingY, `${tokens.paddingY}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.minHeight, `${tokens.minHeight}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.shadow, tokens.shadow);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.focus, tokens.focus);
}
export interface HostControlThemeBindingOptions {
layer: HostOwnedLayer;
/** The host-owned element whose inline `--ws-control-*` variables are set. */
+7 -3
View File
@@ -103,17 +103,21 @@ const popoverFallbacks = new WeakSet<HTMLElement>();
* 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 {
export function syncRecoveryPopover(
element: HTMLElement | null | undefined,
visible: boolean,
display: "flex" | "inline-flex" = "flex",
): void {
if (!element) return;
const enterFallback = (): void => {
popoverFallbacks.add(element);
element.removeAttribute("popover");
element.style.display = visible ? "flex" : "none";
element.style.display = visible ? display : "none";
};
if (popoverFallbacks.has(element)) {
element.style.display = visible ? "flex" : "none";
element.style.display = visible ? display : "none";
return;
}
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import test from "node:test";
import { resolveHostRecoveryPresentation } from "./host-recovery-presentation.js";
const base = {
visible: true,
shortcutOpen: false,
libraryAvailable: true,
builtIn: { available: false, docked: false },
library: { available: false, docked: false },
};
test("a capsule-only skin keeps both actions in the capsule", () => {
const result = resolveHostRecoveryPresentation(base);
assert.deepEqual(result.capsuleActions, ["built-in", "library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.suppressLauncher, false);
assert.equal(result.toolbar.docked, false);
});
test("a docked toolbar group removes both actions from the capsule", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.docked, { builtIn: true, library: true });
assert.deepEqual(result.capsuleActions, []);
assert.equal(result.capsuleVisible, false);
assert.equal(result.suppressLauncher, true, "the toolbar library is the only library entry");
});
test("a failed anchor returns its action to the capsule without duplicating the other", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: true, docked: false },
});
assert.deepEqual(result.docked, { builtIn: true, library: false });
assert.deepEqual(result.capsuleActions, ["library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.suppressLauncher, true, "the floating capsule now carries the only library entry");
});
test("the shortcut forces the complete capsule and hides the toolbar", () => {
const result = resolveHostRecoveryPresentation({
...base,
shortcutOpen: true,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.docked, { builtIn: false, library: false });
assert.deepEqual(result.capsuleActions, ["built-in", "library"]);
assert.equal(result.capsuleVisible, true);
assert.equal(result.toolbar.visible, false);
});
test("no recovery entry means no capsule, no toolbar and no launcher suppression", () => {
const result = resolveHostRecoveryPresentation({
...base,
visible: false,
builtIn: { available: true, docked: true },
library: { available: true, docked: true },
});
assert.deepEqual(result.capsuleActions, []);
assert.equal(result.capsuleVisible, false);
assert.equal(result.toolbar.visible, false);
assert.equal(result.suppressLauncher, false);
});
test("an unavailable library never renders or suppresses anything", () => {
const result = resolveHostRecoveryPresentation({
...base,
libraryAvailable: false,
library: { available: false, docked: true },
});
assert.deepEqual(result.capsuleActions, ["built-in"]);
assert.equal(result.suppressLauncher, false);
});
test("a docked built-in toolbar button leaves only the library in the capsule", () => {
const result = resolveHostRecoveryPresentation({
...base,
builtIn: { available: true, docked: true },
library: { available: false, docked: false },
});
assert.deepEqual(result.capsuleActions, ["library"]);
assert.equal(result.capsuleVisible, true);
});
@@ -0,0 +1,87 @@
/**
* Pure presentation decisions for the trusted recovery entry.
*
* The recovery entry has two host buttons ("use built-in skin" and
* "application library"). A skin may dock them as one capsule (the historical
* `host.recovery` slot), as one chrome-less toolbar group, or as two separate
* toolbar buttons (`host.recovery.built-in` / `host.recovery.library`).
*
* This module keeps the duplicate and fallback rules in one testable place:
* - an action is only "in the toolbar" when its anchor is currently slotted,
* so a missing/hidden anchor immediately returns it to the floating capsule;
* - the capsule renders only the actions that are not currently in the
* toolbar, so the same page never shows two copies of an action;
* - the shortcut forces every action back into the capsule (and hides the
* toolbar) so one keystroke still summons the complete recovery entry;
* - a toolbar-mode application-library action suppresses the ordinary
* `host.plugins.launcher`, because the host button is now the only library
* entry on that page (docked or floating, the capsule still offers it).
*/
export type HostRecoveryAction = "built-in" | "library";
export interface HostRecoveryToolbarActionState {
/** The slot declaration exists and the action is usable on this page. */
available: boolean;
/** The slot binding currently reports a valid, docked anchor. */
docked: boolean;
}
export interface HostRecoveryPresentationInput {
/** The recovery entry should be visible at all (third-party skin / shortcut). */
visible: boolean;
/** The recovery shortcut is currently holding the entry open. */
shortcutOpen: boolean;
/** The application library is usable (connected with a plugin session). */
libraryAvailable: boolean;
builtIn: HostRecoveryToolbarActionState;
library: HostRecoveryToolbarActionState;
}
export interface HostRecoveryPresentation {
/** Toolbar entries the host should paint (and bind) on this page. */
toolbar: HostRecoveryToolbarActionState & { visible: boolean };
/** Whether each action is currently painted by a docked toolbar button. */
docked: HostRecoveryDockedState;
/** Actions still shown by the floating capsule, in render order. */
capsuleActions: HostRecoveryAction[];
capsuleVisible: boolean;
/** Hide the ordinary plugin launcher to keep exactly one library entry. */
suppressLauncher: boolean;
}
export interface HostRecoveryDockedState {
builtIn: boolean;
library: boolean;
}
export function resolveHostRecoveryPresentation(
input: HostRecoveryPresentationInput,
): HostRecoveryPresentation {
const toolbarVisible = input.visible && !input.shortcutOpen;
const docked: HostRecoveryDockedState = {
builtIn: toolbarVisible && input.builtIn.available && input.builtIn.docked,
library: toolbarVisible && input.libraryAvailable && input.library.available && input.library.docked,
};
const capsuleActions: HostRecoveryAction[] = [];
if (input.visible && !docked.builtIn) capsuleActions.push("built-in");
if (input.visible && input.libraryAvailable && !docked.library) capsuleActions.push("library");
return {
toolbar: {
available: toolbarVisible && (input.builtIn.available || input.library.available),
docked: docked.builtIn || docked.library,
visible: toolbarVisible,
},
docked,
capsuleActions,
capsuleVisible: capsuleActions.length > 0,
// A toolbar-mode library button replaces the normal launcher even while
// its anchor is invalid, because the fallback capsule would otherwise add
// a second library entry next to that launcher.
suppressLauncher: input.visible
&& input.libraryAvailable
&& input.library.available,
};
}
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
HOST_SLOT_VIEWPORT_INSET,
INITIAL_SLOT_MODE_STATE,
computeSlotPlacement,
evaluateSlottedControl,
@@ -166,3 +167,40 @@ test("rect overlap ignores edge contact and sub-pixel slivers", () => {
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(99.5, 0, 50, 40)), false);
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(0, 60, 100, 40)), false);
});
test("toolbar buttons with long localised labels stay inside a narrow viewport", () => {
// German "Integrierten Skin verwenden" / Russian / Japanese labels make a
// toolbar button much wider than the capsule's short actions. The placement
// clamps it into the viewport; when the control is wider than the viewport
// the slot rejects it and the caller falls back to the capsule.
const viewport = { width: 320, height: 640 };
const wide = { width: 300, height: 64 };
const placement = computeSlotPlacement(rect(280, 8, 32, 32), wide, viewport, "end");
assert.ok(placement.left >= HOST_SLOT_VIEWPORT_INSET);
assert.ok(placement.left + wide.width <= viewport.width - HOST_SLOT_VIEWPORT_INSET);
const tooWide = rect(4, 8, 340, 64);
assert.deepEqual(
evaluateSlottedControl({
anchor: anchor({ rect: rect(0, 0, 320, 48) }),
controlRect: tooWide,
viewport,
minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
hitTestOk: true,
}),
{ ok: false, reason: "control-offscreen" },
"an oversized toolbar must fall back to the visible capsule, not disappear",
);
// A wrapped two-line button (64px high) still passes the minimum hit target.
assert.deepEqual(
evaluateSlottedControl({
anchor: anchor({ rect: rect(0, 0, 320, 120) }),
controlRect: rect(4, 8, 300, 64),
viewport,
minHitTarget: HOST_CONTROL_MIN_HIT_TARGET,
hitTestOk: true,
}),
{ ok: true },
);
});
+66 -15
View File
@@ -20,9 +20,11 @@ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
import {
RECOVERY_CONTROL_DEFAULTS,
applyHostControlTokens,
applyHostControlToolbarTokens,
createHostControlProbe,
findSkinRoot,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlTokens,
type HostControlProbe,
} from "./host-control-tokens.js";
@@ -271,22 +273,31 @@ function isVisibleAnchor(element: HTMLElement): boolean {
}
/**
* Resolve the first visible `[data-ws-part="<anchor>"]` inside the active
* skin's DOM. Plugin and surface hosts render inside `.ws-skin-root` too
* Resolve the first visible candidate `[data-ws-part="<anchor>"]` inside the
* active skin's DOM. Plugin and surface hosts render inside `.ws-skin-root` too
* (runtime plugins may Teleport to a `data-ws-skin-mount` slot, but every
* mount slot is part of the skin root), so a skin cannot point the recovery
* control at host chrome outside its own subtree.
*
* A candidate list lets one declaration cover several pages: the home and
* voice surfaces render different prefixed parts, but only one page is visible
* at a time, so the first visible candidate is the deterministic one. The
* binding re-resolves on every check, which is what makes a page switch (or a
* skin reload) fall back and re-dock without a rebind.
*/
export function resolveSkinAnchor(
anchor: string,
anchor: string | readonly string[],
doc: Document = document,
skinId?: string,
): HTMLElement | null {
const selector = `[data-ws-part="${anchor}"]`;
for (const root of doc.querySelectorAll(".ws-skin-root")) {
if (skinId && root.getAttribute("data-ws-skin") !== skinId) continue;
for (const element of root.querySelectorAll<HTMLElement>(selector)) {
if (isVisibleAnchor(element)) return element;
const anchors = typeof anchor === "string" ? [anchor] : anchor;
for (const candidate of anchors) {
const selector = `[data-ws-part="${candidate}"]`;
for (const root of doc.querySelectorAll(".ws-skin-root")) {
if (skinId && root.getAttribute("data-ws-skin") !== skinId) continue;
for (const element of root.querySelectorAll<HTMLElement>(selector)) {
if (isVisibleAnchor(element)) return element;
}
}
}
return null;
@@ -300,11 +311,27 @@ export interface HostSlotModeChange {
export interface HostSlotBindingOptions {
layer: HostOwnedLayer;
control: HTMLElement;
anchor: string;
/** One anchor name, or ordered candidates (first visible one wins). */
anchor: string | readonly string[];
/** Restricts anchor resolution and token fallback to this active skin. */
skinId?: string;
align?: SkinChromeSlotAlign;
resolveAnchor?: (anchor: string) => HTMLElement | null;
/**
* `toolbar` also applies `--skin-recovery-toolbar-*` tokens (background,
* foreground, border, radius, font, font size, padding, min height, shadow).
* The capsule mode keeps the historical control tokens only.
*/
presentation?: "capsule" | "toolbar";
/**
* Called before measuring. A toolbar popover is closed while it floats, so
* its box would be 0×0 and the control could never re-dock after a fallback.
* The callback shows it for the synchronous check; `settle` hides it again
* in the same task when the anchor is still unusable, so nothing paints.
*/
prepare?: () => void;
/** Called after each evaluation with the resulting docked state. */
settle?: (slotted: boolean) => void;
resolveAnchor?: (anchor: string | readonly string[]) => HTMLElement | null;
onModeChange?: (change: HostSlotModeChange) => void;
}
@@ -332,7 +359,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
if (!view) return NOOP_BINDING;
const win = view;
const resolveAnchor = options.resolveAnchor
?? ((name: string) => resolveSkinAnchor(name, doc, options.skinId));
?? ((name: string | readonly string[]) => resolveSkinAnchor(name, doc, options.skinId));
let state = INITIAL_SLOT_MODE_STATE;
let lastReason: SlotFailureReason | undefined;
@@ -348,9 +375,9 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback);
const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
function readTokens(source: Element | null): HostControlTokens {
function readTokens(style: CSSStyleDeclaration | null): HostControlTokens {
return resolveHostControlTokens(
source ? win.getComputedStyle(source) : null,
style,
"host.recovery",
probe.probeColor,
RECOVERY_CONTROL_DEFAULTS,
@@ -400,14 +427,35 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
function evaluate(): void {
if (disposed) return;
// A floating toolbar popover is closed; show it for this synchronous
// measurement. `settle` hides it again before paint on any failure.
options.prepare?.();
const anchorElement = resolveAnchor(anchorName);
observe(anchorElement);
// The fallback keeps the skin palette: read tokens from the anchor, or
// from the skin root when the anchor is missing or hidden.
const tokenSource = anchorElement
?? (options.skinId ? findSkinRoot(options.skinId, doc) : null);
const tokens = readTokens(tokenSource);
applyHostControlTokens(control, tokenSource ? tokens : null);
const tokenStyle = tokenSource ? win.getComputedStyle(tokenSource) : null;
const tokens = readTokens(tokenStyle);
applyHostControlTokens(control, tokenStyle ? tokens : null);
if (options.presentation === "toolbar") {
// Toolbar buttons get a second, independent token set so they can match
// a neighbouring top-bar button instead of the capsule palette. The
// resolver keeps the same contrast/font floors and falls back as a group.
applyHostControlToolbarTokens(
control,
tokenStyle
? resolveHostControlToolbarTokens(
tokenStyle,
"host.recovery",
probe.probeColor,
RECOVERY_CONTROL_DEFAULTS,
probe.isWebFont,
)
: null,
);
}
const controlBox = control.getBoundingClientRect();
maxSize = {
@@ -481,6 +529,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
lastReason = reason;
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
}
options.settle?.(state.slotted);
}
/** Any unexpected error returns the capsule to the default corner. */
@@ -488,6 +537,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
const wasSlotted = state.slotted;
state = nextSlotModeState(state, false);
clearPlacement();
options.settle?.(false);
if (wasSlotted) onModeChange?.({ mode: "floating" });
}
@@ -535,6 +585,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
win.removeEventListener("scroll", schedule, { capture: true });
clearPlacement();
applyHostControlTokens(control, null);
applyHostControlToolbarTokens(control, null);
probe.dispose();
},
};