fix: harden floating host-control avoidance after review

Independent review of 16e25ea (DeepSeek v4.1 Flash, Qwen4 Max) found the
runtime avoidance could flap, park on protected controls and drift from the
CSS on notched phones. Runtime only; still no skin.css restriction.

- Anti-flap: a move needs the collision to persist ~250 ms, moves are at least
  1 s apart, and more than 6 moves in 10 s park the control at its default
  corner for 10 s (an animated/hostile skin can no longer keep it moving).
- Protected parts now outweigh dialogs and the other host control; ordinary
  buttons inside the protected `app` root (or `home.footer`) are no longer
  weighted as protected.
- Never move onto the last pointer position or the focused control.
- Fold to the compact mark only when that frees at least one control (a
  full-screen click-away layer no longer hides the recovery buttons).
- Score with the live expanded size (language switch) and reset on resize;
  model margins include env(safe-area-inset-*) like the CSS.
- Skip invisible (opacity 0) controls; also count [tabindex], option/switch/
  checkbox/radio roles, iframes and media controls; count the other host
  control once; prefilter by candidate rects (cheap on 3 000-control skins);
  re-check after scrolls; ignore sticky :hover on touch; bind idempotently.
- Tests: weights, fold threshold, pointer, safe area, protected-vs-dialog,
  stability over repeated ticks, two host controls, anti-flap.
This commit is contained in:
OddTurtleHead committed 2026-11-15 21:38:39 +08:00
1 parent e46d7a0eb7
commit 2b019d82ff
7 files changed
+391 -42

No files matched your search

+1 -1
View File
@@ -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)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框等;禁用的“发送”按钮也算,受保护部件和打开的对话框/底部弹层里的控件权重更高)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置;处处都会遮挡时,收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停或焦点在胶囊内时不会移动。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
**浮动位置的运行时避让。** 没有停靠(未声明 `slots`,或锚点回退)时,恢复胶囊默认在左下角;宿主约每 400 ms(以及每次点击后约 150 ms)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框、`[tabindex]` 自定义按钮、iframe 等;禁用的“发送”按钮也算,透明度为 0 的不算;受保护部件权重最高,其次是打开的对话框/底部弹层里的控件;只因位于皮肤根 `app` 之内的普通按钮不算受保护)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置,但不会换到鼠标最后所在的位置或当前聚焦的控件上;只有收起能至少让出一个控件时,才收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停(触屏上不算残留的悬停)或焦点在胶囊内时不会移动。为避免闪动:遮挡要持续约 250 ms 才移动,两次移动至少相隔 1 s,10 s 内移动超过 6 次就停在默认角落 10 s 不动;当前位置不遮挡时不会为了“回到默认角落”而移动。位置计算和 CSS 一样计入 `env(safe-area-inset-*)`(刘海屏、底部手势条)。宿主自带的应用库悬浮按钮(皮肤没有提供 `voice.plugin-launcher` 挂载点时出现在右下角)使用同一套避让,两者也互相避开。这同样只是运行时行为,不新增任何 `skin.css` 编译期限制;皮肤作者无需为它做任何事,但如果希望胶囊固定在设计好的位置,仍建议用 `slots` 停靠。
**样式令牌**:皮肤可在皮肤根(`:root`)、锚点或锚点的祖先上设置下列普通 `--skin-*` 变量;宿主从锚点(存在时)或活动皮肤根的计算样式读取、校验,再写入闭合 Shadow DOM 内部的宿主变量。没有声明 `slots` 的皮肤也能用这些令牌给浮动态胶囊换肤;锚点仍在 DOM 中时,停靠态和浮动态都会继续使用这些令牌;锚点被移除或隐藏时,宿主读取皮肤根上可继承的值,否则使用默认值。每个 `--skin-recovery-*` 都有全局回退 `--skin-host-<同名>`,`--skin-recovery-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。
+20 -3
View File
@@ -251,6 +251,9 @@ const compactPinned = ref(false);
const floatPosition = ref<FloatingPosition>("bottom-left");
const floatCompact = ref(false);
let floatingAvoidance: FloatingAvoidance | undefined;
let floatingElement: HTMLElement | null = null;
/** Sticky `:hover` after a tap on touch screens must not pause avoidance. */
const canHover = () => typeof matchMedia === "function" && matchMedia("(hover: hover)").matches;
const compact = computed(() => !shortcutExpanded.value
&& !compactPinned.value
@@ -301,15 +304,26 @@ function syncSlotBinding() {
}
function bindFloating() {
const control = recoveryPopover.value;
// Idempotent: called on mount and whenever the popover element appears.
if (floatingAvoidance && floatingElement === control) return;
floatingAvoidance?.dispose();
floatingAvoidance = undefined;
const control = recoveryPopover.value;
floatingElement = null;
if (!control || !layer) return;
const host = layer.host;
floatingElement = control;
floatingAvoidance = bindFloatingAvoidance({
element: control,
isSelf: node => node === host || host.contains(node),
margins: { top: 12, right: 12, bottom: 38, left: 12 },
// Same numbers as RECOVERY_LAYER_CSS, including env(safe-area-inset-*).
margins: insets => ({
top: Math.max(12, insets.top),
right: Math.max(12, insets.right),
bottom: 38 + insets.bottom,
left: Math.max(12, insets.left),
}),
insetsParent: layer.shadow,
defaultPosition: "bottom-left",
apply: next => { floatPosition.value = next; },
compactSize: () => {
@@ -322,7 +336,7 @@ function bindFloating() {
paused: () => slotMode.value === "slotted"
|| shortcutExpanded.value
|| compactPinned.value
|| control.matches(":hover")
|| (canHover() && control.matches(":hover"))
|| Boolean(layer.shadow.activeElement),
});
}
@@ -366,6 +380,7 @@ watch([recoveryVisible, recoveryPopover], () => {
void nextTick(() => {
syncPopover();
slotBinding?.revalidate();
bindFloating();
floatingAvoidance?.revalidate();
});
}, { flush: "post" });
@@ -397,6 +412,8 @@ onBeforeUnmount(() => {
if (compactHoldTimer) clearTimeout(compactHoldTimer);
slotBinding?.dispose();
floatingAvoidance?.dispose();
floatingAvoidance = undefined;
floatingElement = null;
recoveryTheme?.dispose();
window.removeEventListener("resize", refreshLauncherReachability);
window.removeEventListener("keydown", onKeydown, true);
+6 -2
View File
@@ -240,10 +240,14 @@ watch([toolbar, () => props.toolbarTarget], ([element, target]) => {
fallbackAvoidance = bindFloatingAvoidance({
element,
isSelf: node => element.contains(node),
margins: { top: 16, right: 16, bottom: 16, left: 16 },
// Same numbers as .ws-plugin-toolbar-fallback in plugin-overlay.css.
margins: insets => ({ top: 16 + insets.top, right: 16, bottom: 16 + insets.bottom, left: 16 }),
defaultPosition: 'bottom-right',
apply: next => { fallbackPosition.value = next; },
paused: () => drawerOpen.value || element.matches(':hover') || element.contains(document.activeElement),
// Sticky :hover after a tap on touch screens must not pause avoidance.
paused: () => drawerOpen.value
|| (matchMedia('(hover: hover)').matches && element.matches(':hover'))
|| element.contains(document.activeElement),
});
}, { flush: 'post' });
onBeforeUnmount(() => { fallbackAvoidance?.dispose(); fallbackAvoidance = undefined; });
@@ -4,8 +4,10 @@ import {
FLOATING_WEIGHT_CONTROL,
FLOATING_WEIGHT_DIALOG,
FLOATING_WEIGHT_PROTECTED,
FLOATING_WEIGHT_POINTER,
chooseFloatingPosition,
floatingRect,
shouldFold,
floatingScore,
type FloatingObstacle,
} from "./host-floating-placement.js";
@@ -30,14 +32,14 @@ test("floating rects follow the corner margins and stay inside the viewport", ()
assert.ok(narrow.bottom <= 844);
});
test("score is zero without overlap, ignores 1px brushes and weights protected/dialog controls", () => {
test("score is zero without overlap, ignores 1px brushes and weights dialog and (above all) protected controls", () => {
const footprint = rect(12, 724, 200, 38);
assert.equal(floatingScore(footprint, [{ rect: rect(400, 400, 40, 40), weight: 1 }]), 0);
assert.equal(floatingScore(footprint, [{ rect: rect(211, 724, 40, 38), weight: 1 }]), 0);
const control = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_CONTROL }]);
const protectedPart = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_PROTECTED }]);
const dialog = floatingScore(footprint, [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_DIALOG }]);
assert.ok(control > 0 && protectedPart > control && dialog > protectedPart);
assert.ok(control > 0 && dialog > control && protectedPart > dialog);
});
test("the default corner is kept while it is free", () => {
@@ -78,3 +80,52 @@ test("ties keep the current position (no flapping between equal corners)", () =>
const choice = chooseFloatingPosition({ current: "top-right", size: capsule, viewport, margins, obstacles });
assert.equal(choice.position, "top-right");
});
test("a move never lands on the pointer or the focused control, but the current spot is not pushed by them", () => {
// Default corner covers the microphone; top-left would be free but the
// pointer rests there, so the capsule takes another free spot.
const obstacles: FloatingObstacle[] = [{ rect: rect(150, 730, 34, 34), weight: FLOATING_WEIGHT_PROTECTED }];
const pointer: FloatingObstacle = { rect: rect(84, 15, 32, 32), weight: FLOATING_WEIGHT_POINTER };
const choice = chooseFloatingPosition({ current: "bottom-left", size: capsule, viewport, margins, obstacles, moveObstacles: [pointer] });
assert.notEqual(choice.position, "top-left");
assert.equal(choice.score, 0);
// A pointer next to (or on) a collision-free capsule never makes it move.
const stay = chooseFloatingPosition({ current: "top-left", size: capsule, viewport, margins, obstacles: [], moveObstacles: [pointer] });
assert.equal(stay.position, "top-left");
});
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 });
const reduced = chooseFloatingPosition({ current: full.position, size: { width: 38, height: 38 }, viewport, margins, obstacles: backdrop });
assert.ok(full.score > 0 && reduced.score < full.score);
assert.equal(shouldFold(full, reduced), false);
// Freeing a real control (score drops by at least 0.25 × weight) folds.
assert.equal(shouldFold({ position: "bottom-left", score: 1.25 }, { position: "bottom-left", score: 0 }), true);
assert.equal(shouldFold({ position: "bottom-left", score: 0.35 }, { position: "bottom-left", score: 0 }), true);
assert.equal(shouldFold({ position: "bottom-left", score: 0 }, { position: "bottom-left", score: 0 }), false);
});
test("safe-area margins shift the modelled rect exactly like the CSS env() offsets", () => {
const insets = { top: 47, right: 0, bottom: 34, left: 0 };
const phone = { width: 390, height: 844 };
const withInsets = { top: Math.max(12, insets.top), right: Math.max(12, insets.right), bottom: 38 + insets.bottom, left: Math.max(12, insets.left) };
// CSS: bottom: calc(38px + env(safe-area-inset-bottom)) -> 844 - 72 - 38.
assert.equal(floatingRect("bottom-left", capsule, phone, withInsets).top, 844 - 72 - 38);
assert.equal(floatingRect("top-left", capsule, phone, withInsets).top, 47);
});
test("with every spot taken, the capsule covers a dialog button before a protected control", () => {
const mobile = { width: 390, height: 844 };
const wide = { width: 250, height: 38 };
// Dialog buttons everywhere except top-left, where the microphone is.
const obstacles: FloatingObstacle[] = [
{ rect: rect(0, 0, 270, 60), weight: FLOATING_WEIGHT_PROTECTED },
{ rect: rect(120, 0, 270, 60), weight: FLOATING_WEIGHT_DIALOG },
{ rect: rect(0, 380, 390, 90), weight: FLOATING_WEIGHT_DIALOG },
{ rect: rect(0, 740, 390, 104), weight: FLOATING_WEIGHT_DIALOG },
];
const choice = chooseFloatingPosition({ current: "bottom-left", size: wide, viewport: mobile, margins, obstacles });
const footprint = floatingRect(choice.position, wide, mobile, margins);
assert.equal(floatingScore(footprint, [obstacles[0]]), 0, choice.position);
});
+198 -27
View File
@@ -13,8 +13,11 @@
* visible interactive controls at runtime and moves the host control to the
* candidate position that covers the fewest of them (protected parts and
* controls inside an open dialog count more). When every position collides,
* the caller may fall back to a compact footprint. The host control stays in
* the viewport and stays clickable in every position; only its corner changes.
* the caller may fall back to a compact footprint (only when that frees at
* 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.
*/
import { PROTECTED_PART_IDS } from "../../../src/shared/skin-visual-parts.js";
@@ -62,9 +65,33 @@ export const HOST_FLOATING_INTERVAL_MS = 400;
export const HOST_FLOATING_AFTER_CLICK_MS = 150;
/** Obstacle weights. */
export const FLOATING_WEIGHT_CONTROL = 1;
export const FLOATING_WEIGHT_PROTECTED = 4;
/** Above dialogs and the other host control: a protected control is the last thing to cover. */
export const FLOATING_WEIGHT_PROTECTED = 16;
export const FLOATING_WEIGHT_DIALOG = 8;
export const FLOATING_WEIGHT_HOST = 8;
/** Weight of the user's last pointer position and focused control when moving. */
export const FLOATING_WEIGHT_POINTER = 8;
/**
* Folding to the compact mark must free at least one control's worth of score
* (every covered obstacle costs at least `weight × 0.25`). A sliver less of a
* viewport-sized click-away layer is not a reason to hide the buttons.
*/
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.
*/
export const HOST_FLOATING_MOVE_CONFIRM_MS = 250;
export const HOST_FLOATING_MOVE_MIN_INTERVAL_MS = 1000;
export const HOST_FLOATING_FLAP_WINDOW_MS = 10_000;
export const HOST_FLOATING_FLAP_MAX_MOVES = 6;
export const HOST_FLOATING_FLAP_FREEZE_MS = 10_000;
/** Parts that wrap ordinary controls; a control inside them is not "protected" by that alone. */
const CONTAINER_PARTS: ReadonlySet<string> = new Set(["app", "home.footer"]);
/** Radius around the last pointer position that a move must not land on. */
const POINTER_RADIUS = 16;
/** Rect a control of `size` would occupy at `position`. */
export function floatingRect(
@@ -117,9 +144,12 @@ export interface FloatingChoice {
}
/**
* Keep `current` while it is collision-free; otherwise take the position with
* the lowest score (ties keep `current`, then follow `FLOATING_POSITIONS`
* order so the default corner wins whenever it is as good as any other).
* Keep `current` while it is collision-free (a free control never moves, even
* when the default corner becomes free again: stability beats tidiness);
* otherwise take the position with the lowest score. Ties keep `current`, then
* follow `FLOATING_POSITIONS` order. `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.
*/
export function chooseFloatingPosition(input: {
current: FloatingPosition;
@@ -127,13 +157,16 @@ export function chooseFloatingPosition(input: {
viewport: FloatingViewport;
margins: FloatingMargins;
obstacles: readonly FloatingObstacle[];
moveObstacles?: readonly FloatingObstacle[];
positions?: readonly FloatingPosition[];
}): FloatingChoice {
const positions = input.positions ?? FLOATING_POSITIONS;
const scoreAt = (position: FloatingPosition) => floatingScore(
floatingRect(position, input.size, input.viewport, input.margins),
input.obstacles,
);
const moveObstacles = input.moveObstacles ?? [];
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 currentScore = scoreAt(input.current);
if (currentScore === 0) return { position: input.current, score: 0 };
let best: FloatingChoice = { position: input.current, score: currentScore };
@@ -146,11 +179,42 @@ export function chooseFloatingPosition(input: {
return best;
}
/** Fold to the compact mark only when that frees at least one control's worth. */
export function shouldFold(full: FloatingChoice, reduced: FloatingChoice): boolean {
return full.score > 0 && reduced.score <= full.score - FLOATING_FOLD_MIN_GAIN + 1e-6;
}
/** Margins of a floating control: its own spacing plus the device safe area. */
export function readSafeAreaInsets(parent: Node & ParentNode): FloatingMargins {
const zero = { top: 0, right: 0, bottom: 0, left: 0 };
const doc = parent.ownerDocument ?? (parent as unknown as Document);
const view = doc?.defaultView;
if (!view) return zero;
const probe = doc.createElement("span");
probe.setAttribute("aria-hidden", "true");
probe.style.cssText = "position:absolute;visibility:hidden;pointer-events:none;width:0;height:0;overflow:hidden;"
+ "padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)";
parent.appendChild(probe);
try {
const style = view.getComputedStyle(probe);
const read = (value: string) => Math.max(0, Number.parseFloat(value) || 0);
return { top: read(style.paddingTop), right: read(style.paddingRight), bottom: read(style.paddingBottom), left: read(style.paddingLeft) };
} finally {
probe.remove();
}
}
function rectsIntersect(first: HostPartRect, second: HostPartRect): boolean {
return first.left < second.right && first.right > second.left && first.top < second.bottom && first.bottom > second.top;
}
/* ------------------------------------------------------------------ *
* DOM binding
* ------------------------------------------------------------------ */
const INTERACTIVE_SELECTOR = "a[href],button,input:not([type='hidden']),select,textarea,summary,[role='button'],[role='tab'],[role='menuitem'],[role='link'],[contenteditable='true']";
const INTERACTIVE_SELECTOR = "a[href],button,input:not([type='hidden']),select,textarea,summary,iframe,audio[controls],video[controls],"
+ "[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']";
/** Live host floating controls, so they also avoid each other. */
@@ -170,18 +234,30 @@ export function collectFloatingObstacles(options: {
/** Elements that belong to the floating control (light DOM wrapper or layer host). */
isSelf: (element: Element) => boolean;
owner: Element;
/**
* Only controls intersecting one of these rects can change a score; others
* skip the style read and hit test (keeps a 3 000-control skin cheap).
*/
regions?: readonly HostPartRect[];
}): FloatingObstacle[] {
const { doc, isSelf, owner } = options;
const { doc, isSelf, owner, regions } = options;
const view = doc.defaultView;
if (!view) return [];
const obstacles: FloatingObstacle[] = [];
const viewportWidth = view.innerWidth;
const viewportHeight = view.innerHeight;
const others = [...registry].filter(entry => entry.owner !== owner).map(entry => entry.owner);
for (const element of doc.querySelectorAll<HTMLElement>(INTERACTIVE_SELECTOR)) {
if (isSelf(element)) continue;
// Another host floating control is added once below, with its own weight.
if (others.some(other => other.contains(element))) continue;
const rect = element.getBoundingClientRect();
if (rect.width < 2 || rect.height < 2) continue;
if (rect.right <= 0 || rect.bottom <= 0 || rect.left >= viewportWidth || rect.top >= viewportHeight) continue;
if (regions && !regions.some(region => rectsIntersect(region, rect))) continue;
// Invisible (opacity 0 / visibility hidden) controls cannot be covered.
if (typeof element.checkVisibility === "function"
&& !element.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue;
const style = view.getComputedStyle(element);
if (style.visibility === "hidden" || style.visibility === "collapse" || style.pointerEvents === "none") continue;
// Disabled controls still count: a "Send" button is disabled only until the
@@ -191,9 +267,10 @@ export function collectFloatingObstacles(options: {
const hit = doc.elementFromPoint(x, y);
if (!hit || !(hit === element || element.contains(hit) || isSelf(hit))) continue;
const part = element.closest("[data-ws-part]")?.getAttribute("data-ws-part") ?? "";
const weight = element.closest(DIALOG_SELECTOR)
? FLOATING_WEIGHT_DIALOG
: PROTECTED_PART_IDS.has(part) ? FLOATING_WEIGHT_PROTECTED : FLOATING_WEIGHT_CONTROL;
const protectedPart = PROTECTED_PART_IDS.has(part) && !CONTAINER_PARTS.has(part);
const weight = protectedPart
? FLOATING_WEIGHT_PROTECTED
: element.closest(DIALOG_SELECTOR) ? FLOATING_WEIGHT_DIALOG : FLOATING_WEIGHT_CONTROL;
obstacles.push({ rect: toRect(rect), weight });
}
for (const entry of registry) {
@@ -209,7 +286,14 @@ export interface FloatingAvoidanceOptions {
element: HTMLElement;
/** Element that identifies "self" for hit tests (layer host or the element). */
isSelf: (element: Element) => boolean;
margins: FloatingMargins;
/**
* Fixed margins, or margins derived from the device safe-area insets (the
* CSS positions the control with `env(safe-area-inset-*)`, so the model must
* use the same numbers). Insets are re-read on bind and on resize.
*/
margins: FloatingMargins | ((insets: FloatingMargins) => FloatingMargins);
/** Where the safe-area probe is inserted (the control's shadow root or element). */
insetsParent?: Node & ParentNode;
defaultPosition?: FloatingPosition;
/** Apply a position (attribute/class on the element; never inline skin styles). */
apply: (position: FloatingPosition) => void;
@@ -227,7 +311,7 @@ export interface FloatingAvoidance {
}
export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): FloatingAvoidance {
const { element, isSelf, margins, apply, onCompactChange } = options;
const { element, isSelf, apply, onCompactChange } = options;
const doc = element.ownerDocument;
const view = doc.defaultView;
const defaultPosition = options.defaultPosition ?? "bottom-left";
@@ -236,6 +320,26 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
let fullSize: FloatingSize = { width: 0, height: 0 };
let disposed = false;
let timer: ReturnType<typeof setInterval> | undefined;
let lastViewport = { width: 0, height: 0 };
let margins: FloatingMargins = { top: 0, right: 0, bottom: 0, left: 0 };
let pointer: { x: number; y: number } | null = null;
let pendingSince = 0;
let lastMoveAt = Number.NEGATIVE_INFINITY;
let frozenUntil = 0;
let moveTimes: number[] = [];
let confirmTimer: ReturnType<typeof setTimeout> | undefined;
function scheduleConfirm(delay: number) {
if (confirmTimer) clearTimeout(confirmTimer);
confirmTimer = setTimeout(() => { confirmTimer = undefined; safeEvaluate(); }, Math.max(0, delay) + 20);
}
function refreshMargins() {
const spec = options.margins;
if (typeof spec !== "function") { margins = spec; return; }
let insets = { top: 0, right: 0, bottom: 0, left: 0 };
try { insets = readSafeAreaInsets(options.insetsParent ?? element); } catch { /* keep zero insets */ }
margins = spec(insets);
}
refreshMargins();
const entry = {
owner: element as Element,
rect: () => {
@@ -257,23 +361,78 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
if (options.paused?.()) return;
const box = element.getBoundingClientRect();
if (!(box.width > 0) || !(box.height > 0)) return;
// The expanded footprint is what the user sees on hover/focus, so score
// with the largest full size observed (never the compact size).
if (!compact) fullSize = { width: Math.max(fullSize.width, box.width), height: Math.max(fullSize.height, box.height) };
const size = fullSize.width > 0 ? fullSize : { width: box.width, height: box.height };
const viewport = { width: view.innerWidth, height: view.innerHeight };
const obstacles = collectFloatingObstacles({ doc, isSelf, owner: element });
const full = chooseFloatingPosition({ current: position, size, viewport, margins, obstacles });
if (viewport.width !== lastViewport.width || viewport.height !== lastViewport.height) {
// Rotation / resize: re-read the safe area and forget the old footprint.
lastViewport = viewport;
fullSize = { width: 0, height: 0 };
refreshMargins();
}
// Score with the expanded footprint the user sees on hover/focus: the live
// size while expanded (it follows language changes), the last expanded
// size while folded.
if (!compact) fullSize = { width: box.width, height: box.height };
const size = fullSize.width > 0 ? fullSize : { width: box.width, height: box.height };
const small = options.compactSize?.() ?? null;
const regions: HostPartRect[] = [];
for (const candidate of FLOATING_POSITIONS) {
regions.push(floatingRect(candidate, size, viewport, margins));
if (small && small.width > 0 && small.height > 0) regions.push(floatingRect(candidate, small, viewport, margins));
}
const obstacles = collectFloatingObstacles({ doc, isSelf, owner: element, regions });
const moveObstacles: FloatingObstacle[] = [];
if (pointer) {
moveObstacles.push({ rect: { left: pointer.x - POINTER_RADIUS, top: pointer.y - POINTER_RADIUS, width: POINTER_RADIUS * 2, height: POINTER_RADIUS * 2, right: pointer.x + POINTER_RADIUS, bottom: pointer.y + POINTER_RADIUS }, weight: FLOATING_WEIGHT_POINTER });
}
const focused = doc.activeElement;
if (focused && focused !== doc.body && focused !== doc.documentElement && !isSelf(focused)) {
const rect = focused.getBoundingClientRect();
if (rect.width > 0 && rect.height > 0) moveObstacles.push({ rect: toRect(rect), weight: FLOATING_WEIGHT_POINTER });
}
const full = chooseFloatingPosition({ current: position, size, viewport, margins, obstacles, moveObstacles });
let next = full;
let nextCompact = false;
const small = full.score > 0 ? options.compactSize?.() : null;
if (small && small.width > 0 && small.height > 0) {
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles });
if (reduced.score < full.score - 1e-6) {
if (full.score > 0 && small && small.width > 0 && small.height > 0) {
const reduced = chooseFloatingPosition({ current: full.position, size: small, viewport, margins, obstacles, moveObstacles });
if (shouldFold(full, reduced)) {
next = reduced;
nextCompact = true;
}
}
if (next.position === position && nextCompact === compact) {
pendingSince = 0;
return;
}
const now = Date.now();
if (now < frozenUntil) return;
if (!pendingSince) {
pendingSince = now;
scheduleConfirm(HOST_FLOATING_MOVE_CONFIRM_MS);
return;
}
if (now - pendingSince < HOST_FLOATING_MOVE_CONFIRM_MS) {
scheduleConfirm(HOST_FLOATING_MOVE_CONFIRM_MS - (now - pendingSince));
return;
}
if (now - lastMoveAt < HOST_FLOATING_MOVE_MIN_INTERVAL_MS) {
scheduleConfirm(HOST_FLOATING_MOVE_MIN_INTERVAL_MS - (now - lastMoveAt));
return;
}
pendingSince = 0;
lastMoveAt = now;
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;
if (position !== defaultPosition) {
position = defaultPosition;
apply(position);
}
setCompact(false);
return;
}
if (next.position !== position) {
position = next.position;
apply(position);
@@ -299,10 +458,17 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
if (clickTimer) clearTimeout(clickTimer);
clickTimer = setTimeout(safeEvaluate, HOST_FLOATING_AFTER_CLICK_MS);
};
const onPointer = (event: PointerEvent) => { pointer = { x: event.clientX, y: event.clientY }; };
const onPointerLeave = () => { pointer = null; };
if (view) {
timer = setInterval(safeEvaluate, HOST_FLOATING_INTERVAL_MS);
view.addEventListener("resize", safeEvaluate, { passive: true });
doc.addEventListener("click", afterClick, { capture: true, passive: true });
// A scrolled list can carry a control under the host control.
doc.addEventListener("scroll", afterClick, { capture: true, passive: true });
doc.addEventListener("pointermove", onPointer, { capture: true, passive: true });
doc.addEventListener("pointerdown", onPointer, { capture: true, passive: true });
doc.documentElement.addEventListener("pointerleave", onPointerLeave, { passive: true });
}
safeEvaluate();
@@ -314,8 +480,13 @@ export function bindFloatingAvoidance(options: FloatingAvoidanceOptions): Floati
registry.delete(entry);
if (timer) clearInterval(timer);
if (clickTimer) clearTimeout(clickTimer);
if (confirmTimer) clearTimeout(confirmTimer);
view?.removeEventListener("resize", safeEvaluate);
doc.removeEventListener("click", afterClick, { capture: true });
doc.removeEventListener("scroll", afterClick, { capture: true });
doc.removeEventListener("pointermove", onPointer, { capture: true });
doc.removeEventListener("pointerdown", onPointer, { capture: true });
doc.documentElement.removeEventListener("pointerleave", onPointerLeave);
setCompact(false);
},
};
+89 -6
View File
@@ -26,7 +26,7 @@
<pre id="result">pending</pre>
<script type="module">
import { createHostOwnedLayer } from "/src/services/host-owned-layer.ts";
import { bindFloatingAvoidance } from "/src/services/host-floating-placement.ts";
import { bindFloatingAvoidance, collectFloatingObstacles } from "/src/services/host-floating-placement.ts";
const output = document.getElementById("result");
const CSS = `
@@ -38,6 +38,9 @@ const CSS = `
.cap.compact { width: 30px; }
`;
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Moves are confirmed after a short dwell and rate-limited (anti-flap).
let binding;
const settle = async () => { binding.revalidate(); await sleep(1400); binding.revalidate(); await sleep(50); };
try {
const layer = createHostOwnedLayer("recovery", CSS);
const control = document.createElement("div");
@@ -48,7 +51,7 @@ try {
control.showPopover();
const host = layer.host;
let compact = false;
const binding = bindFloatingAvoidance({
binding = bindFloatingAvoidance({
element: control,
isSelf: (node) => node === host || host.contains(node),
margins: { top: 12, right: 12, bottom: 38, left: 12 },
@@ -68,26 +71,106 @@ try {
return document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2) === host;
})() });
const results = [];
binding.revalidate();
await settle();
results.push(snap("dock-and-send"));
// Stability: repeated re-checks (interval + manual) never move a settled capsule.
const seen = new Set([binding.position]);
for (let i = 0; i < 6; i++) { binding.revalidate(); seen.add(binding.position); await sleep(120); }
await sleep(1300); seen.add(binding.position);
results.push({ ...snap("stable"), positions: [...seen] });
// A full-screen click-away layer (role=button) is "covered" everywhere; a
// sliver less of it is no reason to fold the capsule to its mark.
document.body.insertAdjacentHTML("beforeend", '<div id="clickaway" role="button" tabindex="0" style="position:fixed;inset:0"></div>');
await settle();
results.push(snap("click-away"));
document.getElementById("clickaway").remove();
await settle();
// A second host floating control (like the application-library launcher):
// the two never overlap and settle without flapping.
const lib = document.createElement("div");
lib.id = "lib";
lib.style.cssText = "position:fixed;right:16px;bottom:16px;width:44px;height:44px;z-index:5";
lib.innerHTML = '<button type="button" style="width:44px;height:44px">L</button>';
document.body.append(lib);
const libPositions = new Set();
const libBinding = bindFloatingAvoidance({
element: lib,
isSelf: (node) => lib.contains(node),
margins: (insets) => ({ top: 16 + insets.top, right: 16, bottom: 16 + insets.bottom, left: 16 }),
defaultPosition: "bottom-right",
apply: (position) => {
libPositions.add(position);
lib.style.left = position.endsWith("left") ? "16px" : position.endsWith("center") ? "calc(50% - 22px)" : "auto";
lib.style.right = position.endsWith("right") ? "16px" : "auto";
lib.style.top = position.startsWith("top") ? "16px" : position.startsWith("middle") ? "calc(50% - 22px)" : "auto";
lib.style.bottom = position.startsWith("bottom") ? "16px" : "auto";
},
});
const capPositions = new Set([binding.position]);
for (let i = 0; i < 12; i++) { libBinding.revalidate(); binding.revalidate(); capPositions.add(binding.position); await sleep(400); }
const cr = control.getBoundingClientRect(), lr = lib.getBoundingClientRect();
const overlap = !(cr.right <= lr.left || lr.right <= cr.left || cr.bottom <= lr.top || lr.bottom <= cr.top);
results.push({ ...snap("two-controls"), overlap, libPosition: libBinding.position, libMoves: libPositions.size, capMoves: capPositions.size, sendCovered: document.elementFromPoint(...(() => { const r = document.getElementById("send").getBoundingClientRect(); return [r.left + r.width / 2, r.top + r.height / 2]; })())?.closest("#lib") != null });
libBinding.dispose();
lib.remove();
await settle();
// A bottom sheet opens behind a backdrop: only its buttons count now.
document.body.insertAdjacentHTML("beforeend", '<div id="backdrop"></div><div id="sheet" role="dialog" aria-modal="true"><button type="button" id="cancel">Cancel</button><button type="button" id="enter">Enter channel</button></div>');
document.getElementById("cancel").click();
await sleep(400);
await sleep(1400);
results.push({ ...snap("after-click-sheet"), before: results[0].position });
// Everything is covered: the capsule folds to its mark at the least harmful spot.
document.getElementById("sheet").remove();
document.getElementById("backdrop").remove();
document.body.insertAdjacentHTML("beforeend", '<div id="wall" style="position:fixed;inset:0;display:grid;grid-template-columns:repeat(20,1fr)">' + '<button type="button"></button>'.repeat(400) + "</div>");
binding.revalidate();
await settle();
results.push(snap("wall"));
document.getElementById("wall").remove();
binding.revalidate();
await settle();
results.push(snap("wall-removed"));
// Weights: an unmarked skin button inside the protected "app" root is an
// ordinary control; the microphone is protected; invisible controls do not
// count; a custom div[tabindex] button does.
document.querySelector(".ws-skin-root").insertAdjacentHTML("beforeend",
'<button type="button" id="plain" style="position:fixed;left:600px;top:300px;width:60px;height:30px">Plain</button>'
+ '<button type="button" id="ghost" style="position:fixed;left:700px;top:300px;width:60px;height:30px;opacity:0">Ghost</button>'
+ '<div id="custom" tabindex="0" style="position:fixed;left:800px;top:300px;width:60px;height:30px">Custom</div>');
const weightOf = (id) => {
const r = document.getElementById(id).getBoundingClientRect();
const hit = collectFloatingObstacles({ doc: document, isSelf: () => false, owner: document.body })
.find((o) => Math.abs(o.rect.left - r.left) < 0.5 && Math.abs(o.rect.top - r.top) < 0.5);
return hit ? hit.weight : 0;
};
results.push({ name: "weights", plain: weightOf("plain"), mic: weightOf("mic"), ghost: weightOf("ghost"), custom: weightOf("custom") });
for (const id of ["plain", "ghost", "custom"]) document.getElementById(id).remove();
// Anti-flap: a skin control hopping between the free spots every 200 ms
// (all other spots taken) cannot keep the capsule moving.
document.body.insertAdjacentHTML("beforeend", '<div id="walls">'
+ ["left:8px;top:8px", "right:8px;top:8px", "left:8px;top:380px", "right:8px;top:380px", "left:540px;top:8px", "left:540px;bottom:20px"]
.map((pos) => `<button type="button" style="position:fixed;${pos};width:230px;height:44px"></button>`).join("") + "</div>");
document.body.insertAdjacentHTML("beforeend", '<button type="button" id="hopper" style="position:fixed;bottom:40px;left:20px;width:220px;height:34px"></button>');
const hopper = document.getElementById("hopper");
const flapPositions = [];
let last = binding.position;
for (let i = 0; i < 60; i++) {
hopper.style.left = i % 2 ? "auto" : "20px";
hopper.style.right = i % 2 ? "20px" : "auto";
binding.revalidate();
if (binding.position !== last) { flapPositions.push(binding.position); last = binding.position; }
await sleep(200);
}
results.push({ name: "flap", moves: flapPositions.length, capsuleHit: snap("x").capsuleHit });
hopper.remove();
document.getElementById("walls").remove();
binding.dispose();
results.push({ ...snap("disposed") });
output.textContent = JSON.stringify({ results });
+24 -1
View File
@@ -316,7 +316,7 @@ test("floating host controls move off skin controls at runtime", { skip: !CHROME
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-placement.html`, ["--virtual-time-budget=10000", "--window-size=1280,800"]);
const dom = await dumpDom(`http://127.0.0.1:${port}/test/fixtures/host-floating-placement.html`, ["--virtual-time-budget=60000", "--window-size=1280,800"]);
const match = dom.match(/<pre id="result"[^>]*>([\s\S]*?)<\/pre>/);
assert.ok(match, "the fixture did not emit a result block");
const payload = JSON.parse(match[1].replace(/&quot;/g, '"').replace(/&amp;/g, "&"));
@@ -332,6 +332,18 @@ test("floating host controls move off skin controls at runtime", { skip: !CHROME
assert.equal(first.capsuleHit, true, "the moved capsule is not clickable");
assert.equal(first.compact, false);
// Settled: repeated re-checks over ~2 s never move it again (no jitter).
assert.deepEqual(byName.stable.positions, [first.position], JSON.stringify(byName.stable));
// A full-screen click-away layer is no reason to fold to the mark.
assert.equal(byName["click-away"].compact, false, JSON.stringify(byName["click-away"]));
// Two host floating controls never overlap, settle, and neither covers Send.
const two = byName["two-controls"];
assert.equal(two.overlap, false, JSON.stringify(two));
assert.equal(two.capMoves, 1, JSON.stringify(two));
assert.ok(two.libMoves <= 2, JSON.stringify(two));
assert.equal(two.sendCovered, false, JSON.stringify(two));
assert.deepEqual(two.covered, [], JSON.stringify(two));
// A modal sheet opened by a click: its buttons are freed within one re-check.
// Controls under the modal backdrop are not reachable anyway and do not count.
assert.deepEqual(byName["after-click-sheet"].covered.filter((id) => id === "cancel" || id === "enter"), [], JSON.stringify(byName["after-click-sheet"]));
@@ -343,6 +355,17 @@ test("floating host controls move off skin controls at runtime", { skip: !CHROME
assert.equal(byName.wall.capsuleHit, true);
assert.equal(byName["wall-removed"].compact, false);
// Weighting: plain skin buttons are ordinary even inside the protected app root.
assert.deepEqual(
{ plain: byName.weights.plain, mic: byName.weights.mic, ghost: byName.weights.ghost, custom: byName.weights.custom },
{ plain: 1, mic: 16, ghost: 0, custom: 1 },
JSON.stringify(byName.weights),
);
// 12 s of a control hopping every 200 ms: at most a handful of moves, then the
// capsule holds still (moves ≥ 1 s apart, frozen after 6 in 10 s).
t.diagnostic(`flap ${JSON.stringify(byName.flap)} two ${JSON.stringify(byName["two-controls"])}`);
assert.ok(byName.flap.moves <= 8, JSON.stringify(byName.flap));
assert.equal(byName.flap.capsuleHit, true);
assert.equal(byName.disposed.compact, false);
});