Merge PR #64: dock trusted recovery controls in skin toolbars

# Conflicts:
#	package.json
This commit is contained in:
illusia committed 2026-11-27 08:42:18 +08:00
commit 02509ea551
43 files changed
+3843 -141

No files matched your search

+461 -64
View File
@@ -28,8 +28,125 @@
<!-- 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"
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="built-in"
:aria-label="copy.useBuiltIn"
:title="copy.shortcut"
@click="useBuiltInSkin"
>
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
</svg>
</span>
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
</button>
<button
v-if="pluginLibraryAvailable"
type="button"
class="ws-host-toolbar-action"
:class="{ 'ws-host-toolbar-action-icon': groupToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="library"
:aria-label="copy.library"
:title="copy.library"
@click="openLibrary"
>
<span v-if="groupToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
</svg>
</span>
<span v-if="groupToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
</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"
:class="{ 'ws-host-toolbar-action-icon': builtInToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="built-in"
:aria-label="copy.useBuiltIn"
:title="copy.shortcut"
@click="useBuiltInSkin"
>
<span v-if="builtInToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<path d="M8 2.2a5.8 5.8 0 1 0 0 11.6h.9a1.5 1.5 0 0 0 .7-2.83 1.2 1.2 0 0 1 .6-2.25H12A2 2 0 0 0 14 6.8C14 4.1 11.3 2.2 8 2.2Z"/>
<circle cx="5" cy="6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="7.2" cy="4.6" r=".7" fill="currentColor" stroke="none"/>
<circle cx="10" cy="4.9" r=".7" fill="currentColor" stroke="none"/>
</svg>
</span>
<span v-if="builtInToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.useBuiltIn }}</span>
</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"
:class="{ 'ws-host-toolbar-action-icon': libraryToolbarConfig.appearance === 'icon' }"
data-ws-recovery-action="library"
:aria-label="copy.library"
:title="copy.library"
@click="openLibrary"
>
<span v-if="libraryToolbarConfig.appearance !== 'label'" class="ws-host-toolbar-icon" aria-hidden="true">
<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" focusable="false">
<rect x="2.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="2.2" width="4.6" height="4.6" rx=".8"/>
<rect x="2.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
<rect x="9.2" y="9.2" width="4.6" height="4.6" rx=".8"/>
</svg>
</span>
<span v-if="libraryToolbarConfig.appearance !== 'icon'" class="ws-host-toolbar-label">{{ copy.library }}</span>
</button>
</div>
<div
ref="recoveryPopover"
popover="manual"
@@ -38,7 +155,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 +163,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 +171,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 +183,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 +196,7 @@ import {
isThirdPartySkinActive,
openPluginLibrary,
requestBuiltInSkin,
setInlineLibraryEntryVisible,
} from "../services/host-chrome.js";
import {
createHostOwnedLayer,
@@ -89,13 +209,16 @@ import {
type FloatingAvoidance,
type FloatingPosition,
} from "../services/host-floating-placement.js";
import { shouldShowRecovery } from "../services/host-chrome-visibility.js";
import { shouldShowRecovery, type HostPartRect } from "../services/host-chrome-visibility.js";
import { thirdPartyAllowed } from "../services/instance-authorization.js";
import {
RECOVERY_CONTROL_DEFAULTS,
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 +287,70 @@ 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: var(--ws-toolbar-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;
gap: 4px;
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 {
border-color: var(--ws-toolbar-hover-border, var(--ws-toolbar-border, #9db6b2));
background: var(--ws-toolbar-hover-background, var(--ws-toolbar-background, #fff));
}
.ws-host-toolbar-action:focus-visible {
outline: 2px solid var(--ws-toolbar-focus, var(--ws-control-accent, #4c8f88));
outline-offset: 2px;
}
.ws-host-toolbar-icon {
display: block;
flex: 0 0 auto;
width: var(--ws-toolbar-icon-size, 16px);
height: var(--ws-toolbar-icon-size, 16px);
}
.ws-host-toolbar-icon svg { display: block; width: 100%; height: 100%; }
.ws-host-toolbar-action-icon {
width: max(24px, calc(var(--ws-toolbar-icon-size, 16px) + 8px));
padding: 0;
}
@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 +375,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 +408,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 +482,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;
@@ -267,40 +498,145 @@ function onRecoveryEscape() {
compactPinned.value = false;
}
/** Unpin when the pointer goes down anywhere outside the host layer. */
/** Dismiss shortcut expansion and unpin on pointer down outside the host layer. */
function onDocumentPointerDown(event: PointerEvent) {
if (!compactPinned.value || !layer) return;
if (!layer) return;
// Events from inside the closed shadow root are retargeted to its host.
if (event.composedPath().includes(layer.host)) return;
shortcutOpen.value = false;
shortcutExpanded.value = false;
compactPinned.value = false;
}
function onRecoveryFocusOut(event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && recoveryPopover.value?.contains(next)) return;
shortcutOpen.value = false;
shortcutExpanded.value = false;
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",
);
}
/** A toolbar that is currently displayed (top layer or display fallback). */
function isToolbarShown(control: HTMLElement | null): boolean {
if (!control) return false;
if (control.matches?.(":popover-open")) return true;
const rect = control.getBoundingClientRect();
return getComputedStyle(control).display !== "none" && rect.width > 0 && rect.height > 0;
}
function rectOf(control: HTMLElement): HostPartRect {
const rect = control.getBoundingClientRect();
return {
left: rect.left, top: rect.top, width: rect.width, height: rect.height,
right: rect.right, bottom: rect.bottom,
};
}
/** Every recovery toolbar currently docked in the top layer. */
function dockedToolbarRects(): HostPartRect[] {
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
.filter((element): element is HTMLElement => Boolean(element) && isToolbarShown(element))
.map(rectOf);
}
/** Other docked recovery toolbars this entry must not cover on a narrow screen. */
function otherToolbarRects(control: HTMLElement): HostPartRect[] {
return [groupToolbarElement.value, builtInToolbarElement.value, libraryToolbarElement.value]
.filter((element): element is HTMLElement => Boolean(element)
&& element !== control && isToolbarShown(element))
.map(rectOf);
}
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",
otherControls: () => otherToolbarRects(control),
// 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,
// A slotted capsule must not cover a still-docked split toolbar either.
otherControls: () => dockedToolbarRects(),
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() {
@@ -331,6 +667,11 @@ function bindFloating() {
return { width: hit + 10, height: hit + 10 };
},
onCompactChange: next => { floatCompact.value = next; },
// Docked toolbars are inside the closed shadow root, so the light-DOM
// obstacle scan cannot see them. In split mode the library toolbar falls
// back to this capsule while the built-in toolbar stays docked; without
// this exclusion the capsule could cover it (320px GUI failure).
avoidRects: () => dockedToolbarRects(),
// Never move the capsule under the user's pointer or focus, and leave a
// docked capsule to the slot binding.
paused: () => slotMode.value === "slotted"
@@ -341,10 +682,6 @@ function bindFloating() {
});
}
function syncPopover() {
syncRecoveryPopover(recoveryPopover.value, recoveryVisible.value);
}
function useBuiltInSkin() {
shortcutOpen.value = false;
requestBuiltInSkin();
@@ -364,8 +701,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 +716,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 +783,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,12 @@ test("slot declarations are honoured for third-party skins only", () => {
anchor: "voice.audio-dock",
align: "end",
compact: false,
mode: "capsule",
appearance: "label",
});
// 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"]) {
+23 -4
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
@@ -116,16 +133,18 @@ export function requestBuiltInSkin(): void {
builtInSkinRequests.value += 1;
}
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key">;
type RecoveryShortcutEvent = Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "key" | "code">;
/**
* 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.
* On macOS, Option/Shift turn the letter key into a derived character (US
* layout: ®), so `event.key` is not "r". Match the physical `code` as well;
* every modifier is still 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";
&& (event.key?.toLowerCase() === "r" || event.code === "KeyR");
}
@@ -9,19 +9,38 @@ 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_GAP,
TOOLBAR_DEFAULT_ICON_SIZE,
TOOLBAR_DEFAULT_PADDING_X,
TOOLBAR_DEFAULT_PADDING_Y,
TOOLBAR_DEFAULT_RADIUS,
TOOLBAR_MAX_FONT_SIZE,
TOOLBAR_MAX_GAP,
TOOLBAR_MAX_HEIGHT,
TOOLBAR_MAX_ICON_SIZE,
TOOLBAR_MAX_PADDING,
TOOLBAR_MIN_HEIGHT,
TOOLBAR_MIN_ICON_SIZE,
applyHostControlTokens,
applyHostControlToolbarTokens,
compositeRgb,
contrastRatio,
fontFamilyNames,
formatRgb,
hasHostControlTokens,
hasHostToolbarTokens,
hostControlTokenKey,
hostControlTokenProperty,
hostToolbarTokenProperty,
parseCssColor,
parseCssColorWithAlpha,
relativeLuminance,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlRawTokens,
} from "./host-control-tokens.js";
@@ -254,6 +273,13 @@ test("CSS colours parse to RGB and ignore alpha for contrast", () => {
}
});
test("alpha colours parse and composite over opaque toolbar surfaces", () => {
assert.deepEqual(parseCssColorWithAlpha("transparent"), { r: 0, g: 0, b: 0, a: 0 });
assert.deepEqual(parseCssColorWithAlpha("#10203080"), { r: 16, g: 32, b: 48, a: 128 / 255 });
assert.deepEqual(parseCssColorWithAlpha("rgb(255 0 0 / 50%)"), { r: 255, g: 0, b: 0, a: 0.5 });
assert.deepEqual(compositeRgb({ r: 0, g: 0, b: 0, a: 0.5 }, { r: 255, g: 255, b: 255 }), { r: 128, g: 128, b: 128 });
});
test("WCAG contrast follows the relative-luminance formula", () => {
assert.equal(relativeLuminance({ r: 0, g: 0, b: 0 }), 0);
assert.equal(relativeLuminance({ r: 255, g: 255, b: 255 }), 1);
@@ -281,3 +307,260 @@ 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 = {}, sampledSurface?: { r: number; g: number; b: number }) =>
resolveHostControlToolbarTokens(
style({ ...tokens, ...global }),
"host.recovery",
raw => raw,
RECOVERY_CONTROL_DEFAULTS,
undefined,
sampledSurface,
);
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(49, 82, 79)");
assert.ok(contrastRatio(parseCssColor(defaults.border)!, parseCssColor(defaults.background)!) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
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("toolbar colours preserve transparency and check text against an opaque surface", () => {
const classic = resolveToolbar({
"--skin-recovery-toolbar-background": "transparent",
"--skin-recovery-toolbar-foreground": "#1a1a1a",
"--skin-recovery-toolbar-border": "transparent",
"--skin-recovery-toolbar-hover-background": "#eaf2fd",
"--skin-recovery-toolbar-hover-border": "#b8cfe8",
}, {}, { r: 255, g: 255, b: 255 });
assert.equal(classic.background, "transparent");
assert.equal(classic.border, "transparent");
assert.equal(classic.foreground, "rgb(26, 26, 26)");
assert.equal(classic.hoverBackground, "rgb(234, 242, 253)");
assert.equal(classic.hoverBorder, "rgb(184, 207, 232)");
const explicitDarkSurface = resolveToolbar({
"--skin-recovery-toolbar-background": "#00000000",
"--skin-recovery-toolbar-foreground": "#ffffff",
"--skin-recovery-toolbar-surface": "#102030",
}, {}, { r: 255, g: 255, b: 255 });
assert.equal(explicitDarkSurface.background, "transparent");
assert.equal(explicitDarkSurface.foreground, "rgb(255, 255, 255)");
const sampledDarkSurface = resolveToolbar({
"--skin-recovery-toolbar-background": "transparent",
"--skin-recovery-toolbar-foreground": "#ffffff",
}, {}, { r: 16, g: 32, b: 48 });
assert.equal(sampledDarkSurface.background, "transparent");
assert.equal(sampledDarkSurface.foreground, "rgb(255, 255, 255)");
const globalSurface = resolveToolbar({
"--skin-recovery-toolbar-background": "transparent",
"--skin-recovery-toolbar-foreground": "#ffffff",
}, { "--skin-host-toolbar-surface": "#102030" }, { r: 255, g: 255, b: 255 });
assert.equal(globalSurface.foreground, "rgb(255, 255, 255)");
});
test("toolbar border and focus colours are rechecked against the final surface", () => {
const palette = {
"--skin-recovery-background": "#000000",
"--skin-recovery-foreground": "#ffffff",
"--skin-recovery-border": "#ffffff",
"--skin-recovery-accent": "#ffffff",
"--skin-recovery-toolbar-foreground": "#000000",
"--skin-recovery-toolbar-surface": "#ffffff",
};
for (const background of ["#ffffff", "transparent"]) {
for (const border of [undefined, "#ffffff"]) {
const toolbar = resolveToolbar({
...palette,
"--skin-recovery-toolbar-background": background,
...(border ? { "--skin-recovery-toolbar-border": border } : {}),
});
const surface = parseCssColor(background === "transparent" ? palette["--skin-recovery-toolbar-surface"] : background)!;
assert.ok(contrastRatio(parseCssColor(toolbar.border)!, surface) >= HOST_CONTROL_MIN_BORDER_CONTRAST,
`${background} background with ${border ?? "inherited"} border produced ${toolbar.border}`);
assert.ok(contrastRatio(parseCssColor(toolbar.focus)!, surface) >= HOST_CONTROL_MIN_ACCENT_CONTRAST,
`${background} background produced ${toolbar.focus} focus ring`);
}
}
});
test("toolbar hover colours and Classic geometry are sanitized independently", () => {
const classic = resolveToolbar({
"--skin-recovery-toolbar-height": "22px",
"--skin-recovery-toolbar-padding": "0 4px",
"--skin-recovery-toolbar-radius": "2px",
"--skin-recovery-toolbar-font-size": "11px",
"--skin-recovery-toolbar-gap": "1px",
"--skin-recovery-toolbar-icon-size": "16px",
});
assert.equal(classic.minHeight, 22);
assert.equal(classic.paddingX, 4);
assert.equal(classic.paddingY, 0);
assert.equal(classic.radius, 2);
assert.equal(classic.fontSize, 11);
assert.equal(classic.gap, 1);
assert.equal(classic.iconSize, 16);
const unreadableHover = resolveToolbar({
"--skin-recovery-toolbar-background": "#ffffff",
"--skin-recovery-toolbar-foreground": "#757575",
"--skin-recovery-toolbar-hover-background": "#eeeeee",
"--skin-recovery-toolbar-hover-border": "not-a-colour",
});
assert.equal(unreadableHover.hoverBackground, "rgb(255, 255, 255)");
assert.equal(unreadableHover.hoverBorder, "rgb(49, 82, 79)");
const clamped = resolveToolbar({
"--skin-recovery-toolbar-gap": "100px",
"--skin-recovery-toolbar-icon-size": "2px",
});
assert.equal(clamped.gap, TOOLBAR_MAX_GAP);
assert.equal(clamped.iconSize, TOOLBAR_MIN_ICON_SIZE);
const oversized = resolveToolbar({ "--skin-recovery-toolbar-icon-size": "100px" });
assert.equal(oversized.iconSize, TOOLBAR_MAX_ICON_SIZE);
assert.equal(resolveToolbar().gap, TOOLBAR_DEFAULT_GAP);
assert.equal(resolveToolbar().iconSize, TOOLBAR_DEFAULT_ICON_SIZE);
});
test("capsule tokens keep their opaque palette and 28px hit target", () => {
const capsule = resolveHostControlTokens(style({
"--skin-recovery-background": "transparent",
"--skin-recovery-foreground": "#1a1a1a",
"--skin-recovery-toolbar-height": "22px",
}), "host.recovery", raw => raw, RECOVERY_CONTROL_DEFAULTS);
assert.equal(capsule.background, "rgb(255, 255, 255)");
assert.equal(capsule.hitTarget, 28);
});
test("unreadable or invalid toolbar tokens fall back to a visible, readable button", () => {
const transparentUnreadable = resolveToolbar({
"--skin-recovery-toolbar-background": "rgba(0, 0, 0, 0)",
"--skin-recovery-toolbar-foreground": "#ffffff",
}, {}, { r: 255, g: 255, b: 255 });
assert.equal(transparentUnreadable.background, "rgb(255, 255, 255)");
assert.equal(transparentUnreadable.foreground, "rgb(49, 82, 79)");
assert.ok(contrastRatio(parseCssColor(transparentUnreadable.foreground)!, parseCssColor(transparentUnreadable.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, TOOLBAR_MIN_HEIGHT);
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": "#ffffff",
"--skin-recovery-toolbar-foreground": "#1a1a1a",
"--skin-recovery-toolbar-padding": "6px 14px",
"--skin-recovery-toolbar-height": "36px",
"--skin-recovery-toolbar-hover-background": "#eaf2fd",
"--skin-recovery-toolbar-hover-border": "#b8cfe8",
"--skin-recovery-toolbar-gap": "1px",
"--skin-recovery-toolbar-icon-size": "16px",
}));
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.background), "rgb(255, 255, 255)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.foreground), "rgb(26, 26, 26)");
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");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBackground), "rgb(234, 242, 253)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBorder), "rgb(184, 207, 232)");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.gap), "1px");
assert.equal(values.get(HOST_TOOLBAR_APPLIED_VARIABLES.iconSize), "16px");
applyHostControlToolbarTokens(control, null);
assert.equal(values.size, 0);
});
+359 -5
View File
@@ -44,6 +44,42 @@ 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",
"hover-background", "hover-border", "surface", "gap", "icon-size",
] 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",
"hover-background": "--skin-host-toolbar-hover-background",
"hover-border": "--skin-host-toolbar-hover-border",
surface: "--skin-host-toolbar-surface",
gap: "--skin-host-toolbar-gap",
"icon-size": "--skin-host-toolbar-icon-size",
};
/** 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 +110,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 +128,25 @@ 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",
hoverBackground: "--ws-toolbar-hover-background",
hoverBorder: "--ws-toolbar-hover-border",
gap: "--ws-toolbar-gap",
iconSize: "--ws-toolbar-icon-size",
} as const;
export interface HostControlRawTokens {
/** Computed-style colour values; unresolved values are rejected. */
accent?: string;
@@ -130,12 +189,39 @@ 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; defaults to the size tier and may reach 22px in toolbar mode. */
minHeight: number;
shadow: string;
hoverBackground: string;
hoverBorder: string;
/** Space between grouped host buttons. */
gap: number;
/** Size of the host-owned toolbar icon. */
iconSize: number;
/** Focus ring colour, from the readable accent of the control palette. */
focus: string;
}
export interface RgbColor {
r: number;
g: number;
b: number;
}
export interface RgbaColor extends RgbColor {
a: number;
}
const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 };
const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 };
const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 };
@@ -147,6 +233,29 @@ 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; only an explicit height may reach 22px. */
export const TOOLBAR_MIN_HEIGHT = 22;
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;
export const TOOLBAR_DEFAULT_GAP = 4;
export const TOOLBAR_MAX_GAP = 16;
export const TOOLBAR_DEFAULT_ICON_SIZE = 16;
export const TOOLBAR_MIN_ICON_SIZE = 12;
export const TOOLBAR_MAX_ICON_SIZE = 24;
const MAX_SHADOW_LENGTH = 160;
const LENGTH_PX_PATTERN = /^(-?\d+(?:\.\d+)?)px$/i;
const PADDING_PATTERN = /^(0|\d+(?:\.\d+)?px)(?:\s+(0|\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
@@ -206,10 +315,11 @@ export const PERMISSION_CONTROL_DEFAULTS: HostControlDefaults = {
},
};
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
export function parseCssColor(value: string | undefined | null): RgbColor | null {
/** Parse CSS colours to sRGB channels plus alpha for toolbar transparency checks. */
export function parseCssColorWithAlpha(value: string | undefined | null): RgbaColor | null {
if (!value) return null;
const text = value.trim().toLowerCase();
if (text === "transparent") return { r: 0, g: 0, b: 0, a: 0 };
const hex = /^#([0-9a-f]{3,8})$/.exec(text);
if (hex) {
const digits = hex[1];
@@ -218,6 +328,7 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
r: Number.parseInt(digits[0] + digits[0], 16),
g: Number.parseInt(digits[1] + digits[1], 16),
b: Number.parseInt(digits[2] + digits[2], 16),
a: digits.length === 4 ? Number.parseInt(digits[3] + digits[3], 16) / 255 : 1,
};
}
if (digits.length === 6 || digits.length === 8) {
@@ -225,6 +336,7 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
r: Number.parseInt(digits.slice(0, 2), 16),
g: Number.parseInt(digits.slice(2, 4), 16),
b: Number.parseInt(digits.slice(4, 6), 16),
a: digits.length === 8 ? Number.parseInt(digits.slice(6, 8), 16) / 255 : 1,
};
}
return null;
@@ -242,7 +354,30 @@ export function parseCssColor(value: string | undefined | null): RgbColor | null
const channel = percent ? parsed * 2.55 : parsed;
channels.push(Math.round(Math.min(255, Math.max(0, channel))));
}
return { r: channels[0], g: channels[1], b: channels[2] };
let alpha = 1;
if (parts.length === 4) {
const rawAlpha = Number.parseFloat(parts[3]);
if (!Number.isFinite(rawAlpha)) return null;
alpha = parts[3].endsWith("%") ? rawAlpha / 100 : rawAlpha;
alpha = Math.min(1, Math.max(0, alpha));
}
return { r: channels[0], g: channels[1], b: channels[2], a: alpha };
}
/** Parse `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()` and `rgba()`. */
export function parseCssColor(value: string | undefined | null): RgbColor | null {
const color = parseCssColorWithAlpha(value);
return color ? { r: color.r, g: color.g, b: color.b } : null;
}
/** Composite a possibly translucent colour over an opaque sRGB surface. */
export function compositeRgb(foreground: RgbaColor, background: RgbColor): RgbColor {
const alpha = Math.min(1, Math.max(0, foreground.a));
return {
r: Math.round(foreground.r * alpha + background.r * (1 - alpha)),
g: Math.round(foreground.g * alpha + background.g * (1 - alpha)),
b: Math.round(foreground.b * alpha + background.b * (1 - alpha)),
};
}
export function formatRgb(color: RgbColor): string {
@@ -449,6 +584,225 @@ 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(TOOLBAR_MIN_HEIGHT, height))
: fallback;
}
function sanitizeToolbarLength(value: string | undefined, fallback: number, min: number, max: number): number {
if (!value) return fallback;
const match = LENGTH_PX_PATTERN.exec(value.trim());
if (!match) return fallback;
const length = Number.parseFloat(match[1]);
return Number.isFinite(length) ? Math.min(max, Math.max(min, length)) : 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())
);
}
function parseToolbarColor(raw: string | undefined, probeColor: ColorProbe): RgbaColor | null {
return parseCssColorWithAlpha(raw ? probeColor(raw) : undefined);
}
function formatToolbarColor(color: RgbaColor): string {
return color.a === 0 ? "transparent" : formatRgb(color);
}
function resolveToolbarSurface(
partTokens: Partial<Record<HostToolbarTokenName, string>>,
globalTokens: Partial<Record<HostToolbarTokenName, string>>,
probeColor: ColorProbe,
sampledSurface: RgbColor | null | undefined,
defaults: HostControlDefaults,
): RgbColor {
for (const raw of [partTokens.surface, globalTokens.surface]) {
const color = parseToolbarColor(raw, probeColor);
if (color?.a === 1) return { r: color.r, g: color.g, b: color.b };
}
return sampledSurface ?? defaults.background;
}
function readableColorOn(candidates: readonly RgbColor[], background: RgbColor): RgbColor {
const readable = candidates.find((color) => contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST);
if (readable) return readable;
return contrastRatio(ON_ACCENT_DARK, background) >= contrastRatio(ON_ACCENT_LIGHT, background)
? ON_ACCENT_DARK
: ON_ACCENT_LIGHT;
}
function resolveToolbarBorder(
raw: string | undefined,
background: RgbColor,
fallbacks: readonly RgbColor[],
probeColor: ColorProbe,
): string {
const color = parseToolbarColor(raw, probeColor);
if (!color) return formatRgb(readableColorOn(fallbacks, background));
if (color.a === 0) return "transparent";
return contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST
? formatRgb(color)
: formatRgb(readableColorOn(fallbacks, background));
}
function resolveToolbarHoverBorder(raw: string | undefined, fallback: string, probeColor: ColorProbe): string {
const color = parseToolbarColor(raw, probeColor);
if (!color) return fallback;
// Classic's subtle #b8cfe8 hover edge is intentionally below the 3:1
// non-text contrast floor; validate syntax without rejecting that design.
return formatToolbarColor(color);
}
/**
* Resolve the toolbar button palette and geometry.
*
* Transparent backgrounds and borders are valid. Text is checked against an
* explicit opaque `surface` token, or the caller's sampled anchor/ancestor
* surface, never against transparent black. Opaque colours keep the existing
* capsule contrast floors. Hover colours fall back independently to the normal
* button colours, and only an explicit toolbar height may reach the 22px
* Classic toolbar floor; the size-tier default remains 28/32/36px.
*/
export function resolveHostControlToolbarTokens(
style: Pick<CSSStyleDeclaration, "getPropertyValue"> | null,
part: string,
probeColor: ColorProbe,
defaults: HostControlDefaults,
isWebFont: WebFontCheck = NO_WEB_FONTS,
sampledSurface?: RgbColor | null,
): 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;
const baseAccent = parseCssColor(base.accent) ?? defaults.accent;
const surface = resolveToolbarSurface(partTokens, globalTokens, probeColor, sampledSurface, defaults);
let background = parseToolbarColor(merged.background, probeColor) ?? { ...baseBackground, a: 1 };
let foreground = parseToolbarColor(merged.foreground, probeColor) ?? { ...baseForeground, a: 1 };
let effectiveBackground = background.a === 0 ? surface : background;
if (contrastRatio(foreground, effectiveBackground) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
background = { ...baseBackground, a: 1 };
foreground = { ...baseForeground, a: 1 };
effectiveBackground = baseBackground;
}
const border = resolveToolbarBorder(merged.border, effectiveBackground, [baseBorder, baseForeground], probeColor);
let hoverBackground = parseToolbarColor(merged["hover-background"], probeColor) ?? background;
let effectiveHoverBackground = hoverBackground.a === 0 ? surface : hoverBackground;
if (contrastRatio(foreground, effectiveHoverBackground) < HOST_CONTROL_MIN_FOREGROUND_CONTRAST) {
hoverBackground = background;
effectiveHoverBackground = effectiveBackground;
}
const hoverBorder = resolveToolbarHoverBorder(merged["hover-border"], border, probeColor);
const padding = sanitizeToolbarPadding(merged.padding);
return {
background: formatToolbarColor(background),
foreground: formatRgb(foreground),
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",
hoverBackground: formatToolbarColor(hoverBackground),
hoverBorder,
gap: sanitizeToolbarLength(merged.gap, TOOLBAR_DEFAULT_GAP, 0, TOOLBAR_MAX_GAP),
iconSize: sanitizeToolbarLength(
merged["icon-size"],
TOOLBAR_DEFAULT_ICON_SIZE,
TOOLBAR_MIN_ICON_SIZE,
TOOLBAR_MAX_ICON_SIZE,
),
focus: formatRgb(readableColorOn([baseAccent, baseForeground], effectiveBackground)),
};
}
/** 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);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBackground, tokens.hoverBackground);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.hoverBorder, tokens.hoverBorder);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.gap, `${tokens.gap}px`);
style.setProperty(HOST_TOOLBAR_APPLIED_VARIABLES.iconSize, `${tokens.iconSize}px`);
}
export interface HostControlThemeBindingOptions {
layer: HostOwnedLayer;
/** The host-owned element whose inline `--ws-control-*` variables are set. */
@@ -584,8 +938,8 @@ export function createHostControlProbe(shadow: ShadowRoot): HostControlProbe {
canvas.fillStyle = "#000";
canvas.fillStyle = computed;
canvas.fillRect(0, 0, 1, 1);
const [r, g, b] = canvas.getImageData(0, 0, 1, 1).data;
return formatRgb({ r, g, b });
const [r, g, b, a] = canvas.getImageData(0, 0, 1, 1).data;
return a === 255 ? formatRgb({ r, g, b }) : `rgba(${r}, ${g}, ${b}, ${a / 255})`;
};
return {
@@ -6,6 +6,7 @@ import {
FLOATING_WEIGHT_PROTECTED,
FLOATING_WEIGHT_POINTER,
chooseFloatingPosition,
floatingHitsAvoidRect,
floatingRect,
shouldFold,
floatingScore,
@@ -33,6 +34,23 @@ test("floating rects follow the corner margins and stay inside the viewport", ()
assert.ok(narrow.bottom <= 844);
});
test("a docked host toolbar is an excluded floating spot, not just a weighted obstacle", () => {
// 318px stage from the GUI retest: a 218x36 built-in toolbar docked at the
// top-left; the fallback capsule is 169x38. Top corners overlap it, so a
// capsule pushed off the bottom dock must not land there.
const narrow = { width: 318, height: 638 };
const cap = { width: 169, height: 38 };
const dockedToolbar = rect(20, 10, 218, 36);
assert.equal(floatingHitsAvoidRect("top-left", cap, narrow, margins, [dockedToolbar]), true);
assert.equal(floatingHitsAvoidRect("top-right", cap, narrow, margins, [dockedToolbar]), true);
assert.equal(floatingHitsAvoidRect("top-center", cap, narrow, margins, [dockedToolbar]), true);
assert.equal(floatingHitsAvoidRect("middle-left", cap, narrow, margins, [dockedToolbar]), false);
assert.equal(floatingHitsAvoidRect("middle-right", cap, narrow, margins, [dockedToolbar]), false);
assert.equal(floatingHitsAvoidRect("bottom-left", cap, narrow, margins, [dockedToolbar]), false);
// A one-pixel brush against the footprint is not a cover.
assert.equal(floatingHitsAvoidRect("top-left", cap, narrow, margins, [rect(180, 50, 10, 10)]), false);
});
test("score is zero without overlap, ignores 1px brushes and weights dialog and (above all) protected controls", () => {
const footprint = rect(12, 724, 200, 38);
assert.equal(floatingScore(footprint, [{ rect: rect(400, 400, 40, 40), weight: 1 }]), 0);
@@ -108,6 +126,21 @@ test("a move never lands on the pointer or the focused control, but the current
assert.equal(stay.position, "top-left");
});
test("an externally excluded current position is scored like every replacement candidate", () => {
const pointerAndFocus: FloatingObstacle = { rect: rect(84, 15, 32, 32), weight: FLOATING_WEIGHT_POINTER };
const choice = chooseFloatingPosition({
current: "bottom-left",
currentEligible: false,
size: capsule,
viewport,
margins,
obstacles: [],
moveObstacles: [pointerAndFocus],
positions: ["top-left", "top-right"],
});
assert.deepEqual(choice, { position: "top-right", score: 0 });
});
test("folding needs to free at least one control; a full-screen click-away layer does not fold the capsule", () => {
const backdrop: FloatingObstacle[] = [{ rect: rect(0, 0, 1280, 800), weight: FLOATING_WEIGHT_CONTROL }];
const full = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles: backdrop });
+54 -10
View File
@@ -165,10 +165,13 @@ export interface FloatingChoice {
* modal dialog's backdrop, a toast) and going back there would cover it.
* `moveObstacles` (the user's pointer and focused control) only count against
* positions the control would move to, so it never jumps under the cursor or
* onto the field being typed in.
* onto the field being typed in. Set `currentEligible` false when an external
* hard exclusion removes the real current position; it must then be scored like
* every other candidate instead of being replaced by a synthetic current spot.
*/
export function chooseFloatingPosition(input: {
current: FloatingPosition;
currentEligible?: boolean;
size: FloatingSize;
viewport: FloatingViewport;
margins: FloatingMargins;
@@ -179,17 +182,19 @@ export function chooseFloatingPosition(input: {
}): FloatingChoice {
const positions = input.positions ?? FLOATING_POSITIONS;
const moveObstacles = input.moveObstacles ?? [];
const currentEligible = input.currentEligible ?? true;
const scoreAt = (position: FloatingPosition) => {
const footprint = floatingRect(position, input.size, input.viewport, input.margins);
const score = floatingScore(footprint, input.obstacles);
return position === input.current || !moveObstacles.length ? score : score + floatingScore(footprint, moveObstacles);
const keepCurrent = currentEligible && position === input.current;
return keepCurrent || !moveObstacles.length ? score : score + floatingScore(footprint, moveObstacles);
};
const currentScore = scoreAt(input.current);
if (currentScore === 0) {
if (currentEligible && currentScore === 0) {
if (input.home && input.home !== input.current && scoreAt(input.home) === 0) return { position: input.home, score: 0 };
return { position: input.current, score: 0 };
}
let best: FloatingChoice = { position: input.current, score: currentScore };
let best: FloatingChoice = { position: input.current, score: currentEligible ? currentScore : Number.POSITIVE_INFINITY };
for (const position of positions) {
if (position === input.current) continue;
const score = scoreAt(position);
@@ -228,6 +233,22 @@ function rectsIntersect(first: HostPartRect, second: HostPartRect): boolean {
return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;
}
/**
* Whether a candidate corner would put the control on top of a docked host
* control. Used to exclude such spots outright; scoring alone can still pick
* one when the other corners cover skin controls.
*/
export function floatingHitsAvoidRect(
position: FloatingPosition,
size: FloatingSize,
viewport: FloatingViewport,
margins: FloatingMargins,
avoidRects: readonly HostPartRect[],
): boolean {
const footprint = floatingRect(position, size, viewport, margins);
return avoidRects.some(rect => rectsIntersect(footprint, rect));
}
/* ------------------------------------------------------------------ *
* DOM binding
* ------------------------------------------------------------------ */
@@ -358,6 +379,14 @@ export interface FloatingAvoidanceOptions {
onCompactChange?: (compact: boolean) => void;
/** Skip re-evaluation (hovered, focused, slotted, drawer open…). */
paused?: () => boolean;
/**
* Footprints of host controls that are docked in the top layer. They are
* invisible to `collectFloatingObstacles` (which scans the light DOM), but a
* floating fallback must never sit on them: a covered button loses its
* label and its click lands on the wrong action. Positions that intersect
* one of these rects are skipped whenever any free position exists.
*/
avoidRects?: () => readonly HostPartRect[];
}
export interface FloatingAvoidance {
@@ -457,13 +486,28 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
}
const now = Date.now();
const urgent = now < urgentUntil;
// Return home only after a screen change (see chooseFloatingPosition).
const home = urgent ? defaultPosition : undefined;
const full = chooseFloatingPosition({ current: position, size, viewport, margins, obstacles, moveObstacles, home });
// Docked recovery toolbars live in the closed shadow root, so the light-DOM
// obstacle scan above cannot see them. Exclude their footprints outright:
// scoring alone could still park the fallback where a docked button sits
// (GUI reproduced this at 320px: the library capsule covered the built-in
// toolbar and its centre click hit the built-in action). If every corner
// is docked, fall back to scoring over all positions rather than trapping
// the capsule off-screen.
const avoid = options.avoidRects?.() ?? [];
const forbiddenAt = (candidate: FloatingPosition) =>
floatingHitsAvoidRect(candidate, size, viewport, margins, avoid);
const freePositions = FLOATING_POSITIONS.filter(candidate => !forbiddenAt(candidate));
const positions = freePositions.length ? freePositions : FLOATING_POSITIONS;
const currentEligible = !forbiddenAt(position);
const park = forbiddenAt(defaultPosition) && freePositions.length ? freePositions[0] : defaultPosition;
// Return home only after a screen change (see chooseFloatingPosition), and
// only when the default corner is not one of the docked footprints.
const home = urgent && !forbiddenAt(defaultPosition) ? defaultPosition : undefined;
const full = chooseFloatingPosition({ current: position, currentEligible, size, viewport, margins, obstacles, moveObstacles, positions, home });
let next = full;
let nextCompact = false;
if (full.score > 0 && small && small.width > 0 && small.height > 0) {
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles, moveObstacles });
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles, moveObstacles, positions });
if (shouldFold(full, reduced)) {
next = reduced;
nextCompact = true;
@@ -514,8 +558,8 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
moveTimes = [];
frozenUntil = now + HOST_FLOATING_FLAP_FREEZE_MS;
frozenEscaped = false;
if (position !== defaultPosition) {
position = defaultPosition;
if (position !== park) {
position = park;
apply(position);
}
setCompact(false);
+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;
}
@@ -9,6 +9,7 @@ type ShortcutEvent = {
altKey: boolean;
shiftKey: boolean;
key: string;
code: string;
};
const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
@@ -17,6 +18,7 @@ const shortcut = (overrides: Partial<ShortcutEvent> = {}): ShortcutEvent => ({
altKey: false,
shiftKey: false,
key: "",
code: "",
...overrides,
});
@@ -24,16 +26,28 @@ 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);
// Option/Shift turn the letter into a derived character (US layout: ®) on
// macOS; the physical key code must still match.
assert.equal(isRecoveryShortcut(shortcut({
metaKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyR",
})), true);
assert.equal(isRecoveryShortcut(shortcut({
ctrlKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyR",
})), true);
for (const rejected of [
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "x" }),
shortcut({ ctrlKey: true, altKey: true, shiftKey: true, key: "Enter" }),
// A derived character alone is not enough: the physical key must be R.
shortcut({ metaKey: true, altKey: true, shiftKey: true, key: "®", code: "KeyX" }),
// 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" }),
// Incomplete modifiers stay rejected even when the physical code matches.
shortcut({ ctrlKey: true, altKey: true, key: "®", code: "KeyR" }),
]) {
assert.equal(isRecoveryShortcut(rejected), false, JSON.stringify(rejected));
}
@@ -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,
@@ -160,9 +161,68 @@ test("a slotted capsule that would cover a protected control falls back", () =>
assert.deepEqual(evaluateSlottedControl({ ...baseEvaluation, coversProtected: false }), { ok: true });
});
test("a toolbar that would cover another docked host control falls back", () => {
assert.deepEqual(
evaluateSlottedControl({
...baseEvaluation,
otherControls: [rect(160, 105, 120, 30)],
}),
{ ok: false, reason: "covers-host-control" },
);
// Edge contact is not a collision; both toolbars can still dock side by side.
assert.deepEqual(
evaluateSlottedControl({
...baseEvaluation,
otherControls: [rect(60, 105, 120, 30)],
}),
{ ok: true },
);
assert.deepEqual(
evaluateSlottedControl({ ...baseEvaluation, otherControls: [] }),
{ ok: true },
);
});
test("rect overlap ignores edge contact and sub-pixel slivers", () => {
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(50, 10, 100, 40)), true);
assert.equal(rectsOverlap(rect(0, 0, 100, 40), rect(100, 0, 50, 40)), false);
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 },
);
});
+110 -19
View File
@@ -20,11 +20,17 @@ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
import {
RECOVERY_CONTROL_DEFAULTS,
applyHostControlTokens,
applyHostControlToolbarTokens,
compositeRgb,
createHostControlProbe,
findSkinRoot,
parseCssColorWithAlpha,
resolveHostControlTokens,
resolveHostControlToolbarTokens,
type HostControlTokens,
type HostControlProbe,
type RgbColor,
type RgbaColor,
} from "./host-control-tokens.js";
export interface SlotViewport {
@@ -81,6 +87,7 @@ export type SlotFailureReason =
| "control-too-small"
| "control-offscreen"
| "covers-protected"
| "covers-host-control"
| "hit-test";
export interface SlotAnchorSnapshot {
@@ -107,6 +114,8 @@ export interface SlotEvaluationInput {
* capsule is top layer, so it would block those controls for the pointer.
*/
coversProtected?: boolean;
/** Footprints of other docked host controls this one must not cover. */
otherControls?: readonly HostPartRect[];
}
export type SlotEvaluation = { ok: true } | { ok: false; reason: SlotFailureReason };
@@ -161,6 +170,13 @@ export function evaluateSlottedControl(input: SlotEvaluationInput): SlotEvaluati
return { ok: false, reason: "control-too-small" };
}
if (!fullyInsideViewport(controlRect, viewport)) return { ok: false, reason: "control-offscreen" };
// Two independently anchored recovery toolbars can converge on the same
// narrow anchor (for example at 320px). Covering a sibling host control
// would make one of the buttons unreachable, so that action returns to the
// visible floating capsule instead of pretending to be docked.
if (input.otherControls?.some((rect) => rectsOverlap(controlRect, rect))) {
return { ok: false, reason: "covers-host-control" };
}
if (input.coversProtected) return { ok: false, reason: "covers-protected" };
if (!hitTestOk) return { ok: false, reason: "hit-test" };
return { ok: true };
@@ -214,6 +230,22 @@ function rectOf(rect: DOMRect | HostPartRect): HostPartRect {
};
}
/** Composite the anchor and top-bar ancestor backgrounds over the page canvas. */
export function sampleOpaqueSurface(element: Element | null, doc: Document = document): RgbColor {
const view = doc.defaultView;
const layers: RgbaColor[] = [];
for (let current: Element | null = element; current && view; current = current.parentElement) {
const color = parseCssColorWithAlpha(view.getComputedStyle(current).backgroundColor);
if (color && color.a > 0) layers.push(color);
if (color?.a === 1) break;
}
let surface: RgbColor = { r: 255, g: 255, b: 255 };
for (let index = layers.length - 1; index >= 0; index -= 1) {
surface = compositeRgb(layers[index], surface);
}
return surface;
}
/** Overlap of two rects in CSS pixels on both axes (more than 1px each). */
export function rectsOverlap(first: HostPartRect, second: HostPartRect): boolean {
const width = Math.min(first.right, second.right) - Math.max(first.left, second.left);
@@ -271,22 +303,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 +341,30 @@ 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-*` / `--skin-host-toolbar-*`
* tokens for background, foreground, border, hover, radius, font, font size,
* padding, height, shadow, surface, gap and icon size. 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;
/** Live footprints of other docked host controls; overlaps force a fallback. */
otherControls?: () => readonly HostPartRect[];
onModeChange?: (change: HostSlotModeChange) => void;
}
@@ -332,11 +392,12 @@ 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;
let currentAnchor: HTMLElement | null = null;
let observingControl = false;
let observer: ResizeObserver | null = null;
const probe: HostControlProbe = createHostControlProbe(layer.shadow);
let frame: number | undefined;
@@ -348,9 +409,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,
@@ -387,27 +448,51 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
}
function observe(anchorElement: HTMLElement | null): void {
if (currentAnchor === anchorElement) return;
// Measurement-only display changes must not feed back into observer scheduling.
const watchControl = !options.prepare || (state.slotted && control.getClientRects().length > 0);
if (currentAnchor === anchorElement && observingControl === watchControl) return;
currentAnchor = anchorElement;
observingControl = watchControl;
if (!observer && typeof ResizeObserver !== "undefined") {
observer = new ResizeObserver(() => schedule());
}
if (!observer) return;
observer.disconnect();
observer.observe(control);
if (watchControl) observer.observe(control);
if (anchorElement) observer.observe(anchorElement);
}
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);
let toolbarMinHeight: number | undefined;
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. A
// transparent button is checked against the surface behind its anchor.
const toolbarTokens = tokenStyle
? resolveHostControlToolbarTokens(
tokenStyle,
"host.recovery",
probe.probeColor,
RECOVERY_CONTROL_DEFAULTS,
probe.isWebFont,
sampleOpaqueSurface(tokenSource, doc),
)
: null;
toolbarMinHeight = toolbarTokens?.minHeight;
applyHostControlToolbarTokens(control, toolbarTokens);
}
const controlBox = control.getBoundingClientRect();
maxSize = {
@@ -462,8 +547,9 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
anchor: anchorSnapshot,
controlRect: intendedRect,
viewport,
minHitTarget: tokens.hitTarget,
minHitTarget: toolbarMinHeight ?? tokens.hitTarget,
coversProtected,
otherControls: options.otherControls?.(),
hitTestOk: placement
? hitTestAt(placement.left, placement.top, { width: controlBox.width, height: controlBox.height })
: false,
@@ -481,6 +567,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
lastReason = reason;
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
}
options.settle?.(state.slotted);
observe(anchorElement);
}
/** Any unexpected error returns the capsule to the default corner. */
@@ -488,6 +576,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
const wasSlotted = state.slotted;
state = nextSlotModeState(state, false);
clearPlacement();
options.settle?.(false);
observe(currentAnchor);
if (wasSlotted) onModeChange?.({ mode: "floating" });
}
@@ -535,6 +625,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
win.removeEventListener("scroll", schedule, { capture: true });
clearPlacement();
applyHostControlTokens(control, null);
applyHostControlToolbarTokens(control, null);
probe.dispose();
},
};
+21
View File
@@ -5,6 +5,7 @@ import { strToU8, zipSync } from "fflate";
import { importSkinPack, resolveSkinCssAssets, SkinPackError } from "./skin-pack.js";
import { scopeBuiltinThemeForCustomSkin } from "./skin-cascade.js";
import { BUILTIN_SKIN_CATALOG } from "./skin-catalog.js";
import { APP_VERSION } from "./app-version.js";
import type { SkinPluginDocument, SkinPluginNode } from "../../../src/shared/skin-plugin.js";
import { createSkinExtensionWasmPrefixByteImmediateProbe } from "../../test/skin-extension-wasm-fixture.js";
@@ -483,6 +484,26 @@ test("a v4 surface cannot compete with a v3 surface on the same public page", as
);
});
test("the distributable host chrome toolbar declares its first compatible runtime", async () => {
const archive = await readFile(new URL("../../../docs/examples/host-chrome-toolbar.wskin", import.meta.url));
const bundledArchive = await readFile(new URL("../../public/host-chrome-toolbar.wskin", import.meta.url));
assert.deepEqual(bundledArchive, archive, "the downloadable example and bundled skin stay in sync");
const skin = await importSkinPack(new File([archive], "host-chrome-toolbar.wskin", { type: "application/octet-stream" }));
assert.equal(skin.id, "community.host-chrome-toolbar");
assert.equal(skin.minAppVersion, "0.3.3", "mode, appearance and anchor arrays are unavailable in WebSpeak 0.3.2");
assert.equal(skin.version, "1.1.1");
assert.equal(APP_VERSION, skin.minAppVersion, "the running build must satisfy the example's declared minimum");
assert.equal(skin.schemaVersion, 3);
assert.equal(skin.packageType, "open-skin");
assert.deepEqual(skin.chromeData?.slots?.["host.recovery"], {
mode: "toolbar",
appearance: "icon",
anchor: ["home.header", "voice.header"],
align: "end",
compact: false,
});
});
test("the distributable KAAK package provides full home and voice surfaces", async () => {
const archive = await readFile(new URL("../../../docs/examples/kaak-voice.wskin", import.meta.url));
const bundledArchive = await readFile(new URL("../../public/skins/kaak-voice.wskin", import.meta.url));