diff --git a/docs/SKIN_DEVELOPMENT.md b/docs/SKIN_DEVELOPMENT.md index 4085681..6f7061a 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)检查一次它是否盖住了皮肤里可见、处于最上层的可交互控件(按钮、链接、输入框等;禁用的“发送”按钮也算,受保护部件和打开的对话框/底部弹层里的控件权重更高)。盖住时,胶囊会换到左下、右下、左上、右上、左中、右中、底部居中、顶部居中里遮挡最少的位置;处处都会遮挡时,收成只显示 ◈ 的紧凑形态(悬停、聚焦或点按展开)。鼠标悬停或焦点在胶囊内时不会移动。宿主自带的应用库悬浮按钮(皮肤没有提供 `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-*` 优先;只有颜色对比度不达标时整组颜色才回退到宿主默认值。声明了插槽但没写颜色令牌时,胶囊使用不透明的宿主默认色(白底),而不是无插槽时的半透明底。 diff --git a/web/src/components/HostChrome.vue b/web/src/components/HostChrome.vue index f141dae..5b72c15 100644 --- a/web/src/components/HostChrome.vue +++ b/web/src/components/HostChrome.vue @@ -251,6 +251,9 @@ const compactPinned = ref(false); const floatPosition = ref("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); diff --git a/web/src/components/PluginPanel.vue b/web/src/components/PluginPanel.vue index aac36a1..d6d469d 100644 --- a/web/src/components/PluginPanel.vue +++ b/web/src/components/PluginPanel.vue @@ -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; }); diff --git a/web/src/services/host-floating-placement.test.ts b/web/src/services/host-floating-placement.test.ts index 899933f..f4da16a 100644 --- a/web/src/services/host-floating-placement.test.ts +++ b/web/src/services/host-floating-placement.test.ts @@ -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); +}); diff --git a/web/src/services/host-floating-placement.ts b/web/src/services/host-floating-placement.ts index 41c463e..fec5e22 100644 --- a/web/src/services/host-floating-placement.ts +++ b/web/src/services/host-floating-placement.ts @@ -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 = 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(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 | 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 | 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); }, }; diff --git a/web/test/fixtures/host-floating-placement.html b/web/test/fixtures/host-floating-placement.html index 773e024..31d2bf6 100644 --- a/web/test/fixtures/host-floating-placement.html +++ b/web/test/fixtures/host-floating-placement.html @@ -26,7 +26,7 @@
pending