From 4e8ea3081c6ee153a7d2cff4be9ea3ee44074649 Mon Sep 17 00:00:00 2001 From: OddTurtleHead <355182507+OddTurtleHead@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:22:24 +0800 Subject: [PATCH] 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. --- docs/examples/HOST-CHROME-TOOLBAR.md | 4 +- docs/examples/host-chrome-toolbar.wskin | Bin 1538 -> 1537 bytes .../host-chrome-toolbar/manifest.json | 4 +- src/shared/skin-css.test.ts | 15 ++ src/shared/skin-css.ts | 4 + web/public/host-chrome-toolbar.wskin | Bin 1538 -> 1537 bytes web/src/components/HostChrome.vue | 7 +- web/src/services/host-control-tokens.test.ts | 30 +++- web/src/services/host-control-tokens.ts | 21 ++- .../services/host-floating-placement.test.ts | 15 ++ web/src/services/host-floating-placement.ts | 17 ++- web/src/services/host-slot-placement.ts | 11 +- web/src/services/skin-pack.test.ts | 21 +++ .../fixtures/host-floating-avoid-pointer.html | 83 +++++++++++ web/test/fixtures/host-recovery-toolbar.html | 39 +++++- .../fixtures/host-slot-observer-loop.html | 132 ++++++++++++++++++ web/test/host-chrome-recovery.test.mjs | 73 ++++++++++ 17 files changed, 453 insertions(+), 23 deletions(-) create mode 100644 web/test/fixtures/host-floating-avoid-pointer.html create mode 100644 web/test/fixtures/host-slot-observer-loop.html diff --git a/docs/examples/HOST-CHROME-TOOLBAR.md b/docs/examples/HOST-CHROME-TOOLBAR.md index 5e080c4..4a577dd 100644 --- a/docs/examples/HOST-CHROME-TOOLBAR.md +++ b/docs/examples/HOST-CHROME-TOOLBAR.md @@ -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 diff --git a/docs/examples/host-chrome-toolbar.wskin b/docs/examples/host-chrome-toolbar.wskin index 2713053979485be236e340bf3f4a7cd1dbecb217..78d54c41634538b6068b12156a85c9fa67d9efc9 100644 GIT binary patch delta 335 zcmV-V0kHmp41o-PP)h>@6aWAK2mm02Z(YLb$Y=Wi005Q&000dD003=aZfRy^b963h zb8l`Hq^sNK`PVIjd*xVn=ZbIwAg@Bv+vFVm&|m`Ms|V zfKfkUaIct@gv}lFHx-S}Pws?=C1SyhMC48+QA^ zo-fk@)hCMia`}mvf}5ebfa(JB=rRoACx!j&RLOU4rW4};&5L~2HldgD-~!}@6^OHx zO@vsIff3y(fXS|c$T=-ls$REVb%obRT2`&I?^-@;qd>fi@jrI6wY}}l=6mx4vnK&7 h1O>wC$Y=YLR|QZ3CX=WII04R+;RPE8K?MK+001wNnvnni delta 336 zcmV-W0k8gn41x@QP)h>@6aWAK2mm02Z(WrlU?%(k005Q&000dD003=aZfRy^b963h zb8l`~=-nIS-Nw_=d-qh;D@L*KB1>oM8Y5ILv0SQT~aRabbeq;^#&`>xAJbrp#BG5*(XwzjpmX7j!I0kb9n iD+C3VB48%`lU4;#0Vk8E1vmlEli&p#20{e@0002IwwBod diff --git a/docs/examples/host-chrome-toolbar/manifest.json b/docs/examples/host-chrome-toolbar/manifest.json index 53a37cf..160bdfa 100644 --- a/docs/examples/host-chrome-toolbar/manifest.json +++ b/docs/examples/host-chrome-toolbar/manifest.json @@ -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" } diff --git a/src/shared/skin-css.test.ts b/src/shared/skin-css.test.ts index a859869..4d386e6 100644 --- a/src/shared/skin-css.test.ts +++ b/src/shared/skin-css.test.ts @@ -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", diff --git a/src/shared/skin-css.ts b/src/shared/skin-css.ts index 31ec797..4b1dc03 100644 --- a/src/shared/skin-css.ts +++ b/src/shared/skin-css.ts @@ -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, "")); } diff --git a/web/public/host-chrome-toolbar.wskin b/web/public/host-chrome-toolbar.wskin index 2713053979485be236e340bf3f4a7cd1dbecb217..78d54c41634538b6068b12156a85c9fa67d9efc9 100644 GIT binary patch delta 335 zcmV-V0kHmp41o-PP)h>@6aWAK2mm02Z(YLb$Y=Wi005Q&000dD003=aZfRy^b963h zb8l`Hq^sNK`PVIjd*xVn=ZbIwAg@Bv+vFVm&|m`Ms|V zfKfkUaIct@gv}lFHx-S}Pws?=C1SyhMC48+QA^ zo-fk@)hCMia`}mvf}5ebfa(JB=rRoACx!j&RLOU4rW4};&5L~2HldgD-~!}@6^OHx zO@vsIff3y(fXS|c$T=-ls$REVb%obRT2`&I?^-@;qd>fi@jrI6wY}}l=6mx4vnK&7 h1O>wC$Y=YLR|QZ3CX=WII04R+;RPE8K?MK+001wNnvnni delta 336 zcmV-W0k8gn41x@QP)h>@6aWAK2mm02Z(WrlU?%(k005Q&000dD003=aZfRy^b963h zb8l`~=-nIS-Nw_=d-qh;D@L*KB1>oM8Y5ILv0SQT~aRabbeq;^#&`>xAJbrp#BG5*(XwzjpmX7j!I0kb9n iD+C3VB48%`lU4;#0Vk8E1vmlEli&p#20{e@0002IwwBod diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue index 7fab748..ec165c0 100644 --- a/web/src/components/HostChrome.vue +++ b/web/src/components/HostChrome.vue @@ -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; } diff --git a/web/src/services/host-control-tokens.test.ts b/web/src/services/host-control-tokens.test.ts index 3636ba0..a516c17 100644 --- a/web/src/services/host-control-tokens.test.ts +++ b/web/src/services/host-control-tokens.test.ts @@ -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", diff --git a/web/src/services/host-control-tokens.ts b/web/src/services/host-control-tokens.ts index b25db2b..97153e0 100644 --- a/web/src/services/host-control-tokens.ts +++ b/web/src/services/host-control-tokens.ts @@ -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)), }; } diff --git a/web/src/services/host-floating-placement.test.ts b/web/src/services/host-floating-placement.test.ts index 3761ba9..2b51189 100644 --- a/web/src/services/host-floating-placement.test.ts +++ b/web/src/services/host-floating-placement.test.ts @@ -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 }); diff --git a/web/src/services/host-floating-placement.ts b/web/src/services/host-floating-placement.ts index 746c99e..e5ed753 100644 --- a/web/src/services/host-floating-placement.ts +++ b/web/src/services/host-floating-placement.ts @@ -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) { diff --git a/web/src/services/host-slot-placement.ts b/web/src/services/host-slot-placement.ts index 9bec6c2..b57d845 100644 --- a/web/src/services/host-slot-placement.ts +++ b/web/src/services/host-slot-placement.ts @@ -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" }); } diff --git a/web/src/services/skin-pack.test.ts b/web/src/services/skin-pack.test.ts index d602cb4..ada4151 100644 --- a/web/src/services/skin-pack.test.ts +++ b/web/src/services/skin-pack.test.ts @@ -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)); diff --git a/web/test/fixtures/host-floating-avoid-pointer.html b/web/test/fixtures/host-floating-avoid-pointer.html new file mode 100644 index 0000000..9ef1281 --- /dev/null +++ b/web/test/fixtures/host-floating-avoid-pointer.html @@ -0,0 +1,83 @@ + + + + + +Host floating placement: docked toolbar and pointer avoidance + + + +
pending
+ + + diff --git a/web/test/fixtures/host-recovery-toolbar.html b/web/test/fixtures/host-recovery-toolbar.html index 3456c62..ee2ea23 100644 --- a/web/test/fixtures/host-recovery-toolbar.html +++ b/web/test/fixtures/host-recovery-toolbar.html @@ -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; } @@ -34,6 +35,7 @@ +
Blank area
pending
@@ -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) { diff --git a/web/test/fixtures/host-slot-observer-loop.html b/web/test/fixtures/host-slot-observer-loop.html new file mode 100644 index 0000000..56db68d --- /dev/null +++ b/web/test/fixtures/host-slot-observer-loop.html @@ -0,0 +1,132 @@ + + + + + +Host slot observer scheduling fixture + + + +
+
+
+
pending
+ + + diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs index d65b1a8..08cb323 100644 --- a/web/test/host-chrome-recovery.test.mjs +++ b/web/test/host-chrome-recovery.test.mjs @@ -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(/
]*>([\s\S]*?)<\/pre>/);
+  assert.ok(match, "the observer fixture did not emit a result block");
+  const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/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(/
]*>([\s\S]*?)<\/pre>/);
+  assert.ok(match, "the floating avoidance fixture did not emit a result block");
+  const payload = JSON.parse(match[1].replace(/"/g, '"').replace(/&/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);