diff --git a/apps/web/tests/open-in-app-menus.e2e.ts b/apps/web/tests/open-in-app-menus.e2e.ts index 177cd31b7e..be50e5d914 100644 --- a/apps/web/tests/open-in-app-menus.e2e.ts +++ b/apps/web/tests/open-in-app-menus.e2e.ts @@ -1,7 +1,7 @@ /** Session menu opening over built plugins; only native application discovery and launch are simulated. */ import { mkdir, readFile } from 'node:fs/promises' import { join } from 'node:path' -import { chromium, type Browser, type BrowserContext, type Page } from 'playwright' +import { chromium, webkit, type Browser, type BrowserContext, type Page } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFinished } from 'vitest' import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment' import { launchWebScaffold, seedSession, type WebScaffold } from './scaffold.ts' @@ -149,6 +149,82 @@ describe('Open in Session menus', () => { expect(await page.getByRole('menuitem', { name: 'Show in Finder', exact: true }).count()).toBe(0) }) + it.each([{ name: 'Chromium', engine: chromium }, { name: 'WebKit', engine: webkit }])( + 'tracks real geometry and ignores unrelated portals in $name', async ({ engine }) => { + const isolated = await engine.launch() + onTestFinished(() => isolated.close()) + const context = await isolated.newContext({ viewport: { width: 1440, height: 1000 }, locale: 'en-US' }) + await nativeRoutes(context, ['vscode', 'cursor', 'finder', 'windowsterminal'], async () => 200) + const page = await context.newPage() + await openSeed(page, scaffold.authenticatedUrl) + await page.getByRole('button', { name: 'More actions', exact: true }).click() + const parent = page.getByRole('menuitem', { name: 'Open in', exact: true }) + await page.mouse.move(20, 750) + await parent.focus() + await page.keyboard.press('ArrowRight') + const root = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Copy Session as Markdown', exact: true }) }) + const child = page.getByRole('menu').filter({ has: page.getByRole('menuitem', { name: 'Windows Terminal', exact: true }) }) + await child.waitFor() + const rootElement = await root.elementHandle() + const childElement = await child.elementHandle() + const parentElement = await parent.elementHandle() + if (rootElement === null || childElement === null || parentElement === null) throw new Error('Both menu panels and the parent row must be mounted') + const alignment = async () => { + const [outer, nested, row] = await Promise.all([rootElement.boundingBox(), childElement.boundingBox(), parentElement.boundingBox()]) + return outer === null || nested === null || row === null ? Infinity : Math.max( + Math.abs(outer.x - nested.x - nested.width - 4), Math.abs(nested.y - row.y), + ) + } + // offsetWidth is integer-valued while browser rectangles retain fractional pixels. + await expect.poll(alignment).toBeLessThanOrEqual(1) + + // Browser layout changes are real; no observer callback or rectangle is mocked. + await rootElement.evaluate((node) => { node.style.transform = 'translate(-80px, 20px)' }) + await expect.poll(alignment).toBeLessThanOrEqual(1) + await parent.evaluate((node) => { node.style.marginTop = '24px' }) + await expect.poll(alignment).toBeLessThanOrEqual(1) + const before = await child.boundingBox() + await page.getByRole('menuitem', { name: 'Windows Terminal', exact: true }).getByText('Windows Terminal', { exact: true }) + .evaluate((node) => { node.style.fontSize = '30px' }) + await expect.poll(async () => (await child.boundingBox())?.width ?? 0).toBeGreaterThan(before?.width ?? 0) + await expect.poll(alignment).toBeLessThanOrEqual(1) + + await rootElement.evaluate((node) => { + node.style.maxHeight = '130px' + const viewport = node.querySelector(':scope > [role="presentation"]') + if (viewport === null || viewport.scrollHeight <= viewport.clientHeight) throw new Error('The parent must scroll') + viewport.scrollTop = viewport.scrollHeight + }) + await expect.poll(alignment).toBeLessThanOrEqual(1) + await page.setViewportSize({ width: 390, height: 844 }) + await page.getByRole('menuitem', { name: 'Back', exact: true }).waitFor() + await expectMenusInside(page) + expect(await childElement.evaluate(node => node.isConnected)).toBe(true) + await page.evaluate(() => new Promise((resolve) => { + requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) }) + })) + const writes = await childElement.evaluate(async (node) => { + let count = 0 + const observer = new MutationObserver((records) => { count += records.length }) + observer.observe(node, { attributes: true, attributeFilter: ['style'] }) + const unrelated = document.createElement('div') + unrelated.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;pointer-events:none' + try { + document.body.append(unrelated) + await new Promise((resolve) => { + requestAnimationFrame(() => { requestAnimationFrame(() => { resolve() }) }) + }) + return count + } finally { observer.disconnect(); unrelated.remove() } + }) + expect(writes).toBe(0) + await page.getByRole('menuitem', { name: 'Back', exact: true }).click() + await parent.waitFor() + await page.keyboard.press('Escape') + await expect.poll(() => page.getByRole('menu').count()).toBe(0) + }, + ) + it.each([{ catalog: [] }, { catalog: ['unnameable'] }, { catalog: ['finder'] }])('keeps empty and single-application catalogs consistent: $catalog', async ({ catalog }) => { const context = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'en-US' }) onTestFinished(() => context.close()) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 7fe0f6ec49..96620eacdd 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -30,8 +30,8 @@ en: 81e58c7b342baf3c zh: 6cd47b16124b215c /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation: - en: 4316aa56d28746af - zh: 90c88ef7a37a2e33 + en: 26392da74a7af2f4 + zh: 64f2eb649abc5292 /deepseek-ai-dsh-client-ui-primitives/understand-the-implementation/source-map: en: fd510d34404eb090 zh: d05b0890db929ae6 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index ff82e823d2..4c61522cf6 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -148,6 +148,8 @@ Portalled menus close when their anchor becomes inert or hidden; contextual menu Submenu parents show a right chevron and open through focus, click, or hover-capable non-touch pointer events. ArrowRight on a menu row enters its child, never activates the external popup trigger; ArrowLeft and Escape return focus to the parent. Each child portals outside the parent's scrolling area, prefers the right side, flips left when it fits, and uses the root menu's visual-viewport limits and WebKit coordinate normalization with internal scrolling. When neither side fits, click or ArrowRight replaces the visible parent panel with the child and a return row; focus alone keeps the parent panel visible. `submenuBackLabel` supplies its localized text; when omitted, the return row uses the caller's parent label beside a left arrow and never selects the parent. Placement depends on available space, not the device's user agent; touch clicks open children on wide screens too. Resizing retains focused child nodes. JavaScript hover requires `(any-hover: hover)` and a non-touch pointer event, so secondary mice and pens can open children even when the primary pointer is touch. Compatibility mouse hover events do not open or collapse children. The pointer grace permits crossing the gap between cards; sibling rows close the previous child. Grace dismissal returns focus left in the child to its parent. Removing or disabling the parent, or emptying its children, restores the root panel and cancels that submenu. Focus left in the removed child returns to its enabled parent, the first enabled root row, or the anchor; focus already moved elsewhere stays there. +Parent menus and child cards use the positioning core behind `useAnchoredPosition`, with per-card scroll/resize subscriptions, size observation, and frame-based movement tracking. The child placement function only chooses the preferred coordinates, side or page mode, and page width. The core owns `--dsh-anchored-max-width`, `--dsh-anchored-max-height`, and the optional `--dsh-anchored-width`; committed menu-content changes invalidate its natural-width measurement. Children have no independent ancestor, intersection, animation, or font observers. Internal font changes that leave the measured boxes and entry identity unchanged are picked up on the next placement invalidation, rather than through a dedicated font subscription. + `Menu` delegates its card material to `MenuSurface`; custom menus use the same component. `MenuSurface` forwards div props and refs, uses translucent fill and blur, and accepts `compact` for the smaller radius. Its default relative positioning contains the material layer; caller classes can supply fixed or absolute placement. On macOS, its non-interactive backing follows the card through CSS anchors and unmounts with it; the backing requires the Web shell’s isolated body. Feature classes control layout and elevation, while the component owns material and outer radius ([menu rules](../../../docs/web-styling.md#component-rules)). Modal masks retain their dark translucent fill without background blur. `MenuGroup` renders a `role="group"` section named by its localized heading, with an instance-owned heading id. It shares heading typography, spacing, and sticky positioning between custom menus and listboxes. Headings are transparent at rest; only `data-stuck` enables the theme's 94%-opaque group-header fill in either palette. Outside `data-platform="darwin"`, headings use `--dsw-radius-md` corners; the enclosing menu keeps its translucent material. diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 779f5d3f03..b3d2bd2356 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -148,6 +148,8 @@ kind: "package-library" 子菜单父项显示向右箭头,可通过聚焦、点击或支持悬停的非触摸指针事件展开。菜单行上的 ArrowRight 进入其子级,不激活外部弹窗入口;ArrowLeft 与 Escape 将焦点还给父项。每个子级通过 portal 脱离父级滚动区域,优先向右展开,左侧能容纳时向左翻转,并采用根菜单相同的 visual viewport 限制与 WebKit 坐标归一化规则,在内部限高滚动。两侧均放不下时,点击或 ArrowRight 用子级及返回行替换当前可见的父菜单面板;仅聚焦时仍显示父面板。`submenuBackLabel` 提供该行的本地化文案;省略时使用调用方的父项标签配合向左箭头,返回操作不会选定父项。布局取决于可用空间,不取决于设备 UA;宽屏触控设备也可通过点击展开子级。调整窗口大小时保留已聚焦子项的 DOM 节点。JavaScript 悬停要求 `(any-hover: hover)` 与非触摸指针事件,所以主指针为触摸时,外接鼠标或笔仍可展开子级。兼容鼠标悬停事件不会展开或收起子级。指针宽限允许跨越卡片间隙;同级其他行会关闭原子级。宽限结束关闭子级时,仍在子级中的焦点会回到父项。父项被移除、禁用或其子项清空时,恢复根面板并取消该子菜单。留在被移除子级中的焦点会回到仍可用的父项、首个可用根菜单行或锚点;已经移到其他位置的焦点保持不变。 +父菜单与子卡片复用 `useAnchoredPosition` 背后的定位核心,各卡片分别注册滚动/窗口变化订阅、尺寸观察与逐帧移动跟踪。子菜单放置函数只选择期望坐标、侧开或单面板模式及页宽。核心持有 `--dsh-anchored-max-width`、`--dsh-anchored-max-height` 和可选的 `--dsh-anchored-width`;菜单内容提交变更时会重新测量自然宽度。子菜单没有独立的祖先、交叉、动画或字体观察器。若内部字体变化未改变已测量的边界和条目身份,则在下一次定位更新时反映,而不通过专用字体订阅触发。 + `Menu` 将卡片材质交给 `MenuSurface`,自定义菜单也使用该组件。`MenuSurface` 转发 div 属性和 ref,采用透明填充及模糊,`compact` 使用较小圆角。默认相对定位使材质层限制在容器内;调用方的类可以设置 fixed 或 absolute 定位。macOS 上,不接收交互的底层通过 CSS 锚点跟随卡片,并随卡片卸载;该底层要求 Web 外壳隔离 body 的层叠上下文。功能类控制布局和层级,组件负责材质和外圆角([菜单规则](../../../docs/web-styling.zh.md#component-rules))。 模态遮罩保留黑色半透明填充,不模糊背景。 `MenuGroup` 渲染以本地化标题命名的 `role="group"` 区段,标题 id 由各实例独立持有。自定义菜单与列表框共用其标题字体、间距和吸顶定位。标题原位透明;只有 `data-stuck` 才启用主题在浅/深色模式下的 94% 不透明分组标题填充。`data-platform="darwin"` 以外的标题使用 `--dsw-radius-md` 圆角;外围菜单保留半透明材质。 diff --git a/packages/client/ui-primitives/src/Menu.module.css b/packages/client/ui-primitives/src/Menu.module.css index 6bc6319e5d..7f908287d9 100644 --- a/packages/client/ui-primitives/src/Menu.module.css +++ b/packages/client/ui-primitives/src/Menu.module.css @@ -296,8 +296,10 @@ .submenu { position: fixed; z-index: 1101; - min-width: 163px; - max-width: min(360px, calc(100vw - 24px)); + width: var(--dsh-anchored-width, max-content); + min-width: min(163px, var(--dsh-anchored-max-width, calc(100vw - 24px))); + max-width: min(360px, var(--dsh-anchored-max-width, calc(100vw - 24px))); + max-height: var(--dsh-anchored-max-height, calc(100dvh - 24px)); } /* Retain the parent's geometry and rows for placement and focus restoration. */ diff --git a/packages/client/ui-primitives/src/Menu.tsx b/packages/client/ui-primitives/src/Menu.tsx index fb89e418ab..1928bee27a 100644 --- a/packages/client/ui-primitives/src/Menu.tsx +++ b/packages/client/ui-primitives/src/Menu.tsx @@ -3,8 +3,8 @@ import type { CSSProperties, ReactNode, SyntheticEvent } from 'react' import { createPortal } from 'react-dom' import clsx from 'clsx' import { IconCheckOutlineRegular, IconChevronLeftOutlineRegular, IconChevronRightOutlineRegular } from './icons/index.tsx' -import { useMenuSubmenuPosition } from './menu-submenu-position.ts' -import { useAnchoredPosition } from './useAnchoredPosition.ts' +import { placeMenuSubmenu } from './menu-submenu-position.ts' +import { useAnchoredPosition, usePositionedOverlay } from './useAnchoredPosition.ts' import { usePointerGrace } from './pointer-grace.ts' import { isBehindModal } from './useModalLayer.ts' import { observeComposition } from './keyboard-composition.ts' @@ -327,9 +327,12 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel first?.focus() } const returningFromSubmenu = useRef(false) - const submenuPosition = useMenuSubmenuPosition( - open && exiting === undefined ? openSubmenuId : null, listRef, submenuTrigger, submenuRef, contextual, - ) + const submenuPosition = usePositionedOverlay({ + open: open && exiting === undefined && openSubmenuId !== null, + anchorRef: submenuTrigger, parentRef: listRef, panelRef: submenuRef, + placement: placeMenuSubmenu, gap: 4, margin: 12, frameClearance: !contextual, + layoutKey: liveSubmenu, + }) const submenuPage = openSubmenuId !== null && openSubmenu?.activated === true && submenuPosition?.page === true const submenuHidden = submenuPosition === null || (submenuPosition.page && !submenuPage) const submenuState = useRef({ id: openSubmenuId, page: submenuPage }) @@ -632,8 +635,7 @@ export function Menu({ open, anchor, items = [], children, submenuBackLabel, sel , - trigger: RefObject, - child: RefObject, - contextual: boolean, -): SubmenuPosition | null { - const [position, setPosition] = useState(null) - useLayoutEffect(() => { - if (active === null) { setPosition(null); return } - const parentElement = parent.current - const triggerElement = trigger.current - const childElement = child.current - /* v8 ignore next -- Menu mounts all three refs before activating this layout effect; cleanup disconnects their observers. */ - if (parentElement === null || triggerElement === null || childElement === null) return - const initialWidth = childElement.style.width - const viewport = window.visualViewport - // Match useAnchoredPosition: WebKit client rects start at the visual origin, - // while fixed CSS coordinates and viewport bounds use the layout origin. - const visualOrigin = typeof window.CSS !== 'undefined' && window.CSS.supports('-webkit-backdrop-filter', 'none') - let disposed = false - let frame: number | null = null - let movement: IntersectionObserver[] = [] - let previousBoxes = '' - const motionTargets: HTMLElement[] = [parentElement, triggerElement] - // Shrinking transforms can stay wholly inside an intersection root. Track - // their active animation only; a settled menu schedules no idle frame. - const moving = () => motionTargets.some(element => typeof element.getAnimations === 'function' - && element.getAnimations().some(animation => animation.playState === 'running')) - const schedule = () => { - if (disposed || frame !== null) return - frame = requestAnimationFrame(() => { - frame = null - place() - if (!disposed && moving()) schedule() - }) - } - // A tight observer root detects position changes, including transforms and - // layout shifts that change neither the element's size nor scroll offsets. - const observeMovement = (element: Element, rect: DOMRect) => { - const observer = new IntersectionObserver((entries) => { - if (entries.some(entry => entry.boundingClientRect.left !== rect.left || entry.boundingClientRect.top !== rect.top - || entry.boundingClientRect.width !== rect.width || entry.boundingClientRect.height !== rect.height)) schedule() - }, { rootMargin: `${-rect.top}px ${rect.right - window.innerWidth}px ${rect.bottom - window.innerHeight}px ${-rect.left}px`, threshold: 1 }) - observer.observe(element) - movement.push(observer) - } - const place = () => { - if (disposed) return - const panel = parentElement.getBoundingClientRect() - const row = triggerElement.getBoundingClientRect() - const margin = 12 - const gap = 4 - const viewportLeft = viewport?.offsetLeft ?? 0 - const viewportTop = viewport?.offsetTop ?? 0 - const vw = viewport?.width ?? (document.documentElement.clientWidth || window.innerWidth) - const vh = viewport?.height ?? (document.documentElement.clientHeight || window.innerHeight) - const offsetX = visualOrigin ? viewportLeft : 0 - const offsetY = visualOrigin ? viewportTop : 0 - const topMargin = contextual ? margin : overlayTopMargin(margin, row, gap) - const maxHeight = Math.max(0, vh - topMargin - margin) - // Intrinsic width is refreshed only on placement invalidation, not idle frames. - if (childElement.style.width !== '') childElement.style.width = '' - const width = childElement.offsetWidth - const right = offsetX + panel.right + gap - const left = offsetX + panel.left - gap - width - const page = right + width > viewportLeft + vw - margin && left < viewportLeft + margin - const pageWidth = Math.min(Math.max(panel.width, width), vw - margin * 2) - const actualWidth = page ? pageWidth : width - const x = page ? offsetX + panel.left : right + width <= viewportLeft + vw - margin ? right : left - const height = Math.min(childElement.offsetHeight, maxHeight) - const y = offsetY + (page ? panel.top : row.top) - const next: SubmenuPosition = { - left: Math.max(viewportLeft + margin, Math.min(x, viewportLeft + vw - actualWidth - margin)), - top: Math.max(viewportTop + topMargin, Math.min(y, viewportTop + vh - height - margin)), - maxHeight, - ...(page ? { width: pageWidth } : {}), - page, - } - if (page) childElement.style.width = `${pageWidth}px` - setPosition(current => current?.left === next.left && current.top === next.top - && current.maxHeight === next.maxHeight && current.width === next.width && current.page === next.page ? current : next) - const boxes = [ - panel.left, panel.top, panel.width, panel.height, row.left, row.top, row.width, row.height, vw, vh, viewportLeft, viewportTop, - ].join(',') - if (typeof IntersectionObserver !== 'undefined' && boxes !== previousBoxes) { - for (const observer of movement) observer.disconnect() - movement = [] - previousBoxes = boxes - observeMovement(parentElement, panel) - observeMovement(triggerElement, row) - } - } - place() - const resize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(schedule) - resize?.observe(parentElement) - resize?.observe(triggerElement) - resize?.observe(childElement) - const mutation = new MutationObserver((records) => { - if (records.some(record => record.target !== childElement || record.attributeName !== 'style')) schedule() - }) - const attributes = { attributes: true, attributeFilter: ['class', 'style', 'hidden'], childList: true } - mutation.observe(parentElement, { ...attributes, subtree: true, characterData: true }) - mutation.observe(childElement, { ...attributes, subtree: true, characterData: true }) - for (let ancestor = parentElement.parentElement; ancestor !== null; ancestor = ancestor.parentElement) { - mutation.observe(ancestor, attributes) - motionTargets.push(ancestor) - } - const onMotion = (event: Event) => { - if (event.target instanceof HTMLElement && motionTargets.includes(event.target)) schedule() - } - const motionEvents = ['animationstart', 'animationend', 'animationcancel', 'transitionrun', 'transitionend', 'transitioncancel'] - for (const event of motionEvents) document.addEventListener(event, onMotion, true) - if (moving()) schedule() - const fonts = 'fonts' in document ? document.fonts : undefined - fonts?.addEventListener('loadingdone', schedule) - fonts?.addEventListener('loadingerror', schedule) - window.addEventListener('resize', place) - window.addEventListener('scroll', place, true) - viewport?.addEventListener('resize', place) - viewport?.addEventListener('scroll', place) - return () => { - disposed = true - if (frame !== null) cancelAnimationFrame(frame) - resize?.disconnect() - mutation.disconnect() - for (const event of motionEvents) document.removeEventListener(event, onMotion, true) - for (const observer of movement) observer.disconnect() - fonts?.removeEventListener('loadingdone', schedule) - fonts?.removeEventListener('loadingerror', schedule) - window.removeEventListener('resize', place) - window.removeEventListener('scroll', place, true) - viewport?.removeEventListener('resize', place) - viewport?.removeEventListener('scroll', place) - childElement.style.width = initialWidth - } - }, [active, parent, trigger, child, contextual]) - return position +export function placeMenuSubmenu(geometry: OverlayGeometry): OverlayPlacement { + const { anchor, parent, width, gap, bounds } = geometry + const right = parent.right + gap + const left = parent.left - gap - width + const page = right + width > bounds.right && left < bounds.left + return { + left: page ? parent.left : right + width <= bounds.right ? right : left, + top: page ? parent.top : anchor.top, + ...(page ? { width: Math.min(Math.max(parent.width, width), Math.max(0, bounds.right - bounds.left)) } : {}), + page, + } } diff --git a/packages/client/ui-primitives/src/useAnchoredPosition.ts b/packages/client/ui-primitives/src/useAnchoredPosition.ts index 61a891e5a9..32f7d9edf2 100644 --- a/packages/client/ui-primitives/src/useAnchoredPosition.ts +++ b/packages/client/ui-primitives/src/useAnchoredPosition.ts @@ -36,9 +36,48 @@ export interface AnchoredPositionOptions { * @returns Fixed left/top coordinates, or null while closed or awaiting an anchor; the first measurement completes before paint. */ export function useAnchoredPosition(options: AnchoredPositionOptions): CSSProperties | null { - const { open, anchorRef, panelRef, side = 'bottom', align = 'start', gap, margin, + return usePositionedOverlay(options)?.style ?? null +} + +/** Layout-origin geometry supplied to the package's submenu placement strategy. */ +export interface OverlayGeometry { + anchor: DOMRect + parent: DOMRect + width: number + gap: number + bounds: { left: number; right: number } +} + +/** Preferred coordinates and optional explicit width, before viewport clamping. */ +export interface OverlayPlacement { + left: number + top: number + width?: number + page: boolean +} + +/** Fixed coordinates and navigation mode from the same placement measurement. */ +interface PositionedOverlay { + style: CSSProperties + page: boolean +} + +/** + * Package-internal placement core shared by anchored overlays and Menu children. + * Owns size variables, coordinate conversion, observers, and movement tracking. + * A custom placement consumes natural width and may set `--dsh-anchored-width`; + * CSS must consume it with a max-content fallback. Managed styles restore on cleanup. + * @param options - Anchored inputs plus an optional parent card and pure placement strategy. + * @returns Coordinates and page mode together, or null while no anchor is available. + */ +export function usePositionedOverlay(options: Omit & { + parentRef?: RefObject + placement?: (geometry: OverlayGeometry) => OverlayPlacement + layoutKey?: unknown +}): PositionedOverlay | null { + const { open, anchorRef, panelRef, parentRef, placement, side = 'bottom', align = 'start', gap, margin, getAnchorRect, layoutKey, minWidthFromAnchor = false, frameClearance = true } = options - const [position, setPosition] = useState(null) + const [position, setPosition] = useState(null) useLayoutEffect(() => { if (!open) { setPosition(null) @@ -52,14 +91,18 @@ export function useAnchoredPosition(options: AnchoredPositionOptions): CSSProper const viewport = win.visualViewport // WebKit client rects use the visual origin; viewport-fixed CSS uses the layout origin. const visualOrigin = typeof win.CSS !== 'undefined' && win.CSS.supports('-webkit-backdrop-filter', 'none') - const properties = ['--dsh-anchored-max-width', '--dsh-anchored-max-height', ...minWidthFromAnchor ? ['min-width'] : []] + const parent = parentRef?.current + const properties = ['--dsh-anchored-max-width', '--dsh-anchored-max-height', + ...placement === undefined ? [] : ['--dsh-anchored-width'], ...minWidthFromAnchor ? ['min-width'] : []] const previous = properties.map(name => [name, panel.style.getPropertyValue(name), panel.style.getPropertyPriority(name)] as const) let active = true - let lastRect: Pick | null = null + let lastBoxes = '' const readRect = () => getAnchorRect === undefined ? anchor.getBoundingClientRect() : getAnchorRect() - const place = (rect: DOMRect | null): void => { - lastRect = rect === null ? null : { x: rect.x, y: rect.y, width: rect.width, height: rect.height } - let next: CSSProperties | null = null + const boxes = (rect: DOMRect | null, parentRect: DOMRect | undefined) => + [rect?.x, rect?.y, rect?.width, rect?.height, parentRect?.x, parentRect?.y, parentRect?.width, parentRect?.height].join(',') + const place = (rect: DOMRect | null, parentRect: DOMRect | undefined): void => { + lastBoxes = boxes(rect, parentRect) + let next: PositionedOverlay | null = null if (rect !== null) { const x = viewport?.offsetLeft ?? 0 const y = viewport?.offsetTop ?? 0 @@ -70,22 +113,35 @@ export function useAnchoredPosition(options: AnchoredPositionOptions): CSSProper panel.style.setProperty('--dsh-anchored-max-width', `${maxWidth}px`) panel.style.setProperty('--dsh-anchored-max-height', `${Math.max(0, height - topMargin - margin)}px`) if (minWidthFromAnchor) panel.style.minWidth = `${Math.min(rect.width, maxWidth)}px` + if (placement !== undefined) panel.style.setProperty('--dsh-anchored-width', 'max-content') const panelWidth = panel.offsetWidth const panelHeight = panel.offsetHeight - const offsetX = visualOrigin ? x : 0 - const offsetY = visualOrigin ? y : 0 - const left = offsetX + (side === 'right' ? rect.right + gap : align === 'end' ? rect.right - panelWidth : rect.left) - const top = offsetY + (side === 'right' ? rect.top : side === 'top' ? rect.top - gap - panelHeight : rect.bottom + gap) + const normalize = (box: DOMRect) => new DOMRect( + box.x + (visualOrigin ? x : 0), box.y + (visualOrigin ? y : 0), box.width, box.height, + ) + const normalized = normalize(rect) + const preferred: OverlayPlacement = placement === undefined ? { + left: side === 'right' ? normalized.right + gap : align === 'end' ? normalized.right - panelWidth : normalized.left, + top: side === 'right' ? normalized.top : side === 'top' ? normalized.top - gap - panelHeight : normalized.bottom + gap, + page: false, + } : placement({ anchor: normalized, parent: normalize(parentRect ?? rect), width: panelWidth, gap, + bounds: { left: x + margin, right: x + width - margin } }) + if (preferred.width !== undefined) panel.style.setProperty('--dsh-anchored-width', `${preferred.width}px`) + const finalHeight = preferred.width === undefined ? panelHeight : panel.offsetHeight next = { - left: Math.max(x + margin, Math.min(left, x + width - margin - panelWidth)), - top: Math.max(y + topMargin, Math.min(top, y + height - margin - panelHeight)), + style: { + left: Math.max(x + margin, Math.min(preferred.left, x + width - margin - (preferred.width ?? panelWidth))), + top: Math.max(y + topMargin, Math.min(preferred.top, y + height - margin - finalHeight)), + }, + page: preferred.page, } } - setPosition(current => current?.left === next?.left && current?.top === next?.top ? current : next) + setPosition(current => current?.style.left === next?.style.left && current?.style.top === next?.style.top + && current?.page === next?.page ? current : next) } const update = (): void => { if (!active) return - place(readRect()) + place(readRect(), parent?.getBoundingClientRect()) } update() win.addEventListener('scroll', update, true) @@ -95,13 +151,14 @@ export function useAnchoredPosition(options: AnchoredPositionOptions): CSSProper const observer = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(update) observer?.observe(anchor) observer?.observe(panel) + if (parent != null) observer?.observe(parent) // Transforms and surrounding layout can move an anchor without resizing either element. let frame = 0 const track = (): void => { if (!active) return const rect = readRect() - if (rect?.x !== lastRect?.x || rect?.y !== lastRect?.y - || rect?.width !== lastRect?.width || rect?.height !== lastRect?.height) place(rect) + const parentRect = parent?.getBoundingClientRect() + if (boxes(rect, parentRect) !== lastBoxes) place(rect, parentRect) frame = win.requestAnimationFrame(track) } frame = win.requestAnimationFrame(track) @@ -115,6 +172,9 @@ export function useAnchoredPosition(options: AnchoredPositionOptions): CSSProper viewport?.removeEventListener('resize', update) for (const [name, value, priority] of previous) panel.style.setProperty(name, value, priority) } - }, [open, anchorRef, panelRef, side, align, gap, margin, getAnchorRect, layoutKey, minWidthFromAnchor, frameClearance]) + }, [ + open, anchorRef, panelRef, parentRef, placement, side, align, gap, margin, + getAnchorRect, layoutKey, minWidthFromAnchor, frameClearance, + ]) return position } diff --git a/packages/client/ui-primitives/tests/menu-submenu-position.client.spec.tsx b/packages/client/ui-primitives/tests/menu-submenu-position.client.spec.tsx index c3ee879b10..1e9d997137 100644 --- a/packages/client/ui-primitives/tests/menu-submenu-position.client.spec.tsx +++ b/packages/client/ui-primitives/tests/menu-submenu-position.client.spec.tsx @@ -1,80 +1,47 @@ // @vitest-environment jsdom -/** Isolated submenu placement work counts exclude Menu's separate root-position tracker. */ +/** Submenu geometry and shared overlay lifecycle; browser layout is verified in the Web lane. */ import { useRef } from 'react' import { act, cleanup, render } from '@testing-library/react' import { afterEach, beforeEach, expect, it, onTestFinished, vi } from 'vitest' -import { useMenuSubmenuPosition } from '../src/menu-submenu-position.ts' +import { placeMenuSubmenu } from '../src/menu-submenu-position.ts' +import { usePositionedOverlay } from '../src/useAnchoredPosition.ts' let panelRect: DOMRect let triggerRect: DOMRect let childWidth: number let childHeight: number -const intersections: ControlledIntersectionObserver[] = [] const resizes: ControlledResizeObserver[] = [] -class ControlledIntersectionObserver implements IntersectionObserver { - readonly root = null - readonly rootMargin: string - readonly scrollMargin = '0px 0px 0px 0px' - readonly thresholds = [1] - private target: Element | null = null - constructor(private readonly callback: IntersectionObserverCallback, options?: IntersectionObserverInit) { - this.rootMargin = options?.rootMargin ?? '' - intersections.push(this) - } - observe = vi.fn((element: Element) => { this.target = element }) - unobserve = vi.fn() - disconnect = vi.fn() - takeRecords = () => [] - emit(rect: DOMRect) { - this.callback([{ target: this.target!, boundingClientRect: rect, intersectionRect: rect, - rootBounds: rect, intersectionRatio: 1, isIntersecting: true, time: 0 }], this) - } -} - class ControlledResizeObserver implements ResizeObserver { constructor(private readonly callback: ResizeObserverCallback) { resizes.push(this) } - observe = vi.fn() + observe = vi.fn() unobserve = vi.fn() disconnect = vi.fn() emit() { this.callback([], this) } } -function observers() { - vi.stubGlobal('IntersectionObserver', ControlledIntersectionObserver) - vi.stubGlobal('ResizeObserver', ControlledResizeObserver) -} - -async function flushPlacement() { - await act(async () => { await Promise.resolve() }) - act(() => { vi.advanceTimersToNextFrame() }) -} - -function Placement({ active = true, contextual = false }: { active?: boolean; contextual?: boolean }) { +function Placement({ active = true, contextual = false, revision = 0 }: { active?: boolean; contextual?: boolean; revision?: number }) { const parent = useRef(null) const trigger = useRef(null) const child = useRef(null) - const position = useMenuSubmenuPosition(active ? 'parent' : null, parent, trigger, child, contextual) + const position = usePositionedOverlay({ open: active, parentRef: parent, anchorRef: trigger, panelRef: child, + gap: 4, margin: 12, frameClearance: !contextual, placement: placeMenuSubmenu, layoutKey: revision }) return <>
- {active &&
Choice
} + {active &&
Choice
} } beforeEach(() => { vi.useFakeTimers() panelRect = new DOMRect(100, 100, 200, 100) - triggerRect = new DOMRect(100, 100, 200, 100) + triggerRect = new DOMRect(104, 140, 192, 34) childWidth = 200 childHeight = 100 - intersections.length = 0 resizes.length = 0 vi.stubGlobal('innerWidth', 390) vi.stubGlobal('innerHeight', 768) - vi.stubGlobal('ResizeObserver', undefined) - vi.stubGlobal('IntersectionObserver', undefined) + vi.stubGlobal('ResizeObserver', ControlledResizeObserver) vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { return this.tagName === 'BUTTON' ? triggerRect : panelRect }) @@ -83,25 +50,19 @@ beforeEach(() => { }) afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); vi.unstubAllGlobals() }) -it('does no geometry reads or width writes across 100 idle animation frames', async () => { - const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect') - const width = vi.spyOn(HTMLElement.prototype, 'offsetWidth', 'get') - const height = vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get') - const view = render() - const writes = vi.spyOn(view.getByTestId('child').style, 'width', 'set') - await flushPlacement() - rect.mockClear(); width.mockClear(); height.mockClear(); writes.mockClear() - act(() => { for (let frame = 0; frame < 100; frame++) vi.advanceTimersToNextFrame() }) - const counts = { - rect: rect.mock.calls.length, width: width.mock.calls.length, height: height.mock.calls.length, widthWrites: writes.mock.calls.length, - } - console.info('submenu idle 100 frames', counts) - expect(counts).toEqual({ rect: 0, width: 0, height: 0, widthWrites: 0 }) +it.each([ + { parentX: 100, right: 1012, width: 200, left: 304, top: 140, page: false }, + { parentX: 780, right: 1012, width: 200, left: 576, top: 140, page: false }, + { parentX: 100, right: 378, width: 200, left: 100, top: 100, page: true }, + { parentX: 100, right: 378, width: 500, left: 100, top: 100, page: true }, + { parentX: 12, right: 416, width: 200, left: 216, top: 140, page: false }, +])('places a child at $left/$top with page=$page', ({ parentX, right, width, left, top, page }) => { + expect(placeMenuSubmenu({ parent: new DOMRect(parentX, 100, 200, 100), anchor: triggerRect, + width, gap: 4, bounds: { left: 12, right } })).toEqual({ left, top, page, + ...(page ? { width: Math.min(Math.max(200, width), right - 12) } : {}) }) }) it.each([true, false])('fits the visual viewport in WebKit=%s coordinates and follows its events', (webkit) => { - vi.stubGlobal('innerWidth', 1000) - vi.stubGlobal('innerHeight', 900) vi.stubGlobal('CSS', { supports: () => webkit }) const viewport = Object.assign(new EventTarget(), { width: 500, height: 400, offsetLeft: 40, offsetTop: 60 }) vi.stubGlobal('visualViewport', viewport) @@ -110,108 +71,57 @@ it.each([true, false])('fits the visual viewport in WebKit=%s coordinates and fo triggerRect = webkit ? new DOMRect(104, 240, 192, 34) : new DOMRect(144, 300, 192, 34) const view = render() const card = view.getByTestId('child') - expect(card.style.width).toBe('200px') + expect(card.style.getPropertyValue('--dsh-anchored-width')).toBe('200px') expect(card.style.left).toBe('140px') expect(card.style.top).toBe('260px') - expect(card.style.maxHeight).toBe('376px') + expect(card.style.getPropertyValue('--dsh-anchored-max-height')).toBe('376px') act(() => { viewport.width = 900; viewport.dispatchEvent(new Event('resize')) }) - expect(card.style.width).toBe('') + expect(card.style.getPropertyValue('--dsh-anchored-width')).toBe('max-content') expect(card.style.left).toBe('344px') expect(card.style.top).toBe('300px') childHeight = 500 act(() => { viewport.height = 180; viewport.offsetTop = 120; viewport.dispatchEvent(new Event('scroll')) }) - expect(card.style.maxHeight).toBe('156px') + expect(card.style.getPropertyValue('--dsh-anchored-max-height')).toBe('156px') expect(card.style.top).toBe('132px') view.unmount() expect(remove.mock.calls.map(([type]) => type)).toEqual(expect.arrayContaining(['resize', 'scroll'])) }) -it('uses document client dimensions when there is no visual viewport', () => { +it('uses document dimensions and remeasures natural width on committed content changes', () => { vi.stubGlobal('visualViewport', undefined) - vi.stubGlobal('innerWidth', 1000) - vi.stubGlobal('innerHeight', 1000) vi.spyOn(document.documentElement, 'clientWidth', 'get').mockReturnValue(390) vi.spyOn(document.documentElement, 'clientHeight', 'get').mockReturnValue(600) - const view = render() - expect(view.getByTestId('child').style.width).toBe('200px') - expect(view.getByTestId('child').style.maxHeight).toBe('576px') -}) - -it('tracks parent and row movement without idle polling and coalesces observer notifications', async () => { - observers() - vi.stubGlobal('innerWidth', 1024) - const view = render() - const card = view.getByTestId('child') - const request = vi.spyOn(window, 'requestAnimationFrame') - expect(card.style.left).toBe('304px') - intersections[0]!.emit(panelRect) - expect(request).not.toHaveBeenCalled() - const original = [...intersections] - panelRect = new DOMRect(400, 100, 200, 100) - intersections[0]!.emit(panelRect) - intersections[0]!.emit(panelRect) - expect(request).toHaveBeenCalledTimes(1) - await flushPlacement() - expect(card.style.left).toBe('604px') - expect(original.every(observer => observer.disconnect.mock.calls.length === 1)).toBe(true) - triggerRect = new DOMRect(404, 740, 192, 34) - intersections.at(-1)!.emit(triggerRect) - await flushPlacement() - expect(card.style.top).toBe('656px') - expect(resizes[0]!.observe).toHaveBeenCalledTimes(3) -}) - -it('remeasures content and font changes while retaining page width and flipping when space becomes available', async () => { - observers() - const fonts = new EventTarget() - const previousFonts = Object.getOwnPropertyDescriptor(document, 'fonts') - Object.defineProperty(document, 'fonts', { configurable: true, value: fonts }) - onTestFinished(() => { - if (previousFonts === undefined) Reflect.deleteProperty(document, 'fonts') - else Object.defineProperty(document, 'fonts', previousFonts) - }) panelRect = new DOMRect(40, 100, 300, 100) const view = render() const card = view.getByTestId('child') - expect(card.style.width).toBe('300px') + expect(card.style.getPropertyValue('--dsh-anchored-width')).toBe('300px') + expect(card.style.getPropertyValue('--dsh-anchored-max-height')).toBe('576px') childWidth = 350 - card.textContent = 'A longer localized choice' - await flushPlacement() - expect(card.style.width).toBe('350px') + view.rerender() + expect(card.style.getPropertyValue('--dsh-anchored-width')).toBe('350px') expect(card.style.left).toBe('28px') childWidth = 200 - fonts.dispatchEvent(new Event('loadingdone')) - await flushPlacement() - expect(card.style.width).toBe('300px') - childWidth = 320 - fonts.dispatchEvent(new Event('loadingerror')) - await flushPlacement() - expect(card.style.width).toBe('320px') - vi.stubGlobal('innerWidth', 1024) - act(() => { window.dispatchEvent(new Event('resize')) }) - expect(card.style.width).toBe('') - expect(card.style.left).toBe('344px') - panelRect = new DOMRect(700, 100, 300, 100) - act(() => { window.dispatchEvent(new Event('scroll')) }) - expect(card.style.left).toBe('376px') - childHeight = 1000 - resizes[0]!.emit() - await flushPlacement() - expect(card.style.maxHeight).toBe('744px') - expect(card.style.top).toBe('12px') - view.unmount() - expect(resizes[0]!.disconnect).toHaveBeenCalledOnce() - expect(intersections.every(observer => observer.disconnect.mock.calls.length > 0)).toBe(true) - const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect') - rect.mockClear() - fonts.dispatchEvent(new Event('loadingdone')) - resizes[0]!.emit() - intersections[0]!.emit(new DOMRect()) - await flushPlacement() - expect(rect).not.toHaveBeenCalled() + view.rerender() + expect(card.style.getPropertyValue('--dsh-anchored-width')).toBe('300px') }) -it.each([true, false])('uses the contextual=%s top clearance for a tall child', (contextual) => { +it('follows parent and row movement through the shared animation-frame tracker', () => { + vi.stubGlobal('innerWidth', 1024) + const view = render() + const card = view.getByTestId('child') + panelRect = new DOMRect(400, 100, 200, 100) + act(() => { vi.advanceTimersToNextFrame() }) + expect(card.style.left).toBe('604px') + triggerRect = new DOMRect(404, 740, 192, 34) + act(() => { vi.advanceTimersToNextFrame() }) + expect(card.style.top).toBe('656px') + childHeight = 1000 + act(() => { resizes[0]!.emit() }) + expect(card.style.top).toBe('12px') + expect(resizes[0]!.observe.mock.calls.map(([node]) => node)).toEqual([view.getByRole('button'), card, view.getByTestId('parent')]) +}) + +it.each([true, false])('uses contextual=%s top clearance for a tall child', (contextual) => { const root = document.documentElement const previous = root.style.getPropertyValue('--dsh-frame-top-clearance') root.style.setProperty('--dsh-frame-top-clearance', '96px') @@ -220,78 +130,25 @@ it.each([true, false])('uses the contextual=%s top clearance for a tall child', else root.style.setProperty('--dsh-frame-top-clearance', previous) }) childHeight = 1000 + triggerRect = new DOMRect(100, 100, 200, 100) const view = render() expect(view.getByTestId('child').style.top).toBe(contextual ? '12px' : '116px') - expect(view.getByTestId('child').style.maxHeight).toBe(contextual ? '744px' : '640px') + expect(view.getByTestId('child').style.getPropertyValue('--dsh-anchored-max-height')).toBe(contextual ? '744px' : '640px') }) -it('observes ancestor attributes and ignores its own width writes', async () => { - const view = render() - const card = view.getByTestId('child') - const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect') - await flushPlacement() - rect.mockClear() - card.style.width = '200px' - await flushPlacement() - expect(rect).not.toHaveBeenCalled() - panelRect = new DOMRect(20, 150, 200, 100) - view.container.style.transform = 'translateY(50px)' - await flushPlacement() - expect(card.style.top).toBe('150px') - card.className = 'compact' - await flushPlacement() - expect(rect).toHaveBeenCalled() -}) - -it.each([true, false])('tracks a finite ancestor animation alreadyRunning=%s, then stops scheduling frames', (alreadyRunning) => { - observers() - vi.stubGlobal('innerWidth', 1024) - let running = alreadyRunning - const body = document.body - const original = Object.getOwnPropertyDescriptor(body, 'getAnimations') - Object.defineProperty(body, 'getAnimations', { configurable: true, value: () => [{ playState: running ? 'running' : 'finished' }] }) - onTestFinished(() => { - if (original === undefined) Reflect.deleteProperty(body, 'getAnimations') - else Object.defineProperty(body, 'getAnimations', original) - }) - const view = render() - const card = view.getByTestId('child') - running = true - act(() => { body.dispatchEvent(new Event('transitionrun', { bubbles: true })) }) - panelRect = new DOMRect(100, 100, 180, 100) - act(() => { vi.advanceTimersToNextFrame() }) - expect(card.style.left).toBe('284px') - panelRect = new DOMRect(100, 100, 160, 100) - act(() => { vi.advanceTimersToNextFrame() }) - expect(card.style.left).toBe('264px') - running = false - act(() => { body.dispatchEvent(new Event('transitionend', { bubbles: true })); vi.advanceTimersToNextFrame() }) - const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect') - rect.mockClear() - act(() => { - document.dispatchEvent(new Event('animationstart')) - card.dispatchEvent(new Event('animationstart', { bubbles: true })) - for (let frame = 0; frame < 100; frame++) vi.advanceTimersToNextFrame() - }) - expect(rect).not.toHaveBeenCalled() - view.unmount() - body.dispatchEvent(new Event('animationstart', { bubbles: true })) - act(() => { vi.advanceTimersToNextFrame() }) - expect(rect).not.toHaveBeenCalled() -}) - -it('cancels pending placement and ignores already queued frames after close', () => { - observers() +it('restores size variables and ignores queued observer and frame callbacks after close', () => { const callbacks: FrameRequestCallback[] = [] vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => { callbacks.push(callback); return callbacks.length }) const cancel = vi.spyOn(window, 'cancelAnimationFrame') const view = render() - resizes[0]!.emit() + const card = view.getByTestId('child') view.rerender() expect(cancel).toHaveBeenCalledWith(1) + expect(resizes[0]!.disconnect).toHaveBeenCalledOnce() + for (const name of ['width', 'max-width', 'max-height']) expect(card.style.getPropertyValue(`--dsh-anchored-${name}`)).toBe('') const rect = vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect') rect.mockClear() - act(() => { callbacks[0]!(0) }) + act(() => { callbacks[0]!(0); resizes[0]!.emit(); window.dispatchEvent(new Event('scroll')) }) expect(rect).not.toHaveBeenCalled() expect(view.queryByTestId('child')).toBeNull() }) diff --git a/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx b/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx index ce3db963b0..dbdbe7fd8f 100644 --- a/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx +++ b/packages/client/ui-primitives/tests/menu-submenu.client.spec.tsx @@ -245,7 +245,7 @@ describe('Menu submenus', () => { expect(menu.parentElement).toBe(document.body) expect(menu.style.left).toBe('576px') expect(menu.style.top).toBe('12px') - expect(menu.style.maxHeight).toBe('744px') + expect(menu.style.getPropertyValue('--dsh-anchored-max-height')).toBe('744px') expect(screen.getByRole('menuitem', { name: 'Applications' }).closest('[role="menu"]')?.contains(menu)).toBe(false) }) @@ -260,7 +260,7 @@ describe('Menu submenus', () => { const menu = childMenu() expect(screen.getAllByRole('menu')).toHaveLength(1) expect(menu.style.left).toBe('170px') - expect(menu.style.width).toBe('200px') + expect(menu.style.getPropertyValue('--dsh-anchored-width')).toBe('200px') expect(document.activeElement).toBe(screen.getByRole('menuitem', { name: 'First app' })) fireEvent.click(screen.getByRole('menuitem', { name: '返回上级' })) expect(select).not.toHaveBeenCalled() diff --git a/packages/client/ui-primitives/tests/use-anchored-position.client.spec.tsx b/packages/client/ui-primitives/tests/use-anchored-position.client.spec.tsx index df02d5a43a..45f5089306 100644 --- a/packages/client/ui-primitives/tests/use-anchored-position.client.spec.tsx +++ b/packages/client/ui-primitives/tests/use-anchored-position.client.spec.tsx @@ -3,7 +3,7 @@ import { useRef } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { act, cleanup, render, renderHook } from '@testing-library/react' -import { useAnchoredPosition } from '../src/useAnchoredPosition.ts' +import { useAnchoredPosition, usePositionedOverlay, type OverlayGeometry } from '../src/useAnchoredPosition.ts' let frames: FrameRequestCallback[] beforeEach(() => { @@ -39,6 +39,19 @@ function show(props: Parameters[0]) { } describe('useAnchoredPosition', () => { + it('uses the anchor as the reference for a placement without a separate parent', () => { + const anchor = document.createElement('button') + const panel = document.createElement('div') + const placement = vi.fn((geometry: OverlayGeometry) => ({ + left: geometry.anchor.left, top: geometry.anchor.bottom + geometry.gap, page: false, + })) + const { result } = renderHook(() => usePositionedOverlay({ + open: true, anchorRef: { current: anchor }, panelRef: { current: panel }, gap: 4, margin: 12, placement, + })) + expect(placement.mock.calls[0]![0].parent).toEqual(placement.mock.calls[0]![0].anchor) + expect(result.current).toEqual({ style: { left: 100, top: 324 }, page: false }) + }) + it.each(['anchor', 'panel'] as const)('does not measure or subscribe without the %s element', (missing) => { const anchor = document.createElement('button') const measure = vi.spyOn(anchor, 'getBoundingClientRect')