mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
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:
1 parent
aefa0bc163
commit
93d221c3ef
10 files changed
+404
-42
No files matched your search
@@ -473,7 +473,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
```json
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "end", "compact": true }
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
```
|
||||
|
||||
@@ -490,13 +490,13 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
- v3 组件中带 `part` 的节点:`skin.<page>.<componentId>.part-<part>`;按钮、链接、输入、`role="button"` 或绑定了用户事件的可交互节点会渲染为 `skin.<page>.<componentId>.control-part-<part>`。推荐在 surface 里放一个专门的非交互空节点并设置稳定的 `part`(例如 `skin.voice.harbor-dock.part-anchor`),避免名称随交互语义变化。
|
||||
- v4 运行时插件生成的节点:`skin.<page>.runtime_plugin_<pluginId>__<componentId>.part-<part>`(同样有 `control-` 变体)。插件 UI 与 `data-ws-skin-mount` 挂载点都位于 `.ws-skin-root` 内,因此也能作为锚点。
|
||||
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
**这不是编译期限制。** `skin.css` 校验器不会因为是否声明 `slots` 而改变,也不会生成额外的隐藏或定位规则;停靠完全由宿主运行时完成。胶囊位于顶层,会挡住它下面的一切,因此宿主还会检查胶囊的占位(按观察到的最大尺寸计算,紧凑模式展开后的宽度也算在内)是否压到了可见的受保护控件(`PROTECTED_PART_IDS`,例如 `voice.audio-dock.microphone`、`voice.audio-dock.output`、`home.footer.clear`、`voice.connection-status.reconnect`);锚点的祖先容器(如包住专用锚点的 `voice.audio-dock`)不算,锚点自身只有在它是或包含可交互控件时才算。压到时同样回退。示例 `host-chrome-demo` 因此把胶囊靠 `start` 对齐在音频栏左侧的说明文字上,避开右侧的麦克风/输出按钮。锚点一旦不可用,胶囊立即回到默认左下角(仍在闭合 Shadow DOM 和顶层,皮肤无法遮挡或隐藏)。为避免闪烁,回退后需要连续 2 次检查都通过才会重新停靠;停靠期间约每 400 ms 复查一次,浮动态保持原来的 1 s 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。
|
||||
|
||||
**样式令牌**:皮肤可在锚点或它的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。只有颜色对比度不达标时整组颜色才回退到宿主默认值。
|
||||
**样式令牌**:皮肤可在锚点或它的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。令牌只对声明了 `slots` 的皮肤生效(没有插槽的皮肤里写了也不会读取,胶囊保持默认外观)。锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
|
||||
|
||||
| 令牌 | 规则 |
|
||||
| --- | --- |
|
||||
| `--skin-recovery-accent` | 强调色,用于「使用内置皮肤」按钮的边框/重点。与背景的对比度必须 ≥ 3,否则整组颜色回退。 |
|
||||
| `--skin-recovery-accent` | 强调色,用于紧凑模式焦点框和「使用内置皮肤」按钮的边框。与背景的对比度必须 ≥ 3,否则整组颜色回退。该按钮自身固定为浅色底 `#fff7ed`,如果强调色在这块浅底上对比度不足 3,只有这个按钮的边框改用宿主默认 `#b45309`,其余位置仍用皮肤强调色。 |
|
||||
| `--skin-recovery-background` | 胶囊背景。宿主强制不透明(alpha 视为 1)。 |
|
||||
| `--skin-recovery-foreground` | 文字色。与背景的对比度必须 ≥ 4.5。 |
|
||||
| `--skin-recovery-radius` | 圆角,只接受 px 长度并限制在 0–999;其他值使用宿主默认 999px。 |
|
||||
@@ -505,9 +505,9 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动
|
||||
|
||||
颜色建议使用 `#rgb`、`#rrggbb`、`rgb()` 或 `rgba()`;宿主通过影子根内的探针元素让浏览器解析颜色,再按 WCAG 相对亮度检查对比度。无效、缺失或无法解析的值使用宿主默认颜色(强调色 `#b45309`、背景 `#ffffff`、文字 `#31524f`)。
|
||||
|
||||
**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停或键盘聚焦时展开为完整按钮。新皮肤激活后的约 5 秒内始终显示完整胶囊,避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。
|
||||
**紧凑模式**:`compact: true` 且成功停靠时,胶囊只显示 ◈ 标记;标记本身达到当前尺寸档位的最小命中区域,区域保留可访问名称,鼠标悬停、键盘聚焦或点按/轻触 ◈ 时展开为完整按钮;点按展开会保持到焦点离开胶囊、在胶囊外按下指针或按 Escape。新皮肤激活后、胶囊首次成功停靠起的约 5 秒内始终显示完整胶囊(从停靠时刻开始计时,皮肤加载慢也不会提前收起),避免用户找不到恢复入口;用快捷键召唤时也始终完整显示。展开/收起不使用动画,`prefers-reduced-motion` 下同样没有过渡。
|
||||
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
**键盘快捷键**:`Ctrl+Alt+Shift+R`(macOS 为 `⌘+⌥+⇧+R`)在停靠、浮动态和紧凑模式下行为一致:显示完整胶囊并聚焦第一个按钮,焦点离开胶囊后紧凑模式重新生效;它仍在捕获阶段处理,皮肤或插件的 `preventDefault()` 无法吞掉。
|
||||
|
||||
`host.watermark`、`host.hint` 与 `host.voice-status-decoration` 属于默认隐藏的装饰:官方/内置皮肤(Day、Night、ILLUSIA、KAAK)不会渲染它们,外观与生产版一致。主题化宿主外壳的皮肤需在 `chrome.json` 中用 `visibleParts` 明确开启;`chrome.json` 的 `hiddenParts` 仍然优先。
|
||||
|
||||
@@ -551,7 +551,7 @@ v3/v4 清单可增加可选字段 `"chrome": "chrome.json"`,文件位于包根
|
||||
"host.plugins.launcher": "assets/icons/apps.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "end", "compact": true }
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Binary file not shown.
@@ -10,6 +10,6 @@
|
||||
"voice.performance": "assets/icons/status.png"
|
||||
},
|
||||
"slots": {
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "end", "compact": true }
|
||||
"host.recovery": { "anchor": "voice.audio-dock", "align": "start", "compact": true }
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -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>
|
||||
|
||||
@@ -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)");
|
||||
});
|
||||
@@ -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
@@ -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>
|
||||
@@ -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(/"/g, '"').replace(/&/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, "");
|
||||
});
|
||||
Reference in new issue
Block a user