fix(skin): repair host recovery compatibility and placement

Align the toolbar example with its first compatible runtime, restore recovery after shortcut focus leaves, and harden observer scheduling, contrast, floating avoidance, and private selector validation.
This commit is contained in:
OddTurtleHead committed 2026-11-26 23:06:43 +08:00
1 parent df826f575e
commit 4e8ea3081c
17 files changed
+453 -23

No files matched your search

+3 -1
View File
@@ -12,11 +12,13 @@ A minimal schema v3 open skin that docks the trusted recovery entry into the pag
```text
host-chrome-toolbar/
manifest.json # schema v3, version 1.1.0, author WebSpeak Community
manifest.json # schema v3, version 1.1.1, minAppVersion 0.3.3, author WebSpeak Community
chrome.json # one grouped toolbar slot with a home/voice anchor list
skin.css # light page theme, Classic toolbar tokens and header space
```
This package requires WebSpeak 0.3.3. WebSpeak 0.3.2 does not accept `mode`, `appearance`, or anchor candidate arrays, so importing it there cannot provide toolbar-mode behavior. Older slots without those fields remain valid and keep their capsule presentation.
`skin.css` uses only public `data-ws-part` hooks and sets `--skin-host-toolbar-*` / `--skin-recovery-toolbar-*` variables. It never targets the host toolbar DOM, the recovery capsule, the authorization dialog or the load-failure banner.
## Grouped declaration
Binary file not shown.
@@ -3,11 +3,11 @@
"packageType": "open-skin",
"id": "community.host-chrome-toolbar",
"name": "Host Chrome Toolbar",
"version": "1.1.0",
"version": "1.1.1",
"author": "WebSpeak Community",
"license": "AGPL-3.0-only",
"description": "Minimal open skin that docks Classic-aligned host-owned recovery icons into the page header.",
"entry": "skin.css",
"chrome": "chrome.json",
"minAppVersion": "0.3.2"
"minAppVersion": "0.3.3"
}
+15
View File
@@ -124,6 +124,21 @@ test("host-owned layer attributes are not skin hooks", () => {
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] { color: teal; }'));
});
test("the host toolbar's private class is not a skin hook", () => {
for (const css of [
':root .ws-host-toolbar { color: red; }',
':root [data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
'[data-ws-part="home.header"] .ws-host-toolbar { color: red; }',
'[data-ws-part="home.header"].ws-host-toolbar { color: red; }',
':root .WS-HOST-TOOLBAR { color: red; }',
':root .\\77 s-host-toolbar { color: red; }',
]) {
assert.throws(() => compile(css), /private host class/i, css);
}
// Ordinary descendant classes remain available when a public hook anchors them.
assert.doesNotThrow(() => compile(':root [data-ws-part="home.header"] .skin-button { color: teal; }'));
});
test("trusted, permission, recovery and essential audio controls stay available even for v3 skins", () => {
for (const part of [
"voice.audio-dock",
+4
View File
@@ -108,6 +108,7 @@ const FORBIDDEN_SCOPE_ATTRIBUTES = new Set([
"data-ws-host-layer-content",
"data-ws-recovery-action",
]);
const FORBIDDEN_SCOPE_CLASSES = new Set(["ws-host-toolbar"]);
/** CSS-wide keywords never name a keyframe and reset an animatable slot. */
const CSS_WIDE_KEYWORDS = new Set(["initial", "inherit", "unset", "revert", "revert-layer"]);
/** Shorthand keyword slots; a repeated category frees the word to be the name. */
@@ -457,6 +458,9 @@ function assertHostChromeSelector(selector: string, schemaVersion: SkinCssSchema
if (node.type === "attribute" && FORBIDDEN_SCOPE_ATTRIBUTES.has(node.attribute.toLowerCase())) {
throw new SkinCssValidationError(`Skin selectors cannot reference the host attribute ${node.attribute}.`, "SKIN_CSS_SELECTOR");
}
if (node.type === "class" && FORBIDDEN_SCOPE_CLASSES.has(decodeCssEscapes(node.value).toLowerCase())) {
throw new SkinCssValidationError(`Skin selectors cannot reference the private host class .${node.value}.`, "SKIN_CSS_SELECTOR");
}
if (node.type === "attribute" && node.attribute.toLowerCase() === "data-ws-part" && node.value) {
partNames.push(node.value.replace(/^['"]|['"]$/g, ""));
}
Binary file not shown.
+5 -2
View File
@@ -498,17 +498,20 @@ 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;
}
+28 -2
View File
@@ -322,7 +322,8 @@ test("toolbar tokens are independent of the capsule shell and keep host floors",
const defaults = resolveToolbar();
assert.equal(defaults.background, "rgb(255, 255, 255)");
assert.equal(defaults.foreground, "rgb(49, 82, 79)");
assert.equal(defaults.border, "rgb(157, 182, 178)");
assert.equal(defaults.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);
@@ -394,6 +395,31 @@ test("toolbar colours preserve transparency and check text against an opaque sur
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",
@@ -418,7 +444,7 @@ test("toolbar hover colours and Classic geometry are sanitized independently", (
"--skin-recovery-toolbar-hover-border": "not-a-colour",
});
assert.equal(unreadableHover.hoverBackground, "rgb(255, 255, 255)");
assert.equal(unreadableHover.hoverBorder, "rgb(157, 182, 178)");
assert.equal(unreadableHover.hoverBorder, "rgb(49, 82, 79)");
const clamped = resolveToolbar({
"--skin-recovery-toolbar-gap": "100px",
+16 -5
View File
@@ -677,16 +677,26 @@ function resolveToolbarSurface(
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,
fallback: string,
fallbacks: readonly RgbColor[],
probeColor: ColorProbe,
): string {
const color = parseToolbarColor(raw, probeColor);
if (!color) return fallback;
if (!color) return formatRgb(readableColorOn(fallbacks, background));
if (color.a === 0) return "transparent";
return contrastRatio(color, background) >= HOST_CONTROL_MIN_BORDER_CONTRAST ? formatRgb(color) : fallback;
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 {
@@ -723,6 +733,7 @@ export function resolveHostControlToolbarTokens(
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 };
@@ -732,7 +743,7 @@ export function resolveHostControlToolbarTokens(
foreground = { ...baseForeground, a: 1 };
effectiveBackground = baseBackground;
}
const border = resolveToolbarBorder(merged.border, effectiveBackground, base.border, probeColor);
const border = resolveToolbarBorder(merged.border, effectiveBackground, [baseBorder, baseForeground], probeColor);
let hoverBackground = parseToolbarColor(merged["hover-background"], probeColor) ?? background;
let effectiveHoverBackground = hoverBackground.a === 0 ? surface : hoverBackground;
@@ -763,7 +774,7 @@ export function resolveHostControlToolbarTokens(
TOOLBAR_MIN_ICON_SIZE,
TOOLBAR_MAX_ICON_SIZE,
),
focus: base.accent,
focus: formatRgb(readableColorOn([baseAccent, baseForeground], effectiveBackground)),
};
}
@@ -126,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 });
+11 -6
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);
@@ -493,12 +498,12 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
floatingHitsAvoidRect(candidate, size, viewport, margins, avoid);
const freePositions = FLOATING_POSITIONS.filter(candidate => !forbiddenAt(candidate));
const positions = freePositions.length ? freePositions : FLOATING_POSITIONS;
const current = forbiddenAt(position) && freePositions.length ? freePositions[0] : position;
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, size, viewport, margins, obstacles, moveObstacles, positions, home });
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) {
+8 -3
View File
@@ -397,6 +397,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
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;
@@ -447,14 +448,17 @@ 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);
}
@@ -464,7 +468,6 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
// 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
@@ -565,6 +568,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
onModeChange?.({ mode, ...(reason ? { reason } : {}) });
}
options.settle?.(state.slotted);
observe(anchorElement);
}
/** Any unexpected error returns the capsule to the default corner. */
@@ -573,6 +577,7 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
state = nextSlotModeState(state, false);
clearPlacement();
options.settle?.(false);
observe(currentAnchor);
if (wasSlotted) onModeChange?.({ mode: "floating" });
}
+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));
+83
View File
@@ -0,0 +1,83 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Host floating placement: docked toolbar and pointer avoidance</title>
<style>
html, body { margin: 0; width: 100%; height: 100%; }
</style>
</head>
<body>
<pre id="result">pending</pre>
<script type="module">
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
import { bindFloatingAvoidance, floatingRect } from "/src/services/host-floating-placement.ts";
const output = document.getElementById("result");
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const viewport = { width: innerWidth, height: innerHeight };
const margins = { top: 12, right: 12, bottom: 38, left: 12 };
const size = { width: 200, height: 30 };
try {
const layer = createHostOwnedLayer("recovery", `
.cap { position: fixed; display: flex; width: 200px; height: 30px; pointer-events: auto; }
.cap button { width: 200px; height: 30px; }
`);
if (!layer) throw new Error("recovery layer was not created");
const control = document.createElement("div");
control.className = "cap";
control.setAttribute("popover", "manual");
control.innerHTML = '<button type="button">Use built-in skin</button>';
layer.container.append(control);
control.showPopover();
let bound = false;
const moves = [];
const binding = bindFloatingAvoidance({
element: control,
isSelf: (node) => node === layer.host || layer.host.contains(node),
margins,
defaultPosition: "bottom-left",
avoidRects: () => [
floatingRect("bottom-left", size, viewport, margins),
floatingRect("bottom-right", size, viewport, margins),
],
apply: (position) => {
control.style.left = position.endsWith("left") ? "12px" : position.endsWith("center") ? "50%" : "auto";
control.style.right = position.endsWith("right") ? "12px" : "auto";
control.style.top = position.startsWith("top") ? "12px" : position.startsWith("middle") ? "50%" : "auto";
control.style.bottom = position.startsWith("bottom") ? "38px" : "auto";
control.style.translate = position.endsWith("center") ? "-50% 0" : position.startsWith("middle") ? "0 -50%" : "none";
if (bound) moves.push(position);
},
});
bound = true;
const pointerTarget = floatingRect("top-left", size, viewport, margins);
document.dispatchEvent(new PointerEvent("pointermove", {
bubbles: true,
pointerType: "mouse",
clientX: pointerTarget.left + pointerTarget.width / 2,
clientY: pointerTarget.top + pointerTarget.height / 2,
}));
binding.screenChanged();
await sleep(80);
binding.revalidate();
const box = control.getBoundingClientRect();
output.textContent = JSON.stringify({
position: binding.position,
moves,
pointerTarget: "top-left",
pointerHit: document.elementFromPoint(
pointerTarget.left + pointerTarget.width / 2,
pointerTarget.top + pointerTarget.height / 2,
) === layer.host,
rect: { left: box.left, top: box.top, width: box.width, height: box.height },
});
binding.dispose();
} catch (error) {
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
}
</script>
</body>
</html>
+37 -2
View File
@@ -16,6 +16,7 @@
#home-anchor { left: 20px; }
#voice-anchor { left: 20px; display: none; }
#dock { position: absolute; left: 12px; bottom: 12px; display: flex; gap: 8px; }
#blank { position: absolute; left: 20px; top: 100px; padding: 12px; background: #fff; }
</style>
</head>
<body>
@@ -34,6 +35,7 @@
<button type="button" data-ws-part="voice.audio-dock.microphone">Mic</button>
</div>
<button type="button" id="launcher" data-ws-part="host.plugins.launcher">Plugins</button>
<div id="blank" tabindex="-1">Blank area</div>
</div>
<div id="app"></div>
<pre id="result" style="position:relative;z-index:5;background:#fff">pending</pre>
@@ -209,7 +211,7 @@ try {
capsuleActions: [...(capsule()?.querySelectorAll("[data-ws-recovery-action]") ?? [])]
.map((button) => button.getAttribute("data-ws-recovery-action")),
};
capsule().dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
layer.shadow.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, composed: true }));
await nextTick();
await sleep(150);
const afterEscape = {
@@ -235,7 +237,7 @@ try {
capsuleActions: [...(capsule()?.querySelectorAll("[data-ws-recovery-action]") ?? [])]
.map((button) => button.getAttribute("data-ws-recovery-action")),
};
capsule().dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
layer.shadow.activeElement?.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, composed: true }));
await nextTick();
await sleep(150);
const afterMacEscape = {
@@ -243,6 +245,37 @@ try {
toolbarOpen: isOpen(toolbar()),
};
window.dispatchEvent(new KeyboardEvent("keydown", {
key: "r", ctrlKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
}));
await nextTick();
await sleep(80);
document.getElementById("blank").focus();
await nextTick();
await sleep(150);
const afterFocusOut = {
focusedAction: layer.shadow.activeElement?.getAttribute?.("data-ws-recovery-action") ?? null,
activeId: document.activeElement?.id ?? null,
capsuleOpen: isOpen(capsule()),
toolbarOpen: isOpen(toolbar()),
};
window.dispatchEvent(new KeyboardEvent("keydown", {
key: "r", ctrlKey: true, altKey: true, shiftKey: true, bubbles: true, cancelable: true,
}));
await nextTick();
await sleep(80);
const blank = document.getElementById("blank");
blank.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, composed: true, pointerType: "mouse" }));
blank.dispatchEvent(new MouseEvent("click", { bubbles: true, composed: true }));
await nextTick();
await sleep(150);
const afterBlankClick = {
activeId: document.activeElement?.id ?? null,
capsuleOpen: isOpen(capsule()),
toolbarOpen: isOpen(toolbar()),
};
// Invalid / unreadable toolbar tokens must not make the button invisible.
const voiceAnchor = document.getElementById("voice-anchor");
voiceAnchor.style.setProperty("--skin-recovery-toolbar-background", "rgba(0,0,0,0)");
@@ -270,6 +303,8 @@ try {
afterEscape,
macShortcut,
afterMacEscape,
afterFocusOut,
afterBlankClick,
invalidTokens,
});
} catch (error) {
+132
View File
@@ -0,0 +1,132 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Host slot observer scheduling fixture</title>
<style>
html, body { margin: 0; width: 100%; height: 100%; }
.ws-skin-root { position: relative; width: 100vw; height: 100vh; }
#anchor { position: absolute; left: 20px; top: 20px; width: 240px; height: 48px; background: #f4f7fb; }
</style>
</head>
<body>
<div class="ws-skin-root" data-ws-skin="community.observer-fixture" data-ws-part="app">
<div id="anchor" data-ws-part="skin.home.header.part-host-actions"></div>
</div>
<pre id="result">pending</pre>
<script type="module">
import { bindHostSlot } from "/src/services/host-slot-placement.ts";
import { createHostOwnedLayer, syncRecoveryPopover } from "/src/services/host-owned-layer.ts";
const NativeResizeObserver = window.ResizeObserver;
const observedTargets = new Set();
let resizeCallbacks = 0;
window.ResizeObserver = class extends NativeResizeObserver {
constructor(callback) {
super((entries, observer) => {
resizeCallbacks += 1;
callback(entries, observer);
});
}
observe(target) {
observedTargets.add(target);
super.observe(target);
}
unobserve(target) {
observedTargets.delete(target);
super.unobserve(target);
}
disconnect() {
observedTargets.clear();
super.disconnect();
}
};
const observedIds = () => [...observedTargets]
.map((target) => target.id || target.getAttribute("data-ws-part") || target.tagName.toLowerCase());
const nativeRequestAnimationFrame = window.requestAnimationFrame.bind(window);
let frameCallbacks = 0;
window.requestAnimationFrame = (callback) => nativeRequestAnimationFrame((time) => {
frameCallbacks += 1;
callback(time);
});
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const output = document.getElementById("result");
try {
const layer = createHostOwnedLayer("recovery", `
.toolbar { position: fixed; pointer-events: auto; min-width: 160px; min-height: 28px; }
.toolbar:popover-open { display: flex; }
.toolbar button { min-width: 120px; min-height: 28px; }
`);
if (!layer) throw new Error("recovery layer was not created");
const control = document.createElement("div");
control.id = "measurement-toolbar";
control.className = "toolbar";
control.popover = "manual";
const button = document.createElement("button");
button.type = "button";
button.textContent = "Use built-in skin";
control.append(button);
layer.container.append(control);
const modeChanges = [];
let toolbarVisible = true;
let lastMode = "floating";
const binding = bindHostSlot({
layer,
control,
anchor: "skin.home.header.part-host-actions",
skinId: "community.observer-fixture",
presentation: "toolbar",
prepare: () => syncRecoveryPopover(control, true),
settle: (slotted) => { if (!slotted || !toolbarVisible) syncRecoveryPopover(control, false); },
onModeChange: (change) => { modeChanges.push(change); lastMode = change.mode; },
});
await sleep(120);
const initial = {
mode: modeChanges.at(-1)?.mode ?? null,
reason: modeChanges.at(-1)?.reason ?? null,
open: control.matches(":popover-open"),
width: control.getBoundingClientRect().width,
height: control.getBoundingClientRect().height,
observed: observedIds(),
};
resizeCallbacks = 0;
frameCallbacks = 0;
modeChanges.length = 0;
toolbarVisible = false;
binding.revalidate();
await sleep(600);
const whileDockedButHidden = {
mode: lastMode,
open: control.matches(":popover-open"),
resizeCallbacks,
frameCallbacks,
observed: observedIds(),
};
resizeCallbacks = 0;
frameCallbacks = 0;
modeChanges.length = 0;
document.getElementById("anchor").remove();
binding.revalidate();
await sleep(600);
const afterAnchorRemoved = {
mode: modeChanges.at(-1)?.mode ?? null,
reason: modeChanges.at(-1)?.reason ?? null,
open: control.matches(":popover-open"),
display: getComputedStyle(control).display,
resizeCallbacks,
frameCallbacks,
modeChanges: modeChanges.length,
observed: observedIds(),
};
binding.dispose();
output.textContent = JSON.stringify({ initial, whileDockedButHidden, afterAnchorRemoved });
} catch (error) {
output.textContent = JSON.stringify({ error: String(error?.stack ?? error) });
}
</script>
</body>
</html>
+73
View File
@@ -358,6 +358,73 @@ test("a declared slot docks the capsule and falls back at runtime", { skip: !CHR
assert.equal(byName.disposed.leftoverAccent, "");
});
test("a docked toolbar does not resize-observe its measurement-only fallback", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
const server = await createServer({
root: webRoot,
configFile: path.join(webRoot, "vite.config.ts"),
logLevel: "silent",
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
});
t.after(() => server.close());
await server.listen();
const address = server.httpServer?.address();
const port = address && typeof address === "object" ? address.port : 0;
assert.ok(port, "Vite did not expose a listening port");
const dom = await dumpDom(
`http://127.0.0.1:${port}/test/fixtures/host-slot-observer-loop.html`,
["--virtual-time-budget=5000", "--window-size=1280,800"],
);
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
assert.ok(match, "the observer fixture did not emit a result block");
const payload = JSON.parse(match[1].replace(/&quot;/g, '"').replace(/&amp;/g, "&"));
assert.equal(payload.error, undefined, payload.error);
assert.equal(payload.initial.mode, "slotted");
assert.equal(payload.initial.open, true);
assert.ok(payload.initial.width >= 160 && payload.initial.height >= 28);
assert.ok(payload.initial.observed.includes("anchor"), "the docked toolbar stopped observing its anchor");
assert.ok(payload.initial.observed.includes("measurement-toolbar"), "the docked toolbar stopped observing its own rendered size");
assert.equal(payload.whileDockedButHidden.mode, "slotted");
assert.equal(payload.whileDockedButHidden.open, false);
assert.ok(payload.whileDockedButHidden.resizeCallbacks <= 4, `hiding a docked toolbar caused ${payload.whileDockedButHidden.resizeCallbacks} ResizeObserver callbacks`);
assert.ok(payload.whileDockedButHidden.frameCallbacks <= 4, `hiding a docked toolbar scheduled ${payload.whileDockedButHidden.frameCallbacks} animation frames`);
assert.equal(payload.whileDockedButHidden.observed.includes("measurement-toolbar"), false, "a hidden docked toolbar remained in its own ResizeObserver feedback path");
assert.equal(payload.afterAnchorRemoved.mode, "floating");
assert.equal(payload.afterAnchorRemoved.reason, "anchor-missing");
assert.equal(payload.afterAnchorRemoved.open, false);
assert.ok(payload.afterAnchorRemoved.resizeCallbacks <= 4, `measurement display changes caused ${payload.afterAnchorRemoved.resizeCallbacks} ResizeObserver callbacks`);
assert.ok(payload.afterAnchorRemoved.frameCallbacks <= 4, `measurement display changes scheduled ${payload.afterAnchorRemoved.frameCallbacks} animation frames`);
assert.equal(payload.afterAnchorRemoved.modeChanges, 1, "the fallback repeatedly changed presentation");
assert.equal(payload.afterAnchorRemoved.observed.includes("measurement-toolbar"), false, "the floating measurement-only toolbar remained in its own ResizeObserver feedback path");
});
test("docked-toolbar exclusion still scores pointer and focus obstacles", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
const server = await createServer({
root: webRoot,
configFile: path.join(webRoot, "vite.config.ts"),
logLevel: "silent",
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, ws: false },
});
t.after(() => server.close());
await server.listen();
const address = server.httpServer?.address();
const port = address && typeof address === "object" ? address.port : 0;
assert.ok(port, "Vite did not expose a listening port");
const dom = await dumpDom(
`http://127.0.0.1:${port}/test/fixtures/host-floating-avoid-pointer.html`,
["--virtual-time-budget=5000", "--window-size=1280,800"],
);
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
assert.ok(match, "the floating avoidance fixture did not emit a result block");
const payload = JSON.parse(match[1].replace(/&quot;/g, '"').replace(/&amp;/g, "&"));
assert.equal(payload.error, undefined, payload.error);
assert.notEqual(payload.position, "top-left", "the first toolbar-free candidate bypassed pointer avoidance");
assert.equal(payload.pointerHit, false, "the replacement position landed on the pointer");
assert.ok(payload.rect.left >= 0 && payload.rect.top >= 0);
assert.ok(payload.rect.left + payload.rect.width <= 1280 && payload.rect.top + payload.rect.height <= 800);
});
test("floating host controls move off skin controls at runtime", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
const server = await createServer({
root: webRoot,
@@ -689,6 +756,12 @@ test("toolbar-mode recovery docks plain host buttons, de-duplicates the library
assert.deepEqual(payload.macShortcut.capsuleActions, ["built-in", "library"]);
assert.equal(payload.afterMacEscape.capsuleOpen, false);
assert.equal(payload.afterMacEscape.toolbarOpen, true, "closing the macOS chord did not restore the docked toolbar");
assert.equal(payload.afterFocusOut.activeId, "blank", "focus did not leave the summoned capsule");
assert.equal(payload.afterFocusOut.focusedAction, null);
assert.equal(payload.afterFocusOut.capsuleOpen, false, "focusout left the full shortcut capsule open");
assert.equal(payload.afterFocusOut.toolbarOpen, true, "focusout did not restore the docked toolbar");
assert.equal(payload.afterBlankClick.capsuleOpen, false, "clicking blank space left the full shortcut capsule open");
assert.equal(payload.afterBlankClick.toolbarOpen, true, "clicking blank space did not restore the docked toolbar");
assert.equal(payload.invalidTokens.visible, true, "invalid toolbar tokens hid the button");
assert.equal(payload.invalidTokens.inViewport, true);