fix: keep docked recovery capsule off protected controls and address slot review

- Fall back to the default corner when the docked capsule's footprint
  (largest observed size) overlaps a visible protected control; runtime
  check only, no new chrome.json or skin.css restriction.
- Demo skin docks at align:start, away from the audio dock buttons.
- Compact mode: tap/click pins it open (touch), shortcut expansion clears
  when focus leaves; the 5 s full-display hold starts on first dock.
- Built-in button border uses the skin accent only when visible on #fff7ed.
- probeColor no longer misreads a token equal to its sentinel.
- Periodic re-check survives an exception and fails safe to floating.
- Browser fixture exercises bindHostSlot: dock, fallback, anti-flap,
  protected cover, offscreen, unreadable tokens, dispose.
This commit is contained in:
OddTurtleHead committed 2026-11-15 15:43:08 +08:00
1 parent aefa0bc163
commit 93d221c3ef
10 files changed
+404 -42

No files matched your search

Binary file not shown.
+52 -11
View File
@@ -33,10 +33,12 @@
<div
ref="recoveryPopover"
popover="manual"
@keydown.escape="shortcutOpen = false"
@keydown.escape="onRecoveryEscape"
@click="compactPinned = compact || compactPinned"
@focusout="onRecoveryFocusOut"
class="ws-host-recovery"
:class="{ 'ws-host-recovery-compact': compact }"
:tabindex="compact ? 0 : undefined"
:tabindex="compact || compactPinned ? 0 : undefined"
data-ws-host-recovery
role="region"
:aria-label="copy.recovery"
@@ -131,7 +133,7 @@ const RECOVERY_LAYER_CSS = `
white-space: nowrap;
}
.ws-host-recovery button[data-ws-recovery-action="built-in"] {
border-color: var(--ws-recovery-accent, #b45309);
border-color: var(--ws-recovery-builtin-border, #b45309);
background: #fff7ed;
color: #7c2d12;
}
@@ -182,29 +184,65 @@ const slotMode = ref<"floating" | "slotted">("floating");
const compactHold = ref(true);
let compactHoldTimer: ReturnType<typeof setTimeout> | undefined;
// Keep the full capsule visible for a moment after it first docks into a
// newly activated skin, so the entry stays discoverable before it folds into
// the skin's layout. The skin id is known from localStorage before the skin
// (and its anchor) has loaded, so the 5 s window starts on the first
// floating -> slotted transition for that skin, not on the id change.
let compactHoldStarted = false;
watch(hostChromeActiveSkinId, () => {
// Keep the full capsule visible for a moment after a skin is activated, so
// the entry stays discoverable before it folds into the skin's layout.
compactHold.value = true;
compactHoldStarted = false;
if (compactHoldTimer) clearTimeout(compactHoldTimer);
compactHoldTimer = setTimeout(() => { compactHold.value = false; }, 5000);
compactHoldTimer = undefined;
}, { immediate: true });
watch(slotMode, (mode) => {
if (mode !== "slotted" || compactHoldStarted) return;
compactHoldStarted = true;
compactHoldTimer = setTimeout(() => { compactHold.value = false; }, 5000);
});
/** Set by the shortcut; cleared once focus leaves the capsule. */
const shortcutExpanded = ref(false);
/** A tap/click on the compact mark keeps it expanded (no hover on touch). */
const compactPinned = ref(false);
const compact = computed(() => Boolean(slotConfig.value?.compact)
&& slotMode.value === "slotted"
&& !compactHold.value
&& !shortcutOpen.value);
&& !shortcutExpanded.value
&& !compactPinned.value);
function onRecoveryEscape() {
shortcutOpen.value = false;
shortcutExpanded.value = false;
compactPinned.value = false;
}
/** Unpin when the pointer goes down anywhere outside the host layer. */
function onDocumentPointerDown(event: PointerEvent) {
if (!compactPinned.value || !layer) return;
// Events from inside the closed shadow root are retargeted to its host.
if (event.composedPath().includes(layer.host)) return;
compactPinned.value = false;
}
function onRecoveryFocusOut(event: FocusEvent) {
const next = event.relatedTarget;
if (next instanceof Node && recoveryPopover.value?.contains(next)) return;
shortcutExpanded.value = false;
compactPinned.value = false;
}
let slotBinding: HostSlotBinding | undefined;
function syncSlotBinding() {
slotBinding?.dispose();
slotBinding = undefined;
// 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) {
slotMode.value = "floating";
return;
}
if (!control || !config || !layer) return;
slotBinding = bindHostSlot({
layer,
control,
@@ -236,6 +274,7 @@ function onKeydown(event: KeyboardEvent) {
if (isRecoveryShortcut(event)) {
event.preventDefault();
shortcutOpen.value = true;
shortcutExpanded.value = true;
void nextTick(() => {
syncPopover();
slotBinding?.revalidate();
@@ -268,6 +307,7 @@ onMounted(() => {
reachabilityTimer = setInterval(refreshLauncherReachability, 1000);
window.addEventListener("resize", refreshLauncherReachability);
window.addEventListener("keydown", onKeydown, true);
window.addEventListener("pointerdown", onDocumentPointerDown, true);
void nextTick(() => {
syncPopover();
syncSlotBinding();
@@ -279,6 +319,7 @@ onBeforeUnmount(() => {
slotBinding?.dispose();
window.removeEventListener("resize", refreshLauncherReachability);
window.removeEventListener("keydown", onKeydown, true);
window.removeEventListener("pointerdown", onDocumentPointerDown, true);
layer?.dispose();
});
</script>
+17 -14
View File
@@ -92,20 +92,23 @@ test("slot declarations are honoured for third-party skins only", () => {
}));
setSkinHostChromeParts(document);
setHostChromeActiveSkin("community.demo");
assert.deepEqual(activeHostSlot("host.recovery"), {
anchor: "voice.audio-dock",
align: "end",
compact: false,
});
// A part that is not slottable cannot be selected through chrome.json.
assert.equal(activeHostSlot("host.permission"), undefined);
try {
assert.deepEqual(activeHostSlot("host.recovery"), {
anchor: "voice.audio-dock",
align: "end",
compact: false,
});
// A part that is not slottable cannot be selected through chrome.json.
assert.equal(activeHostSlot("host.permission"), undefined);
// Bundled/official skins keep the default floating placement.
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
setHostChromeActiveSkin(id);
assert.equal(activeHostSlot("host.recovery"), undefined, String(id));
// Bundled/official skins keep the default floating placement.
for (const id of [undefined, "builtin.light", "builtin.dark", "community.illusia-voice", "community.kaak-voice"]) {
setHostChromeActiveSkin(id);
assert.equal(activeHostSlot("host.recovery"), undefined, String(id));
}
} finally {
// Module-global state: never leak it into sibling tests.
setSkinHostChromeParts(undefined);
setHostChromeActiveSkin(undefined);
}
setSkinHostChromeParts(undefined);
setHostChromeActiveSkin(undefined);
});
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test";
import {
INITIAL_SLOT_MODE_STATE,
RECOVERY_BUILT_IN_BUTTON_BACKGROUND,
RECOVERY_MIN_ACCENT_CONTRAST,
RECOVERY_MIN_FONT_SIZE,
RECOVERY_MIN_FOREGROUND_CONTRAST,
@@ -12,6 +13,7 @@ import {
evaluateSlottedControl,
nextSlotModeState,
parseCssColor,
rectsOverlap,
relativeLuminance,
resolveRecoveryTokens,
type SlotAnchorSnapshot,
@@ -157,6 +159,7 @@ test("skin tokens default to the host palette", () => {
const tokens = resolveRecoveryTokens();
assert.deepEqual(tokens, {
accent: "rgb(180, 83, 9)",
builtInBorder: "rgb(180, 83, 9)",
background: "rgb(255, 255, 255)",
foreground: "rgb(49, 82, 79)",
radius: 999,
@@ -241,3 +244,29 @@ test("the mode gate does not flap between the anchor and the fallback", () => {
assert.equal(state.slotted, true);
assert.equal(state.hasSlotted, true);
});
test("a slotted capsule that would cover a protected control falls back", () => {
assert.deepEqual(
evaluateSlottedControl({ ...baseEvaluation, coversProtected: true }),
{ ok: false, reason: "covers-protected" },
);
assert.deepEqual(evaluateSlottedControl({ ...baseEvaluation, coversProtected: false }), { 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("the built-in button border only uses an accent visible on its fixed light background", () => {
// Passes against the dark skin background, but vanishes on #fff7ed.
const pale = resolveRecoveryTokens({ background: "#141414", foreground: "#ffffff", accent: "#fff7ec" });
assert.equal(pale.accent, "rgb(255, 247, 236)");
assert.equal(pale.builtInBorder, "rgb(180, 83, 9)");
assert.ok(contrastRatio(parseCssColor(pale.builtInBorder)!, RECOVERY_BUILT_IN_BUTTON_BACKGROUND) >= RECOVERY_MIN_ACCENT_CONTRAST);
const strong = resolveRecoveryTokens({ background: "#ffffff", foreground: "#111111", accent: "#1d4ed8" });
assert.equal(strong.builtInBorder, "rgb(29, 78, 216)");
});
+116 -8
View File
@@ -16,6 +16,7 @@
import type { SkinChromeSlotAlign } from "../../../src/shared/skin-chrome.js";
import type { HostOwnedLayer } from "./host-owned-layer.js";
import { isHostPartReachable, type HostPartRect } from "./host-chrome-visibility.js";
import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
export interface SlotViewport {
width: number;
@@ -70,6 +71,7 @@ export type SlotFailureReason =
| "control-hidden"
| "control-too-small"
| "control-offscreen"
| "covers-protected"
| "hit-test";
export interface SlotAnchorSnapshot {
@@ -89,6 +91,13 @@ export interface SlotEvaluationInput {
minHitTarget: number;
/** `document.elementFromPoint` at the control centre is the host layer. */
hitTestOk: boolean;
/**
* The capsule's footprint (at its largest observed size, so a compact
* capsule that expands on hover is included) overlaps a visible protected
* control such as the microphone, output or "clear local data" link. The
* capsule is top layer, so it would block those controls for the pointer.
*/
coversProtected?: boolean;
}
export type SlotEvaluation = { ok: true } | { ok: false; reason: SlotFailureReason };
@@ -143,6 +152,7 @@ export function evaluateSlottedControl(input: SlotEvaluationInput): SlotEvaluati
return { ok: false, reason: "control-too-small" };
}
if (!fullyInsideViewport(controlRect, viewport)) return { ok: false, reason: "control-offscreen" };
if (input.coversProtected) return { ok: false, reason: "covers-protected" };
if (!hitTestOk) return { ok: false, reason: "hit-test" };
return { ok: true };
}
@@ -217,6 +227,12 @@ export interface RecoveryRawTokens {
export interface RecoveryTokens {
accent: string;
/**
* Border of the built-in-skin button, which keeps its own fixed light
* background (`#fff7ed`). The skin accent is used only when it stays visible
* against that background; otherwise the host default accent is used there.
*/
builtInBorder: string;
background: string;
foreground: string;
radius: number;
@@ -245,6 +261,7 @@ export const RECOVERY_SKIN_TOKEN_PROPERTIES = {
/** Host-owned variables set inside the closed shadow root. */
export const RECOVERY_APPLIED_VARIABLES = {
accent: "--ws-recovery-accent",
builtInBorder: "--ws-recovery-builtin-border",
background: "--ws-recovery-background",
foreground: "--ws-recovery-foreground",
radius: "--ws-recovery-radius",
@@ -254,6 +271,8 @@ export const RECOVERY_APPLIED_VARIABLES = {
} as const;
const DEFAULT_ACCENT: RgbColor = { r: 180, g: 83, b: 9 };
/** Fixed background of the built-in-skin button (`#fff7ed`). */
export const RECOVERY_BUILT_IN_BUTTON_BACKGROUND: RgbColor = { r: 255, g: 247, b: 237 };
const DEFAULT_BACKGROUND: RgbColor = { r: 255, g: 255, b: 255 };
const DEFAULT_FOREGROUND: RgbColor = { r: 49, g: 82, b: 79 };
const DEFAULT_RADIUS = 999;
@@ -361,8 +380,12 @@ export function resolveRecoveryTokens(raw: RecoveryRawTokens = {}): RecoveryToke
const sizeValue = raw.size?.trim();
const size = isRecoverySizeTier(sizeValue) ? sizeValue : "small";
const metrics = RECOVERY_SIZE_METRICS[size];
const builtInBorder = contrastRatio(palette.accent, RECOVERY_BUILT_IN_BUTTON_BACKGROUND) >= RECOVERY_MIN_ACCENT_CONTRAST
? palette.accent
: DEFAULT_ACCENT;
return {
accent: formatRgb(palette.accent),
builtInBorder: formatRgb(builtInBorder),
background: formatRgb(palette.background),
foreground: formatRgb(palette.foreground),
radius: sanitizeRadius(raw.radius),
@@ -381,6 +404,7 @@ export function applyRecoveryTokens(control: HTMLElement, tokens: RecoveryTokens
return;
}
style.setProperty(RECOVERY_APPLIED_VARIABLES.accent, tokens.accent);
style.setProperty(RECOVERY_APPLIED_VARIABLES.builtInBorder, tokens.builtInBorder);
style.setProperty(RECOVERY_APPLIED_VARIABLES.background, tokens.background);
style.setProperty(RECOVERY_APPLIED_VARIABLES.foreground, tokens.foreground);
style.setProperty(RECOVERY_APPLIED_VARIABLES.radius, `${tokens.radius}px`);
@@ -404,6 +428,46 @@ function rectOf(rect: DOMRect | HostPartRect): HostPartRect {
};
}
/** 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);
const height = Math.min(first.bottom, second.bottom) - Math.max(first.top, second.top);
return width > 1 && height > 1;
}
const INTERACTIVE_SELECTOR = "a[href],button,input,select,textarea,[role='button'],[tabindex],[contenteditable='true']";
/**
* Protected controls (`PROTECTED_PART_IDS`) that the capsule must not sit on.
* Ancestors of the anchor (for example `app` or `voice.audio-dock` around a
* dedicated anchor node) are containers, not click targets, and are skipped;
* the anchor itself only counts when it is or contains an interactive control.
*/
export function protectedPartsCovered(
footprint: HostPartRect,
anchorElement: Element,
doc: Document = anchorElement.ownerDocument,
): boolean {
const view = doc.defaultView;
for (const element of doc.querySelectorAll<HTMLElement>("[data-ws-part]")) {
const part = element.getAttribute("data-ws-part") ?? "";
if (!PROTECTED_PART_IDS.has(part)) continue;
if (element === anchorElement) {
if (!element.matches(INTERACTIVE_SELECTOR) && !element.querySelector(INTERACTIVE_SELECTOR)) continue;
} else if (element.contains(anchorElement)) {
continue;
}
const rect = element.getBoundingClientRect();
if (!(rect.width > 0) || !(rect.height > 0)) continue;
if (view) {
const style = view.getComputedStyle(element);
if (style.display === "none" || style.visibility === "hidden" || style.visibility === "collapse") continue;
}
if (rectsOverlap(footprint, rectOf(rect))) return true;
}
return false;
}
function isVisibleAnchor(element: HTMLElement): boolean {
const view = element.ownerDocument.defaultView;
if (!view) return false;
@@ -500,6 +564,8 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
let frame: number | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
let disposed = false;
/** Largest capsule size seen; covers a compact capsule's expanded footprint. */
let maxSize = { width: 0, height: 0 };
const requestFrame = (callback: FrameRequestCallback): number => win.requestAnimationFrame(callback);
const cancelFrame = (handle: number): void => win.cancelAnimationFrame(handle);
@@ -518,10 +584,17 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
if (!raw) return undefined;
const element = ensureProbe();
if (!element) return undefined;
element.style.color = "rgb(1, 2, 3)";
element.style.color = raw;
const computed = win.getComputedStyle(element).color;
return computed === "rgb(1, 2, 3)" ? undefined : computed;
// An invalid value leaves the previous colour in place. Probe against two
// different sentinels so a real token equal to one of them still resolves.
const resolveWith = (sentinel: string): string => {
element.style.color = sentinel;
element.style.color = raw;
return win.getComputedStyle(element).color;
};
const first = resolveWith("rgb(1, 2, 3)");
if (first !== "rgb(1, 2, 3)") return first;
const second = resolveWith("rgb(4, 5, 6)");
return second === "rgb(4, 5, 6)" ? undefined : second;
}
function readTokens(source: Element | null): RecoveryTokens {
@@ -586,6 +659,10 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
applyRecoveryTokens(control, tokenSource ? tokens : null);
const controlBox = control.getBoundingClientRect();
maxSize = {
width: Math.max(maxSize.width, controlBox.width),
height: Math.max(maxSize.height, controlBox.height),
};
const viewport: SlotViewport = { width: win.innerWidth, height: win.innerHeight };
let anchorSnapshot: SlotAnchorSnapshot | null = null;
if (anchorElement) {
@@ -617,12 +694,25 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
// Move first, then hit-test: the capsule has to actually occupy the
// intended point before `elementFromPoint` can see it. The move and a
// failed revert happen in one task, so nothing paints in between.
let coversProtected = false;
if (anchorElement && anchorSnapshot && placement) {
const footprintPlacement = computeSlotPlacement(anchorSnapshot.rect, maxSize, viewport, align);
coversProtected = protectedPartsCovered({
width: maxSize.width,
height: maxSize.height,
left: footprintPlacement.left,
top: footprintPlacement.top,
right: footprintPlacement.left + maxSize.width,
bottom: footprintPlacement.top + maxSize.height,
}, anchorElement, doc);
}
if (placement) applyPlacement(placement.left, placement.top);
const evaluation = evaluateSlottedControl({
anchor: anchorSnapshot,
controlRect: intendedRect,
viewport,
minHitTarget: tokens?.hitTarget ?? RECOVERY_SIZE_METRICS.small.hitTarget,
minHitTarget: tokens.hitTarget,
coversProtected,
hitTestOk: placement
? hitTestAt(placement.left, placement.top, { width: controlBox.width, height: controlBox.height })
: false,
@@ -642,11 +732,23 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
}
}
/** Any unexpected error returns the capsule to the default corner. */
function failSafe(): void {
const wasSlotted = state.slotted;
state = nextSlotModeState(state, false);
clearPlacement();
if (wasSlotted) onModeChange?.({ mode: "floating" });
}
function schedule(): void {
if (disposed || frame !== undefined) return;
frame = requestFrame(() => {
frame = undefined;
evaluate();
try {
evaluate();
} catch {
failSafe();
}
});
}
@@ -654,8 +756,14 @@ export function bindHostSlot(options: HostSlotBindingOptions): HostSlotBinding {
if (disposed) return;
timer = setTimeout(() => {
if (disposed) return;
evaluate();
scheduleTick();
// The periodic check is the safety net; one failing pass must not stop it.
try {
evaluate();
} catch {
failSafe();
} finally {
scheduleTick();
}
}, state.slotted ? HOST_SLOT_SLOTTED_INTERVAL_MS : HOST_SLOT_IDLE_INTERVAL_MS);
}
+124
View File
@@ -0,0 +1,124 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Host slot placement fixture</title>
<style>
html, body { margin: 0; width: 100%; height: 100%; font: 12px/1.5 system-ui, sans-serif; }
.ws-skin-root { position: relative; width: 100vw; height: 100vh; }
#dock { position: absolute; left: 40px; top: 200px; width: 640px; height: 56px; }
#anchor { position: absolute; left: 0; top: 4px; width: 320px; height: 48px; }
#mic { position: absolute; right: 8px; top: 11px; width: 120px; height: 34px; }
</style>
</head>
<body>
<!-- A skin surface: an empty anchor node on the left, a protected control on the right. -->
<div class="ws-skin-root" data-ws-skin="community.slot-fixture" data-ws-part="app">
<div id="dock" data-ws-part="voice.audio-dock">
<div id="anchor" data-ws-part="skin.voice.dock.part-anchor"
style="--skin-recovery-accent:#ffcc00;--skin-recovery-background:#102030;--skin-recovery-foreground:#ffffff;--skin-recovery-size:large"></div>
<button type="button" id="mic" data-ws-part="voice.audio-dock.microphone">Mic</button>
</div>
</div>
<pre id="result">pending</pre>
<script type="module">
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
import { bindHostSlot } from "/src/services/host-slot-placement.ts";
const output = document.getElementById("result");
const CSS = `
.cap {
position: fixed; inset: auto auto 12px 12px; margin: 0;
display: flex; gap: 4px; padding: 4px; border: 0; pointer-events: auto;
background: var(--ws-recovery-background, #fff);
color: var(--ws-recovery-foreground, #31524f);
}
.cap button { min-height: var(--ws-recovery-hit, 28px); padding: 0 8px; }
`;
try {
const layer = createHostOwnedLayer("recovery", CSS);
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();
const anchor = document.getElementById("anchor");
const mic = document.getElementById("mic");
const changes = [];
const binding = bindHostSlot({
layer,
control,
anchor: "skin.voice.dock.part-anchor",
skinId: "community.slot-fixture",
align: "start",
onModeChange: (change) => changes.push(change),
});
const snap = (name) => {
const rect = control.getBoundingClientRect();
const anchorRect = anchor.getBoundingClientRect();
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
const style = getComputedStyle(control);
return {
name,
mode: changes.at(-1)?.mode ?? "floating",
reason: changes.at(-1)?.reason,
inlineLeft: control.style.left,
insideAnchor: rect.left >= anchorRect.left - 0.5 && rect.right <= anchorRect.right + 0.5
&& rect.top >= anchorRect.top - 0.5 && rect.bottom <= anchorRect.bottom + 0.5,
atDefaultCorner: Math.abs(rect.left - 12) < 1 && Math.abs(innerHeight - 12 - rect.bottom) < 1,
hitIsLayerHost: hit === layer.host,
background: style.backgroundColor,
color: style.color,
buttonHeight: control.querySelector("button").getBoundingClientRect().height,
};
};
const results = [];
results.push(snap("initial"));
anchor.style.display = "none";
binding.revalidate();
results.push(snap("anchor-hidden"));
anchor.style.display = "";
binding.revalidate();
results.push(snap("restored-once"));
binding.revalidate();
results.push(snap("restored-twice"));
mic.style.left = "8px";
mic.style.right = "auto";
binding.revalidate();
results.push(snap("covers-mic"));
mic.style.left = "";
mic.style.right = "";
binding.revalidate();
binding.revalidate();
anchor.style.transform = "translateX(-5000px)";
binding.revalidate();
results.push(snap("anchor-offscreen"));
anchor.style.transform = "";
binding.revalidate();
binding.revalidate();
anchor.style.setProperty("--skin-recovery-foreground", "#102030");
binding.revalidate();
results.push(snap("unreadable-tokens"));
binding.dispose();
results.push({
...snap("disposed"),
leftoverAccent: control.style.getPropertyValue("--ws-recovery-accent"),
});
output.textContent = JSON.stringify({ results, changes });
} catch (error) {
output.textContent = JSON.stringify({ error: String(error && error.stack || error) });
}
</script>
</body>
</html>
+58 -1
View File
@@ -76,7 +76,8 @@ test("host chrome renders recovery and authorization in a closed-shadow top laye
assert.match(hostChrome, /addEventListener\("keydown", onKeydown, true\)/);
assert.match(hostChrome, /removeEventListener\("keydown", onKeydown, true\)/);
// Escape closes the popover from inside its closed shadow root.
assert.match(hostChrome, /@keydown\.escape="shortcutOpen = false"/);
assert.match(hostChrome, /@keydown\.escape="onRecoveryEscape"/);
assert.match(hostChrome, /function onRecoveryEscape\(\) \{\s*shortcutOpen\.value = false;/);
assert.doesNotMatch(hostChrome, /event\.defaultPrevented \|\| event\.repeat/);
assert.doesNotMatch(hostChrome, /data-ws-part="host\.recovery"/);
assert.doesNotMatch(hostChrome, /ws-host-recovery-layer/);
@@ -237,3 +238,59 @@ test("recovery stays visible and clickable under hostile compiled skins", { skip
assert.equal(result.layerOutsideSkinRoot, true, `${result.name}: recovery was rendered inside .ws-skin-root`);
}
});
test("a declared slot docks the capsule and falls back at runtime", { 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-placement.html`);
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
assert.ok(match, "the 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);
const byName = Object.fromEntries(payload.results.map((result) => [result.name, result]));
const initial = byName.initial;
assert.equal(initial.mode, "slotted", JSON.stringify(payload));
assert.equal(initial.insideAnchor, true, "the capsule is not placed over the anchor");
assert.equal(initial.hitIsLayerHost, true, "the docked capsule is not the hit-test target");
assert.equal(initial.background, "rgb(16, 32, 48)", "skin background token was not applied");
assert.equal(initial.color, "rgb(255, 255, 255)", "skin foreground token was not applied");
assert.ok(initial.buttonHeight >= 36, "the large size tier minimum was not enforced");
assert.equal(byName["anchor-hidden"].mode, "floating");
assert.equal(byName["anchor-hidden"].reason, "anchor-missing");
assert.equal(byName["anchor-hidden"].inlineLeft, "");
assert.equal(byName["anchor-hidden"].atDefaultCorner, true);
// Anti-flap: one good check after a fallback is not enough to re-dock.
assert.equal(byName["restored-once"].mode, "floating");
assert.equal(byName["restored-twice"].mode, "slotted");
assert.equal(byName["restored-twice"].insideAnchor, true);
assert.equal(byName["covers-mic"].mode, "floating");
assert.equal(byName["covers-mic"].reason, "covers-protected");
assert.equal(byName["covers-mic"].atDefaultCorner, true);
assert.equal(byName["anchor-offscreen"].mode, "floating");
// An invisible/off-screen element is never resolved as the anchor at all.
assert.equal(byName["anchor-offscreen"].reason, "anchor-missing");
assert.equal(byName["anchor-offscreen"].atDefaultCorner, true);
// Foreground equal to background: the whole colour group reverts.
assert.equal(byName["unreadable-tokens"].background, "rgb(255, 255, 255)");
assert.equal(byName["unreadable-tokens"].color, "rgb(49, 82, 79)");
assert.equal(byName.disposed.inlineLeft, "");
assert.equal(byName.disposed.atDefaultCorner, true);
assert.equal(byName.disposed.leftoverAccent, "");
});