Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 930d33fc6b fix(app): track partly clipped triggers and centralize anchor geometry reads
- Keep observeElementMove active when a trigger is partly clipped by a scroll
  container or viewport edge by bracketing its visible intersectionRatio and
  relaxing the inset opposite clipped edges, with a browser regression test.
- Add useAnchorGeometry inside packages/app/src/components/ui/anchor so Menu
  and Tooltip share one viewport/anchor measurement and 0x0-filtering path
  instead of reassembling the observer primitives separately.
2026-12-01 16:48:20 +01:00
Mohamed Boudra ce329d6bf1 fix(app): keep anchored popovers attached when layout or orientation changes
HoverCard, Menu, Tooltip, Combobox, and AutocompletePopover either measured
their trigger only on mount or watched only the trigger and portal host boxes.
Toggling sidebars, resizing panes, shifting siblings inside a fixed-width row,
or rotating a tablet left open surfaces stranded or clipped off-screen.

Introduce a shared useAnchorLayoutObserver inside packages/app/src/components/ui/anchor:
- On web, observe the anchor and host ancestor chains with ResizeObserver plus
  a zero-polling IntersectionObserver move detector, capturing the pre-flush
  anchor rect before flushSync so repositioning avoids a second layout recalc.
- On native, listen to Dimensions changes and re-measure across the next two
  animation frames and rotation settle delays so iOS UIKit/Fabric layout commits
  before final placement.
- Wire all five anchored surfaces to the observer, wrap dynamic holder heights
  with inlineUnistylesStyle to prevent CSSOM rule churn, and derive Menu and
  Tooltip placement via useMemo so each resize commits once.
2026-12-01 16:34:11 +01:00
14 changed files with 1537 additions and 196 deletions
+7 -4
View File
@@ -324,10 +324,13 @@ Fabric's transform-free `measureLayout` instead. Re-measure when `isMoving`
settles; the composer's resting position changes as the draft grows.
A measured rect is an asynchronous copy, so it lands after the anchor's new
layout has painted. The composer resizes while the autocomplete is open: a
wrapped line, cleared text, a window resize. On web a `ResizeObserver` reads
the anchor's rect against the layer and commits the placement with `flushSync`,
which runs after layout and before paint. On native a Reanimated frame callback
layout has painted. Layout shifts while a surface is open: a wrapped line, a
toggled or resized sidebar, a split-pane drag, a sibling button appearing, or a
window resize. Use `useAnchorLayoutObserver` from `@/components/ui/anchor` so
anchored surfaces follow those moves: on web it watches the anchor, its layout
ancestors, the host, and element movement, committing placement with `flushSync`
after layout and before paint; on native it listens for `Dimensions` changes.
On native autocomplete, a Reanimated frame callback
reads only the anchor's height on the UI thread and holds its bottom edge at
the rest measurement. A height carries no transform. On iOS the absolute
position does not follow the keyboard while it moves: the lift runs on the
@@ -439,7 +439,7 @@ test("usage arriving after the card opens never moves its bottom edge", async ({
expect(new Set(frames.map((frame) => frame.bottom)).size).toBe(1);
});
test("context details support keyboard entry and dismiss when the viewport moves", async ({
test("context details support keyboard entry and follow when the viewport resizes", async ({
page,
agent,
}) => {
@@ -480,9 +480,86 @@ test("context details support keyboard entry and dismiss when the viewport moves
await trigger.press("ArrowDown");
await expect(details).toBeVisible();
await page.setViewportSize({ width: 1280, height: 850 });
await expect(details).toBeVisible();
await expect(details).toBeInViewport({ ratio: 1 });
const meterAfterResize = await meter.boundingBox();
const cardAfterResize = await details.boundingBox();
expect(meterAfterResize).not.toBeNull();
expect(cardAfterResize).not.toBeNull();
const expectedLeft = Math.max(
8,
Math.min(
1280 - cardAfterResize!.width - 8,
meterAfterResize!.x + meterAfterResize!.width / 2 - cardAfterResize!.width / 2,
),
);
expect(Math.abs(cardAfterResize!.x - expectedLeft)).toBeLessThan(2);
expect(
Math.abs(meterAfterResize!.y - (cardAfterResize!.y + cardAfterResize!.height) - 8),
).toBeLessThan(2);
await page.keyboard.press("Escape");
await expect(details).toHaveCount(0);
});
test("context details follow when left and right sidebars toggle", async ({ page, agent }) => {
test.setTimeout(180_000);
const usage = await scriptAgentUsage(page);
const [claude] = claudeAndCodexReports();
usage.answerNext([onPersonalLogin(claude!)]);
await page.setViewportSize({ width: 1280, height: 800 });
await openAgent(page, agent);
const meter = page.getByTestId("context-window-meter");
await expect(meter).toBeVisible({ timeout: 30_000 });
const expectCardAnchoredToMeter = async (card: Locator) => {
await expect(card).toBeVisible();
await expect(card).toBeInViewport({ ratio: 1 });
const meterBox = await meter.boundingBox();
const cardBox = await card.boundingBox();
expect(meterBox).not.toBeNull();
expect(cardBox).not.toBeNull();
const expectedLeft = Math.max(
8,
Math.min(1280 - cardBox!.width - 8, meterBox!.x + meterBox!.width / 2 - cardBox!.width / 2),
);
expect(Math.abs(cardBox!.x - expectedLeft)).toBeLessThan(2);
expect(cardBox!.x + cardBox!.width).toBeLessThanOrEqual(1280 - 8 + 1);
expect(Math.abs(meterBox!.y - (cardBox!.y + cardBox!.height) - 8)).toBeLessThan(2);
};
// Start with the left sidebar closed, open the card, and rest the pointer on the card.
await page.keyboard.press("ControlOrMeta+b");
const card = await hoverContextWindowMeter(page);
await moveOntoContextWindowDetails(page, card);
await expectCardAnchoredToMeter(card);
// Open the left sidebar while the card stays open: the card must follow and stay on screen.
const meterXBeforeLeftOpen = (await meter.boundingBox())!.x;
await page.keyboard.press("ControlOrMeta+b");
await expect
.poll(async () => (await meter.boundingBox())?.x ?? meterXBeforeLeftOpen)
.toBeGreaterThan(meterXBeforeLeftOpen + 100);
await expectCardAnchoredToMeter(card);
// Open the right explorer sidebar while the card stays open: the card must follow left.
const meterXBeforeExplorerOpen = (await meter.boundingBox())!.x;
await page.keyboard.press("ControlOrMeta+e");
await expect
.poll(async () => (await meter.boundingBox())?.x ?? meterXBeforeExplorerOpen)
.toBeLessThan(meterXBeforeExplorerOpen - 100);
await expectCardAnchoredToMeter(card);
// Close the right explorer sidebar: the card must follow back right.
await page.keyboard.press("ControlOrMeta+e");
await expect
.poll(async () => (await meter.boundingBox())?.x ?? 0)
.toBeGreaterThan(meterXBeforeExplorerOpen - 10);
await expectCardAnchoredToMeter(card);
await leaveContextWindowMeter(page);
});
test("context details stay open while the chat streams", async ({ page }) => {
test.setTimeout(120_000);
await page.setViewportSize(DESKTOP);
@@ -0,0 +1,550 @@
import React, { act, useMemo, useRef, useState } from "react";
import { createRoot } from "react-dom/client";
import { Text, View } from "react-native";
import { PortalProvider } from "@gorhom/portal";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { page } from "vitest/browser";
import { useAnimatedRef, useSharedValue } from "react-native-reanimated";
import { PopoverFrame } from "./autocomplete-popover/internal/frame.web";
import {
FloatingPanelPortalHost,
FloatingPanelPortalHostNameProvider,
} from "./floating-panel-portal";
import { HoverCard, HoverCardContent, HoverCardTrigger } from "./hover-card";
import { AnchoredSurface } from "./menu/menu-overlay";
import { Tooltip, TooltipContent, TooltipTrigger } from "./tooltip";
const INITIAL_METRICS = {
frame: { x: 0, y: 0, width: 1200, height: 800 },
insets: { top: 0, left: 0, right: 0, bottom: 0 },
};
const NOOP = () => {};
const ROW_FULL = {
display: "flex",
flexDirection: "row",
width: "100%",
height: "100%",
} as const;
const RELATIVE_ROW_FULL = {
position: "relative",
flex: 1,
display: "flex",
flexDirection: "row",
height: "100%",
} as const;
const RELATIVE_FULL = { position: "relative", width: "100%", height: "100%" } as const;
const RELATIVE_FLEX_ROW_FULL = {
position: "relative",
width: "100%",
height: "100%",
display: "flex",
flexDirection: "row",
} as const;
const CENTER_BOTTOM_COL = {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "flex-end",
alignItems: "center",
paddingBottom: 40,
} as const;
const COMPOSER_BOTTOM_COL = {
flex: 1,
display: "flex",
flexDirection: "column",
justifyContent: "flex-end",
alignItems: "center",
paddingBottom: 32,
} as const;
const TOOLBAR_ROW = {
width: 420,
display: "flex",
flexDirection: "row",
justifyContent: "flex-end",
alignItems: "center",
gap: 8,
} as const;
const TRIGGER_STYLE = { width: 28, height: 28, backgroundColor: "#333" } as const;
const HOVER_CARD_STYLE = { width: 260, height: 100 } as const;
const SIBLING_STYLE = { width: 64, height: 28, flexShrink: 0 } as const;
const OVERLAP_TRIGGER_WRAPPER = { position: "absolute", left: 400, top: 300 } as const;
const OVERLAP_TRIGGER_STYLE = { width: 28, height: 28 } as const;
const OVERLAP_CARD_STYLE = { width: 240, height: 80 } as const;
const HIDDEN_STYLE = { display: "none" } as const;
const MENU_COLUMN = { flex: 1, paddingTop: 120, paddingLeft: 60 } as const;
const MENU_ANCHOR_STYLE = { width: 100, height: 32, marginBottom: 40 } as const;
const MENU_BODY_STYLE = { height: 60 } as const;
const TOOLTIP_ANCHOR_STYLE = { width: 60, height: 24 } as const;
const COMPOSER_ANCHOR_STYLE = { width: 360, height: 48 } as const;
const PORTAL_LAYER_STYLE = { position: "absolute", inset: 0, pointerEvents: "none" } as const;
const INITIAL_ANCHOR_AT_REST = { x: 0, y: 0, width: 360, height: 48, hostHeight: 700 } as const;
const AUTOCOMPLETE_BODY_STYLE = { height: 80 } as const;
const CLIPPED_SCROLL_BOX = {
width: 300,
height: 120,
overflow: "hidden",
position: "relative",
display: "flex",
alignItems: "center",
marginLeft: 200,
marginTop: 320,
} as const;
const CLIPPED_TRIGGER_STYLE = { width: 80, height: 32, flexShrink: 0 } as const;
const CLIPPED_SPACER_BASE = 260;
const activeCleanups: Array<() => Promise<void>> = [];
beforeEach(async () => {
await page.viewport(1200, 800);
});
afterEach(async () => {
while (activeCleanups.length > 0) {
await activeCleanups.pop()?.();
}
});
async function mountInBrowser(element: React.ReactElement) {
const container = document.createElement("div");
container.style.cssText =
"position:fixed;inset:0;width:100vw;height:100vh;margin:0;padding:0;overflow:hidden;";
document.body.appendChild(container);
const root = createRoot(container);
await act(async () => {
root.render(<SafeAreaProvider initialMetrics={INITIAL_METRICS}>{element}</SafeAreaProvider>);
});
const cleanup = async () => {
await act(async () => {
root.unmount();
});
container.remove();
};
activeCleanups.push(cleanup);
return { container, cleanup };
}
async function waitForLayoutSettled(frames = 4): Promise<void> {
for (let i = 0; i < frames; i++) {
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
}
}
async function waitForCondition(check: () => boolean, timeoutMs = 2000): Promise<void> {
const deadline = performance.now() + timeoutMs;
while (performance.now() < deadline) {
if (check()) return;
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
}
throw new Error("Timed out waiting for anchored surface layout update");
}
function getRequiredRect(selector: string): DOMRect {
const el = document.querySelector(selector);
if (!el) throw new Error(`Missing element for selector ${selector}`);
return el.getBoundingClientRect();
}
function SidebarSpacer({ width }: { width: number }) {
const style = useMemo(() => ({ width, flexShrink: 0, height: "100%" }) as const, [width]);
if (width <= 0) return null;
return <div style={style} />;
}
let cardContentRenders = 0;
function MeterToolbar({ showRightSibling }: { showRightSibling: boolean }) {
return (
<div style={CENTER_BOTTOM_COL}>
<div style={TOOLBAR_ROW}>
<HoverCard>
<HoverCardTrigger focusable accessibilityLabel="Context meter">
<View testID="test-trigger" style={TRIGGER_STYLE} />
</HoverCardTrigger>
<HoverCardContent
placement="top"
offset={8}
testID="test-hover-card"
style={HOVER_CARD_STYLE}
>
<RenderCountingContent />
</HoverCardContent>
</HoverCard>
{showRightSibling ? <div style={SIBLING_STYLE} /> : null}
</div>
</div>
);
}
function RenderCountingContent() {
cardContentRenders += 1;
return <Text>Context details</Text>;
}
describe("useAnchorLayoutObserver across anchored surfaces", () => {
test("HoverCard follows left sidebar toggle, right explorer toggle (unchanged host size), toolbar sibling shifts, and viewport resize", async () => {
let setLeftSidebarWidth!: (width: number) => void;
let setRightExplorerWidth!: (width: number) => void;
let setShowRightSibling!: (show: boolean) => void;
cardContentRenders = 0;
function WorkspaceFixture() {
const [leftSidebarWidth, _setLeft] = useState(0);
const [rightExplorerWidth, _setRight] = useState(0);
const [showRightSibling, _setSibling] = useState(false);
setLeftSidebarWidth = _setLeft;
setRightExplorerWidth = _setRight;
setShowRightSibling = _setSibling;
return (
<PortalProvider shouldAddRootHost={false}>
<div style={ROW_FULL}>
<SidebarSpacer width={leftSidebarWidth} />
<div style={RELATIVE_ROW_FULL}>
<FloatingPanelPortalHostNameProvider hostName="workspace-host">
<MeterToolbar showRightSibling={showRightSibling} />
<SidebarSpacer width={rightExplorerWidth} />
</FloatingPanelPortalHostNameProvider>
<FloatingPanelPortalHost name="workspace-host" />
</div>
</div>
</PortalProvider>
);
}
await mountInBrowser(<WorkspaceFixture />);
const triggerEl = document.querySelector('[data-testid="test-trigger"]')?.parentElement;
if (!triggerEl) throw new Error("Trigger wrapper missing");
await act(async () => {
triggerEl.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));
});
await waitForLayoutSettled();
const assertCenteredAndClamped = () => {
const triggerRect = getRequiredRect('[data-testid="test-trigger"]');
const cardRect = getRequiredRect('[data-testid="test-hover-card"]');
const triggerCenter = triggerRect.x + triggerRect.width / 2;
const expectedLeft = Math.max(
8,
Math.min(window.innerWidth - cardRect.width - 8, triggerCenter - cardRect.width / 2),
);
expect(Math.abs(cardRect.left - expectedLeft)).toBeLessThan(2);
expect(cardRect.right).toBeLessThanOrEqual(window.innerWidth - 8 + 1);
expect(Math.abs(triggerRect.top - cardRect.bottom - 8)).toBeLessThan(2);
};
assertCenteredAndClamped();
// 1. Open left sidebar (shifts workspace host right + shrinks its width).
const initialTriggerX = getRequiredRect('[data-testid="test-trigger"]').x;
await act(async () => setLeftSidebarWidth(280));
await waitForCondition(() => {
const t = getRequiredRect('[data-testid="test-trigger"]');
const c = getRequiredRect('[data-testid="test-hover-card"]');
const expectedLeft = Math.max(
8,
Math.min(window.innerWidth - c.width - 8, t.x + t.width / 2 - c.width / 2),
);
return t.x !== initialTriggerX && Math.abs(c.left - expectedLeft) < 2;
});
assertCenteredAndClamped();
// 2. Open right explorer sidebar inside the SAME portal host (host keeps its exact size).
const afterLeftTriggerX = getRequiredRect('[data-testid="test-trigger"]').x;
await act(async () => setRightExplorerWidth(220));
await waitForCondition(() => {
const t = getRequiredRect('[data-testid="test-trigger"]');
const c = getRequiredRect('[data-testid="test-hover-card"]');
const expectedLeft = Math.max(
8,
Math.min(window.innerWidth - c.width - 8, t.x + t.width / 2 - c.width / 2),
);
return t.x !== afterLeftTriggerX && Math.abs(c.left - expectedLeft) < 2;
});
assertCenteredAndClamped();
// 3. Let the move observer settle at rest, then mount a sibling inside the fixed-width row.
await waitForLayoutSettled(4);
const afterExplorerTriggerX = getRequiredRect('[data-testid="test-trigger"]').x;
await act(async () => setShowRightSibling(true));
await waitForCondition(() => {
const t = getRequiredRect('[data-testid="test-trigger"]');
const c = getRequiredRect('[data-testid="test-hover-card"]');
const expectedLeft = Math.max(
8,
Math.min(window.innerWidth - c.width - 8, t.x + t.width / 2 - c.width / 2),
);
return t.x !== afterExplorerTriggerX && Math.abs(c.left - expectedLeft) < 2;
});
assertCenteredAndClamped();
// 4. Resize the browser viewport while the card stays open.
const rendersBeforeViewportResize = cardContentRenders;
const afterSiblingTriggerX = getRequiredRect('[data-testid="test-trigger"]').x;
await page.viewport(960, 720);
await waitForCondition(() => {
const t = getRequiredRect('[data-testid="test-trigger"]');
const c = getRequiredRect('[data-testid="test-hover-card"]');
const expectedLeft = Math.max(
8,
Math.min(window.innerWidth - c.width - 8, t.x + t.width / 2 - c.width / 2),
);
return t.x !== afterSiblingTriggerX && Math.abs(c.left - expectedLeft) < 2;
});
assertCenteredAndClamped();
// HoverCardSurface repositioning must stay isolated from its child content subtree.
expect(cardContentRenders).toBe(rendersBeforeViewportResize);
});
test("HoverCard keeps its own surface ref when an overlapping hidden PortalHost shares the host name", async () => {
function OverlappingHostFixture() {
return (
<PortalProvider shouldAddRootHost={false}>
<div style={RELATIVE_FULL}>
<FloatingPanelPortalHostNameProvider hostName="shared-host">
<div style={OVERLAP_TRIGGER_WRAPPER}>
<HoverCard>
<HoverCardTrigger focusable accessibilityLabel="Shared trigger">
<View testID="overlap-trigger" style={OVERLAP_TRIGGER_STYLE} />
</HoverCardTrigger>
<HoverCardContent
placement="top"
offset={8}
testID="overlap-card"
style={OVERLAP_CARD_STYLE}
>
<Text>Visible details</Text>
</HoverCardContent>
</HoverCard>
</div>
</FloatingPanelPortalHostNameProvider>
<FloatingPanelPortalHost name="shared-host" />
<div style={HIDDEN_STYLE}>
<FloatingPanelPortalHost name="shared-host" />
</div>
</div>
</PortalProvider>
);
}
await mountInBrowser(<OverlappingHostFixture />);
const triggerWrapper = document.querySelector('[data-testid="overlap-trigger"]')?.parentElement;
if (!triggerWrapper) throw new Error("Trigger wrapper missing");
await act(async () => {
triggerWrapper.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));
});
await waitForLayoutSettled();
const triggerRect = getRequiredRect('[data-testid="overlap-trigger"]');
const visibleCard = Array.from(document.querySelectorAll('[data-testid="overlap-card"]')).find(
(el) => el.getBoundingClientRect().width > 0,
);
expect(visibleCard).toBeDefined();
const cardRect = visibleCard!.getBoundingClientRect();
const expectedLeft = triggerRect.x + (triggerRect.width - cardRect.width) / 2;
expect(Math.abs(cardRect.left - expectedLeft)).toBeLessThan(2);
});
test("AnchoredSurface (Menu) and Tooltip follow when an ancestor sidebar toggles", async () => {
let setSidebarWidth!: (width: number) => void;
function MenuAndTooltipFixture() {
const [sidebarWidth, _setSidebarWidth] = useState(0);
setSidebarWidth = _setSidebarWidth;
const menuAnchorRef = useRef<View>(null);
return (
<div style={ROW_FULL}>
<SidebarSpacer width={sidebarWidth} />
<div style={MENU_COLUMN}>
<View ref={menuAnchorRef} testID="menu-anchor" style={MENU_ANCHOR_STYLE} />
<AnchoredSurface
open
onClose={NOOP}
anchorRect={null}
anchorRef={menuAnchorRef}
side="bottom"
align="start"
offset={4}
width={180}
backdrop={false}
testID="anchored-menu"
>
<View style={MENU_BODY_STYLE}>
<Text>Menu item</Text>
</View>
</AnchoredSurface>
<Tooltip open delayDuration={0}>
<TooltipTrigger>
<View testID="tooltip-anchor" style={TOOLTIP_ANCHOR_STYLE} />
</TooltipTrigger>
<TooltipContent side="bottom" align="start" offset={6} testID="anchored-tooltip">
<Text>Tip</Text>
</TooltipContent>
</Tooltip>
</div>
</div>
);
}
await mountInBrowser(<MenuAndTooltipFixture />);
await waitForCondition(() => {
const menu = document.querySelector('[data-testid="anchored-menu"]')?.getBoundingClientRect();
const tip = document
.querySelector('[data-testid="anchored-tooltip"]')
?.getBoundingClientRect();
return Boolean(menu && menu.left > 0 && tip && tip.left > 0);
});
const beforeMenuAnchor = getRequiredRect('[data-testid="menu-anchor"]');
const beforeMenu = getRequiredRect('[data-testid="anchored-menu"]');
expect(Math.abs(beforeMenu.left - beforeMenuAnchor.left)).toBeLessThan(2);
await act(async () => setSidebarWidth(240));
await waitForCondition(() => {
const menuAnchor = getRequiredRect('[data-testid="menu-anchor"]');
const menu = getRequiredRect('[data-testid="anchored-menu"]');
const tipAnchor = getRequiredRect('[data-testid="tooltip-anchor"]');
const tip = getRequiredRect('[data-testid="anchored-tooltip"]');
return (
menuAnchor.left > beforeMenuAnchor.left + 200 &&
Math.abs(menu.left - menuAnchor.left) < 2 &&
Math.abs(tip.left - tipAnchor.left) < 2
);
});
});
test("AutocompletePopover PopoverFrame follows when a right explorer sidebar opens while the composer stays at maxWidth", async () => {
let setExplorerWidth!: (width: number) => void;
function AutocompleteFixture() {
const [explorerWidth, _setExplorerWidth] = useState(0);
setExplorerWidth = _setExplorerWidth;
const anchorRef = useAnimatedRef<View>();
const reservedLift = useSharedValue(0);
return (
<div style={RELATIVE_FLEX_ROW_FULL}>
<div style={COMPOSER_BOTTOM_COL}>
<View ref={anchorRef} testID="composer-anchor" style={COMPOSER_ANCHOR_STYLE} />
</div>
<SidebarSpacer width={explorerWidth} />
<div style={PORTAL_LAYER_STYLE}>
<PopoverFrame
anchorRef={anchorRef}
anchorAtRest={INITIAL_ANCHOR_AT_REST}
reservedLift={reservedLift}
>
<View style={AUTOCOMPLETE_BODY_STYLE}>
<Text>Slash items</Text>
</View>
</PopoverFrame>
</div>
</div>
);
}
await mountInBrowser(<AutocompleteFixture />);
await waitForLayoutSettled();
const beforeComposer = getRequiredRect('[data-testid="composer-anchor"]');
const beforePopover = getRequiredRect('[data-testid="composer-autocomplete-popover"]');
expect(Math.abs(beforePopover.left - beforeComposer.left)).toBeLessThan(2);
await act(async () => setExplorerWidth(260));
await waitForCondition(() => {
const composer = getRequiredRect('[data-testid="composer-anchor"]');
const popover = getRequiredRect('[data-testid="composer-autocomplete-popover"]');
return (
composer.left < beforeComposer.left - 100 &&
Math.abs(popover.left - composer.left) < 2 &&
Math.abs(popover.width - composer.width) < 2
);
});
});
test("HoverCard still follows a partly clipped trigger when a sibling shifts it deeper into or out of an overflow-hidden container", async () => {
let setSpacerWidth!: (width: number) => void;
function ClippedTriggerFixture() {
const [spacerWidth, _setSpacerWidth] = useState(CLIPPED_SPACER_BASE);
setSpacerWidth = _setSpacerWidth;
return (
<PortalProvider shouldAddRootHost={false}>
<div style={RELATIVE_ROW_FULL}>
<FloatingPanelPortalHostNameProvider hostName="clipped-host">
<div style={CLIPPED_SCROLL_BOX}>
<SidebarSpacer width={spacerWidth} />
<HoverCard>
<HoverCardTrigger focusable accessibilityLabel="Clipped trigger">
<View testID="clipped-trigger" style={CLIPPED_TRIGGER_STYLE} />
</HoverCardTrigger>
<HoverCardContent
placement="top"
offset={8}
testID="clipped-hover-card"
style={HOVER_CARD_STYLE}
>
<Text>Clipped card</Text>
</HoverCardContent>
</HoverCard>
</div>
</FloatingPanelPortalHostNameProvider>
<FloatingPanelPortalHost name="clipped-host" />
</div>
</PortalProvider>
);
}
await mountInBrowser(<ClippedTriggerFixture />);
const triggerEl = document.querySelector('[data-testid="clipped-trigger"]')?.parentElement;
if (!triggerEl) throw new Error("Clipped trigger missing");
await act(async () => {
triggerEl.dispatchEvent(new PointerEvent("pointerover", { bubbles: true }));
});
await waitForCondition(() => {
const trigger = getRequiredRect('[data-testid="clipped-trigger"]');
const card = getRequiredRect('[data-testid="clipped-hover-card"]');
return Math.abs(card.left + card.width / 2 - (trigger.left + trigger.width / 2)) < 2;
});
// Wait several frames so observeElementMove settles through slack=0 -> slack=1 -> clipped arm.
await waitForLayoutSettled();
await waitForLayoutSettled();
const initialTrigger = getRequiredRect('[data-testid="clipped-trigger"]');
// Shift deeper into the right clip (no watched ancestor resizes; CLIPPED_SCROLL_BOX stays 300px).
await act(async () => setSpacerWidth(CLIPPED_SPACER_BASE + 20));
await waitForCondition(() => {
const trigger = getRequiredRect('[data-testid="clipped-trigger"]');
const card = getRequiredRect('[data-testid="clipped-hover-card"]');
return (
trigger.left > initialTrigger.left + 15 &&
Math.abs(card.left + card.width / 2 - (trigger.left + trigger.width / 2)) < 2
);
});
await waitForLayoutSettled();
// Shift back out of the right clip (still partly clipped, visible ratio increases).
await act(async () => setSpacerWidth(CLIPPED_SPACER_BASE - 20));
await waitForCondition(() => {
const trigger = getRequiredRect('[data-testid="clipped-trigger"]');
const card = getRequiredRect('[data-testid="clipped-hover-card"]');
return (
trigger.left < initialTrigger.left - 15 &&
Math.abs(card.left + card.width / 2 - (trigger.left + trigger.width / 2)) < 2
);
});
});
});
@@ -4,7 +4,11 @@ import {
fitSurfaceWidth,
getTransformOrigin,
holdSurfaceEdge,
isSameHostSurfacePosition,
isSameRect,
isSameSize,
surfaceFrameStyles,
toHostSurfacePosition,
type Rect,
} from "./anchor";
@@ -167,3 +171,49 @@ describe("fitSurfaceWidth", () => {
});
});
});
describe("toHostSurfacePosition", () => {
it("converts a top-placed surface to host-relative left and bottom coordinates", () => {
const hostRect: Rect = { x: 320, y: 0, width: 960, height: 800 };
const placed = position({
displayArea: { x: 0, y: 0, width: 1280, height: 800 },
triggerRect: { x: 1107, y: 743, width: 28, height: 28 },
contentSize: { width: 300, height: 90 },
placement: "top",
alignment: "center",
offset: 8,
});
expect(toHostSurfacePosition(placed, 90, hostRect)).toEqual({ left: 651, bottom: 65 });
});
it("converts a bottom-placed surface to host-relative left and top coordinates", () => {
const hostRect: Rect = { x: 320, y: 40, width: 960, height: 760 };
const placed = position({
displayArea: { x: 0, y: 0, width: 1280, height: 800 },
triggerRect: { x: 400, y: 100, width: 40, height: 20 },
contentSize: { width: 200, height: 100 },
placement: "bottom",
alignment: "start",
offset: 4,
});
expect(toHostSurfacePosition(placed, 100, hostRect)).toEqual({ left: 80, top: 84 });
});
});
describe("geometry equality helpers", () => {
it("compares host surface positions, rects, and sizes by value", () => {
expect(isSameHostSurfacePosition({ left: 10, bottom: 20 }, { left: 10, bottom: 20 })).toBe(
true,
);
expect(isSameHostSurfacePosition({ left: 10, bottom: 20 }, { left: 10, top: 20 })).toBe(false);
expect(isSameHostSurfacePosition(null, { left: 10, top: 20 })).toBe(false);
expect(isSameRect(TRIGGER, { ...TRIGGER })).toBe(true);
expect(isSameRect(TRIGGER, { ...TRIGGER, x: 101 })).toBe(false);
expect(isSameRect(null, null)).toBe(true);
expect(isSameRect(TRIGGER, null)).toBe(false);
expect(isSameSize(CONTENT, { ...CONTENT })).toBe(true);
expect(isSameSize(CONTENT, { ...CONTENT, width: 201 })).toBe(false);
});
});
@@ -0,0 +1,31 @@
export {
computePosition,
fitSurfaceWidth,
getTransformOrigin,
holdSurfaceEdge,
isSameHostSurfacePosition,
isSameRect,
isSameSize,
measureElement,
surfaceFrameStyles,
toHostSurfacePosition,
type Alignment,
type HostSurfacePosition,
type Placement,
type Rect,
type Size,
type SurfacePosition,
type SurfaceWidth,
} from "./internal/placement";
export {
readElementRectSync,
readViewportSize,
useAnchorLayoutObserver,
type AnchorLayoutObserverOptions,
type AnchorTarget,
} from "./internal/observe-layout";
export {
useAnchorGeometry,
type AnchorGeometry,
type UseAnchorGeometryOptions,
} from "./internal/use-anchor-geometry";
@@ -0,0 +1,103 @@
import { useEffect, useLayoutEffect, useRef, type RefObject } from "react";
import { Dimensions, type View } from "react-native";
import type { Rect, Size } from "./placement";
export type AnchorTarget = View | HTMLElement | null;
export interface AnchorLayoutObserverOptions {
/** Only observes while true (typically while the floating surface is open). */
enabled: boolean;
/** Element the surface is anchored to. */
anchorRef: RefObject<AnchorTarget>;
/**
* Optional host element whose origin defines the surface's coordinate frame (for example a
* portal overlay). Its size and layout ancestors are observed alongside the anchor.
*/
hostRef?: RefObject<AnchorTarget>;
/** Optional floating surface element whose own box resize triggers re-placement. */
surfaceRef?: RefObject<AnchorTarget>;
/** Called whenever layout changes may have moved the anchor, host, viewport, or surface. */
onLayoutChange: () => void;
/** Commit React state updates synchronously on web inside ResizeObserver (via flushSync). */
sync?: boolean;
}
export function readViewportSize(): Size {
const { width, height } = Dimensions.get("window");
return { width, height };
}
export function readElementRectSync(_element: AnchorTarget): Rect | null {
return null;
}
const NATIVE_ROTATION_SETTLE_DELAYS_MS = [120, 400] as const;
function scheduleNativeSettle(onSettle: () => void): () => void {
let raf1: number | null = null;
let raf2: number | null = null;
const timers: ReturnType<typeof setTimeout>[] = [];
const runSecondFrame = () => {
raf2 = null;
onSettle();
};
raf1 = requestAnimationFrame(() => {
raf1 = null;
onSettle();
raf2 = requestAnimationFrame(runSecondFrame);
});
for (const delayMs of NATIVE_ROTATION_SETTLE_DELAYS_MS) {
timers.push(setTimeout(onSettle, delayMs));
}
return () => {
if (raf1 !== null) cancelAnimationFrame(raf1);
if (raf2 !== null) cancelAnimationFrame(raf2);
for (const timer of timers) {
clearTimeout(timer);
}
};
}
/**
* Subscribes to layout changes that can move an anchored surface. Native listens for window
* dimension changes (orientation, split view); keyboard translation stays owned by
* `@/keyboard/shift`. The web companion observes DOM layout ancestors and element movement.
*
* On iOS, `Dimensions` emits before UIKit and Fabric finish laying out views in the new
* orientation, so measuring synchronously inside the event mixes the new viewport with the old
* trigger coordinates. Re-measuring across the next animation frames and after the rotation
* transition settles lets consumers converge cleanly without stale placement; consumers skip
* state updates when geometry is unchanged.
*/
export function useAnchorLayoutObserver({
enabled,
onLayoutChange,
}: AnchorLayoutObserverOptions): void {
const callbackRef = useRef(onLayoutChange);
useLayoutEffect(() => {
callbackRef.current = onLayoutChange;
});
useEffect(() => {
if (!enabled) return undefined;
let cancelPending: (() => void) | null = null;
const handleChange = () => {
cancelPending?.();
cancelPending = scheduleNativeSettle(() => {
callbackRef.current();
});
};
const subscription = Dimensions.addEventListener("change", handleChange);
return () => {
cancelPending?.();
subscription.remove();
};
}, [enabled]);
}
@@ -0,0 +1,310 @@
import { useLayoutEffect, useRef } from "react";
import { flushSync } from "react-dom";
import { Dimensions } from "react-native";
import type { AnchorLayoutObserverOptions, AnchorTarget } from "./observe-layout";
import type { Rect, Size } from "./placement";
function asHtmlElement(target: AnchorTarget): HTMLElement | null {
if (!target || typeof HTMLElement === "undefined") return null;
return target instanceof HTMLElement ? target : null;
}
export function readViewportSize(): Size {
if (typeof window !== "undefined") {
return { width: window.innerWidth, height: window.innerHeight };
}
const { width, height } = Dimensions.get("window");
return { width, height };
}
export function readElementRectSync(target: AnchorTarget): Rect | null {
const element = asHtmlElement(target);
if (!element || !element.isConnected) return null;
const { x, y, width, height } = element.getBoundingClientRect();
return { x, y, width, height };
}
function collectBoxAndAncestors(targets: Set<Element>, element: HTMLElement | null): void {
let current: Element | null = element;
while (current) {
targets.add(current);
current = current.parentElement;
}
}
const MOVE_EPSILON_PX = 0.5;
const CLIPPED_RATIO_EPSILON = 0.001;
const MIN_VISIBLE_THRESHOLD = 1e-7;
interface ClippedArmOptions {
ratio: number;
relaxTop: boolean;
relaxRight: boolean;
relaxBottom: boolean;
relaxLeft: boolean;
}
interface MoveArmConfig {
slack: number;
clipped?: ClippedArmOptions;
}
function buildClippedThreshold(ratio: number): number[] {
if (ratio <= 0) return [MIN_VISIBLE_THRESHOLD];
const lower = Math.max(MIN_VISIBLE_THRESHOLD, ratio - CLIPPED_RATIO_EPSILON);
const upper = Math.min(1, ratio + CLIPPED_RATIO_EPSILON);
return lower === upper ? [lower] : [lower, upper];
}
function detectClippedEdges(entry: IntersectionObserverEntry, rect: DOMRect): ClippedArmOptions {
const ir = entry.intersectionRect;
const ratio = entry.intersectionRatio;
if (ratio <= 0 || ir.width <= 0 || ir.height <= 0) {
return {
ratio: 0,
relaxTop: true,
relaxRight: true,
relaxBottom: true,
relaxLeft: true,
};
}
const clippedTop = ir.top > rect.top + MOVE_EPSILON_PX;
const clippedRight = ir.right < rect.right - MOVE_EPSILON_PX;
const clippedBottom = ir.bottom < rect.bottom - MOVE_EPSILON_PX;
const clippedLeft = ir.left > rect.left + MOVE_EPSILON_PX;
// Relax the inset opposite each clipped edge so movement out of the clip increases
// intersectionRatio above the upper threshold while movement deeper into the clip drops it.
return {
ratio,
relaxTop: clippedBottom,
relaxRight: clippedLeft,
relaxBottom: clippedTop,
relaxLeft: clippedRight,
};
}
/**
* Watches for visual position shifts of `element` that happen without any ancestor resizing
* (for example, a sibling button mounting inside a fixed-width flex row or a CSS transform).
* Uses a viewport-clipped IntersectionObserver tightly boxed around the element's current rect,
* re-armed on the next animation frame whenever the element moves. Partly clipped triggers stay
* watched by bracketing their visible intersectionRatio and relaxing the inset opposite clipped
* edges.
*/
function observeElementMove(
element: HTMLElement,
onMove: () => void,
): { rearm: (knownRect?: { x: number; y: number } | null) => void; dispose: () => void } {
if (typeof IntersectionObserver === "undefined" || typeof document === "undefined") {
return { rearm: () => {}, dispose: () => {} };
}
let io: IntersectionObserver | null = null;
let rearmFrame: number | null = null;
let disposed = false;
let lastKnownRect: { x: number; y: number } | null = null;
const hasMovedFrom = (prev: { x: number; y: number } | null, next: DOMRect): boolean => {
if (!prev) return false;
return (
Math.abs(next.x - prev.x) >= MOVE_EPSILON_PX || Math.abs(next.y - prev.y) >= MOVE_EPSILON_PX
);
};
const cleanupObserver = () => {
io?.disconnect();
io = null;
if (rearmFrame !== null) {
cancelAnimationFrame(rearmFrame);
rearmFrame = null;
}
};
const scheduleArm = (config: MoveArmConfig = { slack: 0 }) => {
if (disposed) return;
if (rearmFrame !== null) {
cancelAnimationFrame(rearmFrame);
}
rearmFrame = requestAnimationFrame(() => {
rearmFrame = null;
arm(config);
});
};
const arm = (config: MoveArmConfig = { slack: 0 }) => {
if (disposed || !element.isConnected) return;
cleanupObserver();
const root = document.documentElement;
const rect = element.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
// Catch moves that occurred while the observer was re-arming between frames.
if (hasMovedFrom(lastKnownRect, rect)) {
lastKnownRect = { x: rect.x, y: rect.y };
onMove();
} else {
lastKnownRect = { x: rect.x, y: rect.y };
}
const { slack, clipped } = config;
const insetTop = clipped?.relaxTop ? 0 : Math.max(0, Math.floor(rect.top) - slack);
const insetLeft = clipped?.relaxLeft ? 0 : Math.max(0, Math.floor(rect.left) - slack);
const insetRight = clipped?.relaxRight
? 0
: Math.max(0, Math.floor(root.clientWidth - rect.right) - slack);
const insetBottom = clipped?.relaxBottom
? 0
: Math.max(0, Math.floor(root.clientHeight - rect.bottom) - slack);
const rootMargin =
clipped && clipped.ratio <= 0
? "0px"
: `${-insetTop}px ${-insetRight}px ${-insetBottom}px ${-insetLeft}px`;
const threshold = clipped ? buildClippedThreshold(clipped.ratio) : 1;
const armedRect = { x: rect.x, y: rect.y };
let firstRun = true;
io = new IntersectionObserver(
(entries) => {
if (disposed) return;
const entry = entries[0];
const ratio = entry?.intersectionRatio ?? 1;
if (firstRun) {
firstRun = false;
if (!clipped && ratio < 1) {
io?.disconnect();
io = null;
if (slack === 0) {
// Sub-pixel coordinates can produce ratio < 1 at slack 0; retry once with 1px slack.
scheduleArm({ slack: 1 });
} else if (entry) {
// Genuinely clipped by a scroll container or viewport edge: bracket the visible ratio.
scheduleArm({ slack: 1, clipped: detectClippedEdges(entry, rect) });
}
}
return;
}
const nextRect = element.getBoundingClientRect();
const moved = hasMovedFrom(armedRect, nextRect);
lastKnownRect = { x: nextRect.x, y: nextRect.y };
io?.disconnect();
io = null;
if (moved) {
onMove();
}
scheduleArm({ slack: 0 });
},
{ root: document, rootMargin, threshold },
);
io.observe(element);
};
arm({ slack: 0 });
return {
rearm: (knownRect?: { x: number; y: number } | null) => {
if (disposed) return;
if (knownRect) {
lastKnownRect = knownRect;
} else if (element.isConnected) {
const rect = element.getBoundingClientRect();
lastKnownRect = { x: rect.x, y: rect.y };
}
io?.disconnect();
io = null;
scheduleArm({ slack: 0 });
},
dispose: () => {
disposed = true;
cleanupObserver();
},
};
}
/**
* Observes every DOM layout source that can change an anchored surface's placement:
* - `ResizeObserver` over `anchor`, `anchor` ancestors, `host`, `host` ancestors, and `surface`
* (runs after layout and before paint, so `sync: true` paints the new position with 0-frame lag),
* - `IntersectionObserver` move detection on `anchor` for sibling/transform shifts inside
* fixed-size containers,
* - `window` and `visualViewport` resize events.
*/
export function useAnchorLayoutObserver({
enabled,
anchorRef,
hostRef,
surfaceRef,
onLayoutChange,
sync = false,
}: AnchorLayoutObserverOptions): void {
const callbackRef = useRef(onLayoutChange);
useLayoutEffect(() => {
callbackRef.current = onLayoutChange;
});
useLayoutEffect(() => {
if (!enabled || typeof window === "undefined") return undefined;
const anchor = asHtmlElement(anchorRef.current);
const host = hostRef ? asHtmlElement(hostRef.current) : null;
const surface = surfaceRef ? asHtmlElement(surfaceRef.current) : null;
let flushing = false;
const notify = (useFlushSync: boolean) => {
if (useFlushSync && !flushing) {
flushing = true;
try {
flushSync(() => callbackRef.current());
} finally {
flushing = false;
}
} else {
callbackRef.current();
}
};
const moveObserver = anchor
? observeElementMove(anchor, () => {
notify(false);
})
: undefined;
let resizeObserver: ResizeObserver | null = null;
if (typeof ResizeObserver !== "undefined") {
const targets = new Set<Element>();
collectBoxAndAncestors(targets, anchor);
collectBoxAndAncestors(targets, host);
if (surface) targets.add(surface);
if (targets.size === 0 && typeof document !== "undefined" && document.documentElement) {
targets.add(document.documentElement);
}
resizeObserver = new ResizeObserver(() => {
// Read anchor's clean post-layout rect BEFORE notify(sync) mutates surface inline styles,
// avoiding a forced second layout recalc on the same frame.
const preFlushRect = anchor?.isConnected ? anchor.getBoundingClientRect() : null;
notify(sync);
moveObserver?.rearm(preFlushRect ? { x: preFlushRect.x, y: preFlushRect.y } : null);
});
for (const target of targets) {
resizeObserver.observe(target);
}
}
const handleViewportResize = () => {
notify(false);
moveObserver?.rearm();
};
window.addEventListener("resize", handleViewportResize);
window.visualViewport?.addEventListener("resize", handleViewportResize);
return () => {
resizeObserver?.disconnect();
moveObserver?.dispose();
window.removeEventListener("resize", handleViewportResize);
window.visualViewport?.removeEventListener("resize", handleViewportResize);
};
}, [anchorRef, enabled, hostRef, surfaceRef, sync]);
}
@@ -1,4 +1,5 @@
import type { View, ViewStyle } from "react-native";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
/**
* Where a floating surface goes relative to the thing that opened it. Menus, hover cards, and
@@ -31,6 +32,18 @@ export function measureElement(element: View): Promise<Rect> {
});
}
export function isSameRect(a: Rect | null, b: Rect | null): boolean {
if (a === b) return true;
if (!a || !b) return false;
return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
}
export function isSameSize(a: Size | null, b: Size | null): boolean {
if (a === b) return true;
if (!a || !b) return false;
return a.width === b.width && a.height === b.height;
}
/**
* A surface asked to open below the trigger flips above it when it doesn't fit below *and*
* there is more room above. Both conditions matter: flipping into a side that is equally
@@ -181,6 +194,35 @@ export function computePosition({
/** Where a placed surface sits: its left edge, and the edge that holds it vertically. */
export type SurfacePosition = { left: number; top: number } | { left: number; bottomEdge: number };
/**
* Where a placed surface sits directly inside a host container (such as a portal overlay whose
* origin may be offset from the window). A surface above its trigger holds its bottom edge so
* content that loads while open grows upward without shifting over the trigger.
*/
export type HostSurfacePosition = { left: number; top: number } | { left: number; bottom: number };
export function toHostSurfacePosition(
placed: { x: number; y: number; actualPlacement: Placement },
contentHeight: number,
hostRect: Rect,
): HostSurfacePosition {
const left = placed.x - hostRect.x;
if (placed.actualPlacement === "top") {
return { left, bottom: hostRect.height - (placed.y + contentHeight - hostRect.y) };
}
return { left, top: placed.y - hostRect.y };
}
export function isSameHostSurfacePosition(
current: HostSurfacePosition | null,
next: HostSurfacePosition,
): boolean {
if (!current || current.left !== next.left) return false;
return "top" in current
? "top" in next && current.top === next.top
: "bottom" in next && current.bottom === next.bottom;
}
/**
* A surface above its trigger is held by its bottom edge, the edge that faces the trigger. When
* its content grows after it paints, it extends upward, away from the trigger. Held by its top,
@@ -211,18 +253,18 @@ export function surfaceFrameStyles(position: SurfacePosition | null): {
const fill: ViewStyle = { position: "absolute", top: 0, left: 0, right: 0 };
if (!position) {
return {
holder: { ...fill, bottom: 0 },
holder: inlineUnistylesStyle({ ...fill, bottom: 0 }),
surface: { position: "absolute", top: -9999, left: -9999 },
};
}
if ("top" in position) {
return {
holder: { ...fill, bottom: 0 },
holder: inlineUnistylesStyle({ ...fill, bottom: 0 }),
surface: { position: "absolute", top: position.top, left: position.left },
};
}
return {
holder: { ...fill, height: position.bottomEdge },
holder: inlineUnistylesStyle({ ...fill, height: position.bottomEdge }),
surface: { position: "absolute", bottom: 0, left: position.left },
};
}
@@ -0,0 +1,98 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import {
type AnchorTarget,
readElementRectSync,
readViewportSize,
useAnchorLayoutObserver,
} from "./observe-layout";
import { isSameRect, isSameSize, measureElement, type Rect, type Size } from "./placement";
export interface UseAnchorGeometryOptions {
/** Only measures and observes while true (typically while the floating surface is open). */
enabled: boolean;
/** Anchor element ref measured when `anchorRect` is not explicitly provided. */
anchorRef: RefObject<AnchorTarget>;
/** Explicit anchor rect (for example a pointer context-menu point). Skips DOM/native measurement. */
anchorRect?: Rect | null;
/** Commit React state updates synchronously on web inside ResizeObserver (via flushSync). */
sync?: boolean;
}
export interface AnchorGeometry {
triggerRect: Rect | null;
viewport: Size;
}
/**
* Owns measuring and live-tracking viewport-space geometry for an anchored floating surface.
* Handles sync web reads, async native `measureInWindow` fallback with stale-request cancellation,
* 0x0 hidden-element filtering, and layout observation across resizes and orientation changes.
*/
export function useAnchorGeometry({
enabled,
anchorRef,
anchorRect = null,
sync = true,
}: UseAnchorGeometryOptions): AnchorGeometry {
const [triggerRect, setTriggerRect] = useState<Rect | null>(null);
const [viewport, setViewport] = useState<Size>(readViewportSize);
const enabledRef = useRef(enabled);
const requestIdRef = useRef(0);
enabledRef.current = enabled;
const measureCurrent = useCallback(() => {
if (!enabledRef.current) return;
const nextViewport = readViewportSize();
setViewport((current) => (isSameSize(current, nextViewport) ? current : nextViewport));
if (anchorRect) {
setTriggerRect((current) => (isSameRect(current, anchorRect) ? current : anchorRect));
return;
}
const anchor = anchorRef.current;
if (!anchor) {
setTriggerRect(null);
return;
}
const syncRect = readElementRectSync(anchor);
if (syncRect) {
if (syncRect.width === 0 && syncRect.height === 0) return;
requestIdRef.current += 1;
setTriggerRect((current) => (isSameRect(current, syncRect) ? current : syncRect));
return;
}
if (!("measureInWindow" in anchor)) return;
const requestId = requestIdRef.current + 1;
requestIdRef.current = requestId;
void measureElement(anchor).then((rect) => {
if (!enabledRef.current || requestIdRef.current !== requestId) return undefined;
if (rect.width === 0 && rect.height === 0) return undefined;
setTriggerRect((current) => (isSameRect(current, rect) ? current : rect));
return undefined;
});
}, [anchorRect, anchorRef]);
useEffect(() => {
if (!enabled) {
requestIdRef.current += 1;
setTriggerRect(null);
return undefined;
}
measureCurrent();
return () => {
requestIdRef.current += 1;
};
}, [enabled, measureCurrent]);
useAnchorLayoutObserver({
enabled,
anchorRef,
onLayoutChange: measureCurrent,
sync,
});
return { triggerRect, viewport };
}
@@ -1,8 +1,8 @@
import { useLayoutEffect, useRef, useState, type ReactElement } from "react";
import { flushSync } from "react-dom";
import { useCallback, useLayoutEffect, useRef, useState, type ReactElement } from "react";
import { View } from "react-native";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useAnchorLayoutObserver } from "@/components/ui/anchor";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { placeAboveAnchor, type AnchorAtRest, type PopoverFrameProps } from "./placement";
type AnchorRect = Omit<AnchorAtRest, "height">;
@@ -18,10 +18,19 @@ function rectWithin(anchor: HTMLElement, host: HTMLElement): AnchorRect {
};
}
function isSameAnchorRect(current: AnchorRect, next: AnchorRect): boolean {
return (
current.x === next.x &&
current.y === next.y &&
current.width === next.width &&
current.hostHeight === next.hostHeight
);
}
/**
* The composer resizes as its text wraps and as the window resizes. ResizeObserver callbacks run
* after layout and before paint, so committing the new placement synchronously there paints the
* popover against the composer's new rect in the same frame.
* The composer moves as its text wraps, sidebars toggle or resize, and the window resizes.
* `useAnchorLayoutObserver` with `sync: true` runs after layout and before paint, so the popover
* repaints against the composer's new rect in the same frame.
*/
export function PopoverFrame({
anchorRef,
@@ -37,19 +46,24 @@ export function PopoverFrame({
const frameRef = useRef<View>(null);
const [anchor, setAnchor] = useState<AnchorRect>(anchorAtRest);
useLayoutEffect(() => {
const syncAnchor = useCallback(() => {
const anchorElement = anchorRef.current as unknown as HTMLElement | null;
// The frame's parent is the portal layer, which covers the host.
const host = (frameRef.current as unknown as HTMLElement | null)?.parentElement;
if (!anchorElement || !host) return undefined;
setAnchor(rectWithin(anchorElement, host));
const observer = new ResizeObserver(() => {
flushSync(() => setAnchor(rectWithin(anchorElement, host)));
});
observer.observe(anchorElement);
observer.observe(host);
return () => observer.disconnect();
}, [anchorAtRest, anchorRef]);
if (!anchorElement || !host) return;
const next = rectWithin(anchorElement, host);
setAnchor((current) => (isSameAnchorRect(current, next) ? current : next));
}, [anchorRef]);
useLayoutEffect(syncAnchor, [anchorAtRest, syncAnchor]);
useAnchorLayoutObserver({
enabled: true,
anchorRef,
hostRef: frameRef,
onLayoutChange: syncAnchor,
sync: true,
});
const style = inlineUnistylesStyle({
position: "absolute" as const,
+98 -25
View File
@@ -63,6 +63,11 @@ import {
type SheetKeyboard,
} from "@/components/adaptive-modal-sheet";
import { FloatingSurface } from "@/components/ui/floating";
import {
readElementRectSync,
readViewportSize,
useAnchorLayoutObserver,
} from "@/components/ui/anchor";
import { useDismissKeyboardOnOpen } from "@/components/ui/keyboard-dismiss";
import { useDismissibleOverlay } from "@/components/ui/overlay-dismissal";
import { getOverlayRoot, OverlayLayerProvider, useOverlayLayer } from "@/lib/overlay-root";
@@ -805,48 +810,104 @@ function useAnchorMeasure(
searchQuery: string,
windowHeight: number,
setters: MeasuredAnchorSetters,
onLayoutUpdate: () => void,
) {
const { setReferenceLeft, setReferenceTop, setReferenceWidth, setReferenceAtOrigin } = setters;
const enabled = isOpen && !isMobile;
const lastGeometryRef = useRef<{
x: number;
y: number;
width: number;
viewportWidth: number;
viewportHeight: number;
} | null>(null);
const measureNow = useCallback((): boolean => {
const referenceEl = anchorRef.current;
if (!referenceEl) return false;
const viewport = readViewportSize();
const syncRect = readElementRectSync(referenceEl);
if (syncRect) {
if (syncRect.width === 0 && syncRect.height === 0) return false;
const prev = lastGeometryRef.current;
const changed =
!prev ||
prev.x !== syncRect.x ||
prev.y !== syncRect.y ||
prev.width !== syncRect.width ||
prev.viewportWidth !== viewport.width ||
prev.viewportHeight !== viewport.height;
if (!changed) return false;
lastGeometryRef.current = {
x: syncRect.x,
y: syncRect.y,
width: syncRect.width,
viewportWidth: viewport.width,
viewportHeight: viewport.height,
};
applyMeasuredAnchor(
{ setReferenceLeft, setReferenceTop, setReferenceWidth, setReferenceAtOrigin },
syncRect.x,
syncRect.y,
syncRect.width,
);
return true;
}
referenceEl.measureInWindow((x, y, width) => {
applyMeasuredAnchor(
{ setReferenceLeft, setReferenceTop, setReferenceWidth, setReferenceAtOrigin },
x,
y,
width,
);
});
return true;
}, [anchorRef, setReferenceLeft, setReferenceTop, setReferenceWidth, setReferenceAtOrigin]);
useEffect(() => {
if (!isOpen || isMobile) {
if (!enabled) {
lastGeometryRef.current = null;
setReferenceLeft(null);
setReferenceAtOrigin(false);
setReferenceTop(null);
return;
}
const referenceEl = anchorRef.current;
if (!referenceEl) {
if (!anchorRef.current) {
lastGeometryRef.current = null;
setReferenceAtOrigin(false);
setReferenceTop(null);
return;
}
const measure = () => {
referenceEl.measureInWindow((x, y, width) => {
applyMeasuredAnchor(
{ setReferenceLeft, setReferenceTop, setReferenceWidth, setReferenceAtOrigin },
x,
y,
width,
);
});
};
measure();
const raf = requestAnimationFrame(measure);
measureNow();
const raf = requestAnimationFrame(() => {
measureNow();
});
return () => cancelAnimationFrame(raf);
}, [
anchorRef,
isMobile,
isOpen,
enabled,
measureNow,
searchQuery,
windowHeight,
setReferenceLeft,
setReferenceTop,
setReferenceWidth,
setReferenceAtOrigin,
]);
const handleLayoutChange = useCallback(() => {
if (measureNow()) {
onLayoutUpdate();
}
}, [measureNow, onLayoutUpdate]);
useAnchorLayoutObserver({
enabled,
anchorRef,
onLayoutChange: handleLayoutChange,
sync: false,
});
}
function applySetOpen(
@@ -1542,12 +1603,24 @@ export function Combobox({
setReferenceWidth,
});
useAnchorMeasure(isOpen, isMobile, anchorRef, searchQuery, windowHeight, {
setReferenceLeft,
setReferenceTop,
setReferenceWidth,
setReferenceAtOrigin,
});
const handleAnchorLayoutUpdate = useCallback(() => {
void update();
}, [update]);
useAnchorMeasure(
isOpen,
isMobile,
anchorRef,
searchQuery,
windowHeight,
{
setReferenceLeft,
setReferenceTop,
setReferenceWidth,
setReferenceAtOrigin,
},
handleAnchorLayoutUpdate,
);
const floatingTop = toNumericStyleValue(floatingStyles.top);
const floatingLeft = toNumericStyleValue(floatingStyles.left);
+54 -37
View File
@@ -12,7 +12,7 @@ import {
type ReactNode,
type RefObject,
} from "react";
import { Dimensions, View, type Role, type StyleProp, type ViewStyle } from "react-native";
import { View, type Role, type StyleProp, type ViewStyle } from "react-native";
import { FadeIn, FadeOut } from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import { Portal } from "@gorhom/portal";
@@ -21,7 +21,17 @@ import { FloatingSurface } from "@/components/ui/floating";
import { useFloatingPanelPortalHostName } from "@/components/ui/floating-panel-portal";
import { isWeb } from "@/constants/platform";
import { useHoverSafeZone } from "@/hooks/use-hover-safe-zone";
import { computePosition, type Alignment, type Placement, type Rect } from "./anchor";
import {
computePosition,
isSameHostSurfacePosition,
readElementRectSync,
readViewportSize,
toHostSurfacePosition,
useAnchorLayoutObserver,
type Alignment,
type HostSurfacePosition,
type Placement,
} from "./anchor";
const CLOSE_GRACE_MS = 100;
@@ -225,13 +235,11 @@ function WebHoverCard({
document.addEventListener("focusout", focusLeft);
trigger.addEventListener("keydown", activateClosedTrigger);
document.addEventListener("scroll", scrolled, true);
window.addEventListener("resize", close);
return () => {
document.removeEventListener("focusin", focusEntered);
document.removeEventListener("focusout", focusLeft);
trigger.removeEventListener("keydown", activateClosedTrigger);
document.removeEventListener("scroll", scrolled, true);
window.removeEventListener("resize", close);
};
}, [clearGraceTimer, keyPressed, open, openNow, scheduleClose]);
@@ -327,24 +335,6 @@ export function HoverCardContent(props: HoverCardContentProps): ReactElement | n
);
}
// A card above its trigger holds its bottom edge, so content that loads while it is open grows it
// upward without a correction. Anchored by its top, it would paint over the trigger until placed.
type CardPosition = { left: number; top: number } | { left: number; bottom: number };
function isSamePosition(current: CardPosition | null, next: CardPosition): boolean {
if (!current || current.left !== next.left) return false;
return "top" in current
? "top" in next && current.top === next.top
: "bottom" in next && current.bottom === next.bottom;
}
function readDomRect(view: View | null): Rect | null {
const element = view as unknown as HTMLElement | null;
if (!element) return null;
const { x, y, width, height } = element.getBoundingClientRect();
return { x, y, width, height };
}
// Rendered inside the portal so the card is placed in the commit that mounts it: the first
// painted frame already sits beside the trigger. Web-only, like the rest of the open card.
function HoverCardSurface({
@@ -365,15 +355,38 @@ function HoverCardSurface({
contentRef: RefObject<View | null>;
}): ReactElement {
const overlayRef = useRef<View>(null);
const [position, setPosition] = useState<CardPosition | null>(null);
const surfaceRef = useRef<View>(null);
const [position, setPosition] = useState<HostSurfacePosition | null>(null);
const setSurfaceRef = useCallback(
(node: View | null) => {
const previous = surfaceRef.current;
surfaceRef.current = node;
if (node) {
contentRef.current = node;
} else if (contentRef.current === previous) {
contentRef.current = null;
}
},
[contentRef],
);
const place = useCallback(() => {
const triggerRect = readDomRect(triggerRef.current);
const overlayRect = readDomRect(overlayRef.current);
const content = contentRef.current as unknown as HTMLElement | null;
const triggerRect = readElementRectSync(triggerRef.current);
const overlayRect = readElementRectSync(overlayRef.current);
const content = surfaceRef.current as unknown as HTMLElement | null;
if (!triggerRect || !overlayRect || !content) return;
const { width, height } = Dimensions.get("window");
const { x, y, actualPlacement } = computePosition({
if (
(triggerRect.width === 0 && triggerRect.height === 0) ||
overlayRect.width === 0 ||
overlayRect.height === 0 ||
content.offsetWidth === 0 ||
content.offsetHeight === 0
) {
return;
}
const { width, height } = readViewportSize();
const placed = computePosition({
triggerRect,
contentSize: { width: content.offsetWidth, height: content.offsetHeight },
displayArea: { x: 0, y: 0, width, height },
@@ -382,16 +395,21 @@ function HoverCardSurface({
alignment,
offset,
});
const left = x - overlayRect.x;
const next: CardPosition =
actualPlacement === "top"
? { left, bottom: overlayRect.height - (y + content.offsetHeight - overlayRect.y) }
: { left, top: y - overlayRect.y };
setPosition((current) => (isSamePosition(current, next) ? current : next));
}, [alignment, contentRef, offset, placement, triggerRef]);
const next = toHostSurfacePosition(placed, content.offsetHeight, overlayRect);
setPosition((current) => (isSameHostSurfacePosition(current, next) ? current : next));
}, [alignment, offset, placement, triggerRef]);
useLayoutEffect(place, [place]);
useAnchorLayoutObserver({
enabled: true,
anchorRef: triggerRef,
hostRef: overlayRef,
surfaceRef,
onLayoutChange: place,
sync: true,
});
const frameStyle = useMemo(
() => ({ position: "absolute" as const, ...(position ?? { top: -9999, left: -9999 }) }),
[position],
@@ -405,11 +423,10 @@ function HoverCardSurface({
style={[styles.portalOverlay, { zIndex: layer }]}
>
<FloatingSurface
ref={contentRef}
ref={setSurfaceRef}
entering={FadeIn.duration(80)}
exiting={FadeOut.duration(80)}
collapsable={false}
onLayout={place}
role={role}
accessibilityLabel={accessibilityLabel}
testID={testID}
@@ -7,7 +7,6 @@ import {
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
type ReactElement,
type RefObject,
@@ -15,7 +14,6 @@ import {
import { createPortal } from "react-dom";
import { useTranslation } from "react-i18next";
import {
Dimensions,
Platform,
Pressable,
View,
@@ -34,13 +32,12 @@ import {
fitSurfaceWidth,
getTransformOrigin,
holdSurfaceEdge,
measureElement,
surfaceFrameStyles,
useAnchorGeometry,
type Alignment,
type Placement,
type Rect,
type Size,
type SurfacePosition,
} from "../anchor";
const SCROLL_CONTENT_STYLE = { flexGrow: 1 } as const;
@@ -119,18 +116,20 @@ export function useAnchoredPosition({
*/
flipHorizontal?: boolean;
}) {
const [triggerRect, setTriggerRect] = useState<Rect | null>(null);
const [contentSize, setContentSize] = useState<Size | null>(null);
const [position, setPosition] = useState<SurfacePosition | null>(null);
const [actualPlacement, setActualPlacement] = useState<Placement>(side);
const heldSideRef = useRef<Placement | null>(null);
const [heldSide, setHeldSide] = useState<Placement | null>(null);
const { triggerRect, viewport: viewportSize } = useAnchorGeometry({
enabled: open,
anchorRef,
anchorRect,
sync: true,
});
const visibleContentSize = useMemo(() => {
if (!contentSize) return null;
if (!scrollable) return contentSize;
const { height: screenHeight } = Dimensions.get("window");
const viewportMaxHeight = Math.max(screenHeight - 16, 0);
const viewportMaxHeight = Math.max(viewportSize.height - 16, 0);
const resolvedMaxHeight =
typeof maxHeight === "number" ? Math.min(maxHeight, viewportMaxHeight) : viewportMaxHeight;
@@ -138,62 +137,52 @@ export function useAnchoredPosition({
width: contentSize.width,
height: Math.min(contentSize.height, resolvedMaxHeight),
};
}, [contentSize, scrollable, maxHeight]);
}, [contentSize, scrollable, maxHeight, viewportSize.height]);
useEffect(() => {
if (!open) {
setTriggerRect(null);
setContentSize(null);
setPosition(null);
heldSideRef.current = null;
return undefined;
setHeldSide(null);
}
}, [open]);
if (anchorRect) {
setTriggerRect(anchorRect);
return undefined;
}
if (!anchorRef.current) {
setTriggerRect(null);
return undefined;
}
let cancelled = false;
// The app draws edge-to-edge, so measureInWindow and the full-screen Modal share one
// coordinate space that starts at the screen top; no status bar offset applies.
void measureElement(anchorRef.current).then((rect) => {
if (cancelled) return undefined;
setTriggerRect(rect);
return undefined;
});
return () => {
cancelled = true;
};
}, [anchorRect, anchorRef, open]);
useEffect(() => {
if (!triggerRect || !visibleContentSize) return;
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
const placementResult = useMemo(() => {
if (!triggerRect || !visibleContentSize) return null;
// measureInWindow and Modal both use full-screen coordinates, so the display area starts at 0.
const heldSide = heldSideRef.current;
const result = computePosition({
triggerRect,
contentSize: visibleContentSize,
displayArea: { x: 0, y: 0, width: screenWidth, height: screenHeight },
displayArea: { x: 0, y: 0, width: viewportSize.width, height: viewportSize.height },
placement: heldSide ?? side,
alignment: align,
offset,
flipHorizontal: flipHorizontal && heldSide === null,
});
if (flipHorizontal) heldSideRef.current = result.actualPlacement;
return {
position: holdSurfaceEdge(result, visibleContentSize.height),
actualPlacement: result.actualPlacement,
};
}, [
triggerRect,
visibleContentSize,
viewportSize.width,
viewportSize.height,
heldSide,
side,
align,
offset,
flipHorizontal,
]);
setPosition(holdSurfaceEdge(result, visibleContentSize.height));
setActualPlacement(result.actualPlacement);
}, [triggerRect, visibleContentSize, side, align, offset, flipHorizontal]);
// Lock the flyout side once after initial placement so content growth cannot jump across the pointer.
useLayoutEffect(() => {
if (flipHorizontal && heldSide === null && placementResult) {
setHeldSide(placementResult.actualPlacement);
}
}, [flipHorizontal, heldSide, placementResult]);
const position = placementResult?.position ?? null;
const actualPlacement = placementResult?.actualPlacement ?? side;
const onContentLayout = useCallback(
(event: { nativeEvent: { layout: { width: number; height: number } } }) => {
@@ -206,7 +195,14 @@ export function useAnchoredPosition({
[],
);
return { position, actualPlacement, contentSize, visibleContentSize, onContentLayout };
return {
position,
actualPlacement,
contentSize,
visibleContentSize,
viewportWidth: viewportSize.width,
onContentLayout,
};
}
export interface AnchoredSurfaceProps {
@@ -270,17 +266,18 @@ export function AnchoredSurface({
}: AnchoredSurfaceProps): ReactElement | null {
const { t } = useTranslation();
const surfaceNativeID = useId();
const { position, actualPlacement, visibleContentSize, onContentLayout } = useAnchoredPosition({
open,
anchorRect,
anchorRef,
side,
align,
offset,
scrollable,
maxHeight,
flipHorizontal,
});
const { position, actualPlacement, visibleContentSize, viewportWidth, onContentLayout } =
useAnchoredPosition({
open,
anchorRect,
anchorRef,
side,
align,
offset,
scrollable,
maxHeight,
flipHorizontal,
});
// The surface is placed once both measurements land. Until then it sits off-screen so it can
// be measured, and it must not animate: an entering animation that ran there would be over
@@ -303,10 +300,9 @@ export function AnchoredSurface({
const frame = useMemo(() => surfaceFrameStyles(position), [position]);
const frameStyle = useMemo<StyleProp<ViewStyle>>(() => {
const { width: screenWidth } = Dimensions.get("window");
const resolvedWidthStyle: ViewStyle = fullWidth
? { width: screenWidth - horizontalPadding * 2 }
: fitSurfaceWidth({ width, minWidth, maxWidth }, screenWidth);
? { width: viewportWidth - horizontalPadding * 2 }
: fitSurfaceWidth({ width, minWidth, maxWidth }, viewportWidth);
return [
resolvedWidthStyle,
frame.surface,
@@ -321,6 +317,7 @@ export function AnchoredSurface({
width,
minWidth,
maxWidth,
viewportWidth,
frame.surface,
actualPlacement,
align,
+21 -45
View File
@@ -15,7 +15,6 @@ import {
} from "react";
import { createPortal } from "react-dom";
import {
Dimensions,
Platform,
Pressable,
View,
@@ -30,7 +29,12 @@ import { FloatingSurface } from "@/components/ui/floating";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { isNative, isWeb } from "@/constants/platform";
import { getOverlayRoot, OVERLAY_Z } from "@/lib/overlay-root";
import { holdSurfaceEdge, surfaceFrameStyles, type SurfacePosition } from "./anchor";
import {
holdSurfaceEdge,
surfaceFrameStyles,
useAnchorGeometry,
type SurfacePosition,
} from "./anchor";
type Side = "top" | "bottom" | "left" | "right";
type Align = "start" | "center" | "end";
@@ -123,21 +127,6 @@ function useControllableOpenState({
return [value, setValue];
}
function measureElement(element: TooltipTriggerElement): Promise<Rect> {
if (isWeb && element instanceof HTMLElement) {
const { x, y, width, height } = element.getBoundingClientRect();
return Promise.resolve({ x, y, width, height });
}
if ("measureInWindow" in element) {
return new Promise((resolve) => {
element.measureInWindow((x, y, width, height) => {
resolve({ x, y, width, height });
});
});
}
throw new Error("A DOM tooltip trigger requires the web platform");
}
function resolveActualSide(args: {
triggerRect: Rect;
contentSize: { width: number; height: number };
@@ -474,34 +463,23 @@ export function TooltipContent({
maxWidth?: number;
}>): ReactElement | null {
const ctx = useTooltipContext("TooltipContent");
const [triggerRect, setTriggerRect] = useState<Rect | null>(null);
const [contentSize, setContentSize] = useState<{ width: number; height: number } | null>(null);
const [position, setPosition] = useState<SurfacePosition | null>(null);
const isActive = ctx.open && ctx.enabled;
const { triggerRect, viewport: viewportSize } = useAnchorGeometry({
enabled: isActive,
anchorRef: ctx.triggerRef,
sync: true,
});
useEffect(() => {
if (!ctx.open || !ctx.enabled || !ctx.triggerRef.current) {
setTriggerRect(null);
if (!isActive) {
setContentSize(null);
setPosition(null);
return () => {};
}
}, [isActive]);
let cancelled = false;
void measureElement(ctx.triggerRef.current).then((rect) => {
if (!cancelled) setTriggerRect(rect);
return undefined;
});
return () => {
cancelled = true;
};
}, [ctx.enabled, ctx.open, ctx.triggerRef]);
useEffect(() => {
if (!triggerRect || !contentSize) return;
const { width: screenWidth, height: screenHeight } = Dimensions.get("window");
const displayArea = { x: 0, y: 0, width: screenWidth, height: screenHeight };
const position = useMemo<SurfacePosition | null>(() => {
if (!triggerRect || !contentSize) return null;
const displayArea = { x: 0, y: 0, width: viewportSize.width, height: viewportSize.height };
const result = computePosition({
triggerRect,
contentSize,
@@ -510,13 +488,11 @@ export function TooltipContent({
align,
offset,
});
setPosition(
holdSurfaceEdge(
{ x: result.x, y: result.y, actualPlacement: result.actualSide },
contentSize.height,
),
return holdSurfaceEdge(
{ x: result.x, y: result.y, actualPlacement: result.actualSide },
contentSize.height,
);
}, [triggerRect, contentSize, side, align, offset]);
}, [triggerRect, contentSize, viewportSize.width, viewportSize.height, side, align, offset]);
const handleLayout = useCallback(
(event: { nativeEvent: { layout: { width: number; height: number } } }) => {