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

+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));