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

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