diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 92c7d16..c3af6a9 100644 --- a/docs/SKIN_DEVELOPMENT.md +++ b/docs/SKIN_DEVELOPMENT.md @@ -492,7 +492,7 @@ Wasm 每轮最多读取一次输入并提交一个 UI 输出;首版宿主动 **这不是编译期限制。** `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 节奏。窗口缩放、滚动和锚点/胶囊尺寸变化都会触发复查。 -**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s 不动;默认角落重新空出来(且当前位置也不遮挡、鼠标不在那里)时,会按同样的节奏回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件;进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,让胶囊尽快换到新页面合适的位置(通常就是重新空出来的默认角落)。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。 +**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s(期间若默认角落盖住了控件,最多再挪开一次,之后保持不动);判断某个控件是否被盖住时会“看穿”短暂出现的提示条(`app.toast`)和另一个宿主浮动控件,提示条暂时挡住的控件仍按存在计算,不会因此把那个角落误判为空闲;默认角落重新空出来(且当前位置也不遮挡、鼠标不在那里)时,会按同样的节奏回到默认角落,免得为上一屏选的位置盖住下一屏新出现的控件;进入或离开语音页、切换皮肤时,宿主会在约 1.5 s 内跳过确认等待和最短间隔、连续复查几次,让胶囊尽快换到新页面合适的位置(通常就是重新空出来的默认角落)。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。 **样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。 diff --git a/web/src/services/host-floating-placement.test.ts b/web/src/services/host-floating-placement.test.ts index 2d8f004..e3bb944 100644 --- a/web/src/services/host-floating-placement.test.ts +++ b/web/src/services/host-floating-placement.test.ts @@ -9,6 +9,7 @@ import { floatingRect, shouldFold, floatingScore, + reachableThrough, type FloatingObstacle, } from "./host-floating-placement.js"; import type { HostPartRect } from "./host-chrome-visibility.js"; @@ -142,3 +143,38 @@ test("with every spot taken, the capsule covers a dialog button before a protect const footprint = floatingRect(choice.position, wide, mobile, margins); assert.equal(floatingScore(footprint, [obstacles[0]]), 0, choice.position); }); + +test("a toast or the other host control passing over a control does not hide it from the obstacle check", () => { + // Stand-ins for elementsFromPoint() results, topmost first. + const button = { id: "accompaniment" } as unknown as Element; + const icon = { id: "accompaniment-icon" } as unknown as Element; + const toast = { id: "toast" } as unknown as Element; + const toastText = { id: "toast-text" } as unknown as Element; + const otherHost = { id: "library-launcher" } as unknown as Element; + const skinLayer = { id: "skin-panel" } as unknown as Element; + const backdrop = { id: "modal-backdrop" } as unknown as Element; + const isTarget = (element: Element) => element === button || element === icon; + const isTransparent = (element: Element) => element === toast || element === toastText || element === otherHost; + assert.equal(reachableThrough([icon, button], isTarget, isTransparent), true); + // The toast is on top for a moment: the control under it still counts. + assert.equal(reachableThrough([toastText, toast, icon, button], isTarget, isTransparent), true); + assert.equal(reachableThrough([otherHost, toast, button], isTarget, isTransparent), true); + // A skin layer or modal backdrop really hides it (even under a toast). + assert.equal(reachableThrough([skinLayer, button], isTarget, isTransparent), false); + assert.equal(reachableThrough([toast, backdrop, button], isTarget, isTransparent), false); + assert.equal(reachableThrough([toast], isTarget, isTransparent), false); + assert.equal(reachableThrough([], isTarget, isTransparent), false); +}); + +test("a corner whose control is counted (not hidden by a toast) is never chosen as the free default corner", () => { + // Library launcher: default bottom-right, parked top-left because the skin's + // accompaniment button sits in the bottom-right corner. + const launcher = { width: 34, height: 34 }; + const launcherMargins = { top: 16, right: 16, bottom: 16, left: 16 }; + const accompaniment = { rect: rect(1218, 738, 34, 34), weight: FLOATING_WEIGHT_PROTECTED }; + const counted = chooseFloatingPosition({ current: "top-left", size: launcher, viewport, margins: launcherMargins, obstacles: [accompaniment], home: "bottom-right" }); + assert.equal(counted.position, "top-left"); + // What 854a488 did while a toast hid the button: the corner looked free. + const hidden = chooseFloatingPosition({ current: "top-left", size: launcher, viewport, margins: launcherMargins, obstacles: [], home: "bottom-right" }); + assert.equal(hidden.position, "bottom-right"); +}); diff --git a/web/src/services/host-floating-placement.ts b/web/src/services/host-floating-placement.ts index 7541b1c..16c436f 100644 --- a/web/src/services/host-floating-placement.ts +++ b/web/src/services/host-floating-placement.ts @@ -17,7 +17,9 @@ * least one control). The host control stays in the viewport and stays * clickable in every position; only its corner changes. It does not move while * hovered or focused, and never moves onto the last pointer position or the - * focused control. + * focused control. A control briefly hidden by a toast (or by the other host + * floating control) still counts, so a passing toast never makes its corner + * look free. */ import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js"; @@ -81,7 +83,8 @@ export const FLOATING_FOLD_MIN_GAIN = 0.25; * Anti-flap: a move needs the collision to persist for `MOVE_CONFIRM_MS`, moves * are at least `MOVE_MIN_INTERVAL_MS` apart, and more than `FLAP_MAX_MOVES` * moves within `FLAP_WINDOW_MS` (an animated or hostile skin) park the control - * at its default corner for `FLAP_FREEZE_MS`, so it is never a moving target. + * at its default corner for `FLAP_FREEZE_MS`, so it is never a moving target + * (one escape per freeze is allowed when that corner covers a control). */ export const HOST_FLOATING_MOVE_CONFIRM_MS = 250; export const HOST_FLOATING_MOVE_MIN_INTERVAL_MS = 1000; @@ -230,9 +233,35 @@ const INTERACTIVE_SELECTOR = "a[href],button,input:not([type='hidden']),select,t + "[role='button'],[role='tab'],[role='menuitem'],[role='link'],[role='option'],[role='switch'],[role='checkbox'],[role='radio']," + "[contenteditable='true'],[tabindex]:not([tabindex='-1'])"; const DIALOG_SELECTOR = "dialog[open],[role='dialog'],[role='alertdialog'],[aria-modal='true']"; +/** + * Transient layers that float over the skin for a moment (the app toast). A + * control under one is still there a second later, so it keeps counting as an + * obstacle: otherwise a toast passing over a corner makes that corner look + * free and the host control jumps onto the control the toast was covering. + */ +const TRANSIENT_OVERLAY_SELECTOR = "[data-ws-part='app.toast']"; /** Live host floating controls, so they also avoid each other. */ -const registry = new Set<{ owner: Element; rect: () => HostPartRect | null }>(); +const registry = new Set<{ owner: Element; isSelf: (element: Element) => boolean; rect: () => HostPartRect | null }>(); + +/** + * Whether a control is the topmost thing at a point once see-through layers + * are skipped. `stack` is `elementsFromPoint` (topmost first); `isTarget` is + * the control (or the floating control being placed, which is the collision + * we want to resolve); `isTransparent` marks transient overlays and the other + * host floating controls, which do not hide a control from this check. + */ +export function reachableThrough( + stack: readonly Element[], + isTarget: (element: Element) => boolean, + isTransparent: (element: Element) => boolean, +): boolean { + for (const element of stack) { + if (isTarget(element)) return true; + if (!isTransparent(element)) return false; + } + return false; +} function toRect(rect: DOMRect | HostPartRect): HostPartRect { return { left: rect.left, top: rect.top, width: rect.width, height: rect.height, right: rect.right, bottom: rect.bottom }; @@ -260,7 +289,15 @@ export function collectFloatingObstacles(options: { const obstacles: FloatingObstacle[] = []; const viewportWidth = view.innerWidth; const viewportHeight = view.innerHeight; - const others = [...registry].filter(entry => entry.owner !== owner).map(entry => entry.owner); + const otherEntries = [...registry].filter(entry => entry.owner !== owner); + const others = otherEntries.map(entry => entry.owner); + const transparent = (element: Element) => element.closest(TRANSIENT_OVERLAY_SELECTOR) !== null + || otherEntries.some(entry => entry.isSelf(element)); + const stackAt = (x: number, y: number): Element[] => { + if (typeof doc.elementsFromPoint === "function") return doc.elementsFromPoint(x, y); + const hit = doc.elementFromPoint(x, y); + return hit ? [hit] : []; + }; for (const element of doc.querySelectorAll(INTERACTIVE_SELECTOR)) { if (isSelf(element)) continue; // Another host floating control is added once below, with its own weight. @@ -278,8 +315,10 @@ export function collectFloatingObstacles(options: { // user types, and the host control must not sit on it either way. const x = Math.min(Math.max(rect.left + rect.width / 2, 0), viewportWidth - 1); const y = Math.min(Math.max(rect.top + rect.height / 2, 0), viewportHeight - 1); - const hit = doc.elementFromPoint(x, y); - if (!hit || !(hit === element || element.contains(hit) || isSelf(hit))) continue; + // Look through toasts and the other host floating control: what they hide + // now is back in a moment. A modal backdrop or a skin layer still hides it. + const isTarget = (hit: Element) => hit === element || element.contains(hit) || isSelf(hit); + if (!reachableThrough(stackAt(x, y), isTarget, transparent)) continue; const part = element.closest("[data-ws-part]")?.getAttribute("data-ws-part") ?? ""; const protectedPart = PROTECTED_PART_IDS.has(part) && !CONTAINER_PARTS.has(part); const weight = protectedPart @@ -346,6 +385,7 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati let pendingSince = 0; let lastMoveAt = Number.NEGATIVE_INFINITY; let frozenUntil = 0; + let frozenEscaped = false; let moveTimes: number[] = []; let confirmTimer: ReturnType | undefined; let urgentUntil = 0; @@ -364,6 +404,7 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati refreshMargins(); const entry = { owner: element as Element, + isSelf, rect: () => { const rect = element.getBoundingClientRect(); return rect.width > 0 && rect.height > 0 ? toRect(rect) : null; @@ -426,7 +467,15 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati return; } const now = Date.now(); - if (now < frozenUntil) return; + const frozen = now < frozenUntil; + if (frozen) { + // Frozen at the default corner: hold still, except one escape per + // freeze when the parked spot covers a control and the move frees some + // of it (e.g. a toast hid that control when the control was parked). + const parked = floatingRect(position, compact && small ? small : size, viewport, margins); + const parkedScore = floatingScore(parked, obstacles); + if (frozenEscaped || !(parkedScore > 0 && next.score < parkedScore - 1e-6)) return; + } const urgent = now < urgentUntil; if (!urgent && !pendingSince) { pendingSince = now; @@ -443,12 +492,23 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati } pendingSince = 0; lastMoveAt = now; + if (frozen) { + // The escape does not count as flapping, and is the only one until the freeze ends. + frozenEscaped = true; + if (next.position !== position) { + position = next.position; + apply(position); + } + setCompact(nextCompact); + return; + } moveTimes = moveTimes.filter(time => now - time < HOST_FLOATING_FLAP_WINDOW_MS); moveTimes.push(now); if (moveTimes.length > HOST_FLOATING_FLAP_MAX_MOVES) { // Flapping: park at the default corner, expanded, and hold still. moveTimes = []; frozenUntil = now + HOST_FLOATING_FLAP_FREEZE_MS; + frozenEscaped = false; if (position !== defaultPosition) { position = defaultPosition; apply(position); diff --git a/web/test/fixtures/host-floating-transient.html b/web/test/fixtures/host-floating-transient.html new file mode 100644 index 0000000..462cadd --- /dev/null +++ b/web/test/fixtures/host-floating-transient.html @@ -0,0 +1,136 @@ + + + + + +Host floating placement: transient overlays and the flap freeze + + + +
+
+
+
pending
+ + + diff --git a/web/test/host-chrome-recovery.test.mjs b/web/test/host-chrome-recovery.test.mjs index 228c927..554eefc 100644 --- a/web/test/host-chrome-recovery.test.mjs +++ b/web/test/host-chrome-recovery.test.mjs @@ -375,6 +375,46 @@ test("floating host controls move off skin controls at runtime", { skip: !CHROME assert.equal(byName.disposed.compact, false); }); +test("floating host controls see through toasts and still step off a control while frozen", { 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-transient.html`, ["--virtual-time-budget=60000", "--window-size=1280,800"]); + const match = dom.match(/
]*>([\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]));
+  t.diagnostic(JSON.stringify(payload.results));
+
+  // open-voice-surface desktop: toasts passing over "Share accompaniment" no
+  // longer make the default bottom-right corner look free.
+  const toast = byName["toast-transient"];
+  assert.notEqual(toast.settled, "bottom-right", JSON.stringify(toast));
+  assert.ok(!toast.positions.includes("bottom-right"), JSON.stringify(toast));
+  assert.equal(toast.coveredSamples, 0, JSON.stringify(toast));
+  assert.equal(toast.finalCovered, false, JSON.stringify(toast));
+
+  // Parked at the default corner by the flap freeze on top of a control: one
+  // escape about 1 s after the freeze (inside the 3 s pin), then still for the rest of it.
+  const freeze = byName["freeze-escape"];
+  assert.equal(freeze.flapMoves, 6, JSON.stringify(freeze));
+  assert.equal(freeze.parkedPosition, "bottom-right", JSON.stringify(freeze));
+  assert.equal(freeze.escapes.length, 1, JSON.stringify(freeze));
+  assert.notEqual(freeze.escapes[0].position, "bottom-right", JSON.stringify(freeze));
+  assert.ok(freeze.escapes[0].afterPinMs < 3000, JSON.stringify(freeze));
+  assert.equal(freeze.movesWhileHeld, 0, JSON.stringify(freeze));
+});
+
 test("host control tokens follow late skin CSS, resolve modern colours and refuse skin fonts", { skip: !CHROME && "google-chrome is not installed" }, async (t) => {
   const server = await createServer({
     root: webRoot,