diff --git a/apps/web/tests/agent-team-panel.e2e.ts b/apps/web/tests/agent-team-panel.e2e.ts index bc6fafa6ac..7438bc86ce 100644 --- a/apps/web/tests/agent-team-panel.e2e.ts +++ b/apps/web/tests/agent-team-panel.e2e.ts @@ -593,10 +593,32 @@ describe('web e2e: agent teamwork panel', () => { await card.waitFor() expect(await card.evaluate(element => [...element.children].slice(0, 2).map(child => child.textContent))) .toEqual([RESEARCHER_DESCRIPTION, 'Owner: team-panel-researcher']) + // The window has room for the card on neither side of the row, and this description fills a card too + // tall to open under or over the row, so the card covers the row; it stays inside the viewport. expect(await card.evaluate((element) => { - const rect = element.getBoundingClientRect() - return rect.left >= 0 && rect.right <= window.innerWidth + // The details sit inside the fixed card. + let fixed = element + while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement! + const rect = fixed.getBoundingClientRect() + return rect.left >= 0 && rect.top >= 0 && rect.right <= window.innerWidth && rect.bottom <= window.innerHeight })).toBe(true) + await page.mouse.move(20, 400) + await card.waitFor({ state: 'detached' }) + // A card that fits under its row opens there, from the row's start edge and inside the viewport's + // margin, so the row stays clear. + const task = panel.locator('[data-team-task]').getByRole('button') + await task.hover() + await card.waitFor() + const anchor = await task.locator('xpath=..').boundingBox() + if (anchor === null) throw new Error('the task row has no box') + const placed = await card.evaluate((element) => { + let fixed = element + while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement! + const bounds = fixed.getBoundingClientRect() + return { left: bounds.left, top: bounds.top, right: bounds.right, viewport: window.innerWidth } + }) + expect({ below: placed.top - (anchor.y + anchor.height), start: placed.left - anchor.x }).toEqual({ below: 8, start: 0 }) + expect(placed.right).toBeLessThanOrEqual(placed.viewport - 8) const beforeClick = page.url() await primary.click() expect(page.url()).toBe(beforeClick) diff --git a/apps/web/tests/subagent-conversation.e2e.ts b/apps/web/tests/subagent-conversation.e2e.ts index e32f0fd38d..f91d40d033 100644 --- a/apps/web/tests/subagent-conversation.e2e.ts +++ b/apps/web/tests/subagent-conversation.e2e.ts @@ -502,13 +502,17 @@ describe('web e2e: persisted subagent conversation and human continuation', () = await card.waitFor() expect(await card.evaluate(element => [...element.children].map(child => child.textContent).slice(0, 3))) .toEqual([LABEL, `Owner: ${CHILD_NAME}`, 'completed · continuable']) - // The panel sits at the window's end, so the card opens on the row's start side, inside the viewport. + // The panel sits at the window's end, so the stylesheet opens the card on the row's start side: + // 8px before the row, its top on the row's top, inside the viewport. const placement = await card.evaluate((element) => { - const bounds = element.getBoundingClientRect() - const row = document.querySelector('[data-subagents-section] [role="treeitem"]')!.getBoundingClientRect() - return { left: bounds.left >= 0, beforeRow: bounds.right <= row.left } + // The details sit inside the fixed card, and the card's anchor wraps the row. + let fixed = element + while (getComputedStyle(fixed).position !== 'fixed') fixed = fixed.parentElement! + const bounds = fixed.getBoundingClientRect() + const row = document.querySelector('[data-subagents-section] [role="treeitem"]')!.parentElement!.getBoundingClientRect() + return { inside: bounds.left >= 8, gap: row.left - bounds.right, top: bounds.top - row.top } }) - expect(placement).toEqual({ left: true, beforeRow: true }) + expect(placement).toEqual({ inside: true, gap: 8, top: 0 }) expect(page.url()).toBe(originalUrl) expect(scaffold.ctx.agents.get(childId)).toBeUndefined() await page.locator('[data-composer-input]').first().hover() diff --git a/apps/web/tests/workspace-management.e2e.ts b/apps/web/tests/workspace-management.e2e.ts index 7dfd5a8135..77f59c34f1 100644 --- a/apps/web/tests/workspace-management.e2e.ts +++ b/apps/web/tests/workspace-management.e2e.ts @@ -541,6 +541,15 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo // crossing ground that belongs to neither. Hovering it must not dismiss // it — the hazard this scenario pins. const card = page.getByRole('button', { name: `Copy: ${rowTitle}` }) + // The stylesheet anchors the card: beside the row's end edge, its top on the row's top. + const beside = async (): Promise<{ gap: number; top: number; bottomMargin: number }> => { + const row = await sessionRow.boundingBox() + const box = await card.boundingBox() + if (row === null || box === null) throw new Error('the row or its hover card has no box') + const height = await page.evaluate(() => window.innerHeight) + return { gap: box.x - (row.x + row.width), top: box.y - row.y, bottomMargin: height - (box.y + box.height) } + } + expect(await beside()).toMatchObject({ gap: 8, top: 0 }) await card.hover() await page.waitForTimeout(POINTER_HOLD_MS) expect(await page.getByText('Idle', { exact: true }).count()).toBeGreaterThanOrEqual(1) @@ -559,6 +568,23 @@ describe('web e2e: workspace management (create / rename / grouping / hover affo // Leaving anchor and card together closes it after the grace. await page.getByRole('button', { name: 'Account menu', exact: true }).hover() await expect.poll(() => card.count(), { timeout: 5_000 }).toBe(0) + // In a window too short for the card below the row's top, the card keeps + // its side and holds its bottom at the viewport's 8px margin. + const viewport = page.viewportSize() + const row = await sessionRow.boundingBox() + if (viewport === null || row === null) throw new Error('no viewport or row box') + await page.setViewportSize({ width: viewport.width, height: Math.ceil(row.y + row.height + 24) }) + try { + await sessionRow.hover() + await card.waitFor({ timeout: 5_000 }) + const held = await beside() + expect(held).toMatchObject({ gap: 8, bottomMargin: 8 }) + expect(held.top).toBeLessThan(0) + await page.mouse.move(viewport.width - 20, 4) + await expect.poll(() => card.count(), { timeout: 5_000 }).toBe(0) + } finally { + await page.setViewportSize(viewport) + } expect(tripwire.pageErrors).toEqual([]) }, 60_000) diff --git a/packages/client/ui-primitives/README.i18n.yaml b/packages/client/ui-primitives/README.i18n.yaml index 1b34ec58bd..9cc32a1ba4 100644 --- a/packages/client/ui-primitives/README.i18n.yaml +++ b/packages/client/ui-primitives/README.i18n.yaml @@ -18,8 +18,8 @@ en: 33a5b39959a595c6 zh: efd1088e9f13ed67 /deepseek-ai-dsh-client-ui-primitives/use-this-package/component-catalog: - en: 8b014a8f8d611bff - zh: eecf9f03115c80d4 + en: 07574e4640e01163 + zh: cc3f074a6ec0a17d /deepseek-ai-dsh-client-ui-primitives/use-this-package/controls-and-icons: en: fd3499ef403a0594 zh: 3a17727316d3c666 diff --git a/packages/client/ui-primitives/README.md b/packages/client/ui-primitives/README.md index dc58a3f6d7..c7745cac13 100644 --- a/packages/client/ui-primitives/README.md +++ b/packages/client/ui-primitives/README.md @@ -65,7 +65,7 @@ Check this table before writing a control in a feature package. A plugin cannot | `Modal` | Centered dialog over a page mask. A nested dialog can intercept keys with `onKeyDownCapture` before document Escape handlers. The tint and dialog fade in while backdrop blur stays fully applied, honoring reduced motion. Set `backdropBlur={false}` when the caller already blurs the source page. `tone="warning"` places an amber warning icon in the title and removes the body's extra top margin; other dialogs retain their spacing. | | `RiskConfirmation` | Sensitive action gated behind an explicit checkbox, using the shared warning-title layout. | | `Tooltip` | Hover and keyboard-focus text anchored to a cloned child; optional `delayMs` controls hover delay and `focusDelayMs` controls keyboard-focus delay, both defaulting to 0 ms. Optional `portal` rendering escapes clipping containers and ancestor stacking contexts that cap the bubble's z-index. | -| `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. A compact card opens beside the anchor's end edge, or beside its start edge when it would cross the viewport's end and fits there, as for rows of a panel at the window's end; with room on neither side it keeps to the viewport's end margin over the anchor. | +| `HoverCard`, `HoverCardGroup` | Readable, optionally copyable hover preview; a physical list can opt cards into shared first-display dwell and exclusive display. A compact card opens beside the anchor's end edge, or beside its start edge when it would cross the viewport's end and fits there, as for rows of a panel at the window's end; with room on neither side it opens below the anchor from the anchor's start edge, or above it without room below, so it does not cover the anchor; a card too tall for either stays inside the viewport, in its bottom end corner. CSS anchor positioning places it, so the card follows its anchor without script measurement; Firefox resolves the anchor without the transforms of its ancestors, so a compact card whose anchor sits under a transformed ancestor is misplaced there. | | `DraggableImage` | Original-image gestures with explicit transfer and feedback callbacks. | | `ImageLightbox` | Shared image modal with focus restoration and Escape dismissal. | | `usePointerGrace` | Cancelable dismissal delay that lets the pointer cross the gap between a trigger and its card; pending timers are cleared on unmount. | diff --git a/packages/client/ui-primitives/README.zh.md b/packages/client/ui-primitives/README.zh.md index 2a54435261..6fad582dde 100644 --- a/packages/client/ui-primitives/README.zh.md +++ b/packages/client/ui-primitives/README.zh.md @@ -65,7 +65,7 @@ kind: "package-library" | `Modal` | 页面遮罩之上的居中对话框。嵌套对话框可通过 `onKeyDownCapture` 在文档级 Escape 处理器之前拦截按键。 色层与弹窗淡入,背景模糊始终完整生效,并遵循减少动态效果偏好。调用方已模糊源页面时设置 `backdropBlur={false}`。`tone="warning"` 在标题中显示橙色警告图标,并移除正文额外的顶部间距;其他弹窗的间距保持不变。 | | `RiskConfirmation` | 以显式复选框把关的敏感操作确认,采用共用的警告标题布局。 | | `Tooltip` | 锚定在克隆子元素上的悬停与键盘聚焦提示;可选的 `delayMs` 控制悬停延迟,`focusDelayMs` 控制键盘聚焦延迟,均默认为 0 毫秒。可通过 `portal` 渲染到外层,避免被容器裁剪,或受祖先层叠上下文限制其 z-index。 | -| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。紧凑卡片出现在锚点结束一侧;会超出视口结束边缘、而开始一侧放得下时出现在开始一侧,例如窗口末端面板中的行;两侧都放不下时贴着视口结束边缘的留白,盖在锚点上。 | +| `HoverCard`、`HoverCardGroup` | 可阅读、可选带复制按钮的悬停预览;物理列表可选择让卡片共享首次显示等待,并互斥显示。紧凑卡片出现在锚点结束一侧;会超出视口结束边缘、而开始一侧放得下时出现在开始一侧,例如窗口末端面板中的行;两侧都放不下时出现在锚点下方,与锚点的开始边缘对齐,下方放不下则出现在上方,因此不会盖住锚点;高到上下都放不下的卡片留在视口内,位于底部结束一角。它由 CSS 锚点定位放置,卡片跟随锚点时不需要脚本测量;Firefox 解析锚点位置时不计入祖先元素的 transform,锚点位于带 transform 的祖先之内时,紧凑卡片在 Firefox 中的位置会偏移。 | | `DraggableImage` | 通过显式传递与反馈回调提供原图拖放。 | | `ImageLightbox` | 共享图片浮层,支持焦点恢复与 Esc 关闭。 | | `usePointerGrace` | 可取消的延迟关闭,让指针能够跨越触发控件与卡片间的空隙;卸载时清除待执行定时器。 | diff --git a/packages/client/ui-primitives/src/HoverCard.module.css b/packages/client/ui-primitives/src/HoverCard.module.css index e98ff29d69..176674d722 100644 --- a/packages/client/ui-primitives/src/HoverCard.module.css +++ b/packages/client/ui-primitives/src/HoverCard.module.css @@ -17,6 +17,48 @@ box-shadow: var(--dsw-shadow-lv3); } +/* A compact card sits beside its anchor's end edge with its top on the + anchor's top: the insets keep it 8px from the anchor and from the viewport's + edges. When that would cross the viewport, the first fallback that fits + places it: beside the start edge; on either side with its bottom at the + viewport's margin; then, with room on neither side, below the anchor from + the anchor's start edge, or above it, so the card does not cover its anchor. + A card too tall for that holds the viewport's bottom and end margins. + Chromium tries five fallbacks, so there the browser's own overflow shift + keeps such a card inside the viewport instead, against its edges. */ +.compact { + position-area: inline-end span-block-end; + inset: 0 8px 8px; + position-try-fallbacks: + flip-inline, + --dsh-hover-card-low, + --dsh-hover-card-low flip-inline, + --dsh-hover-card-below, + --dsh-hover-card-above, + --dsh-hover-card-held; +} + +@position-try --dsh-hover-card-low { + position-area: inline-end span-all; + align-self: end; +} + +@position-try --dsh-hover-card-below { + position-area: block-end span-inline-end; + inset: 8px 8px 8px 0; +} + +@position-try --dsh-hover-card-above { + position-area: block-start span-inline-end; + inset: 8px 8px 8px 0; +} + +@position-try --dsh-hover-card-held { + position-area: span-all; + justify-self: end; + align-self: end; +} + .copyable { cursor: pointer; } diff --git a/packages/client/ui-primitives/src/HoverCard.tsx b/packages/client/ui-primitives/src/HoverCard.tsx index 28031265c4..1bf15d713e 100644 --- a/packages/client/ui-primitives/src/HoverCard.tsx +++ b/packages/client/ui-primitives/src/HoverCard.tsx @@ -1,4 +1,4 @@ -import { useCallback, useContext, useEffect, useLayoutEffect, useRef, useState } from 'react' +import { useCallback, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react' import type { CSSProperties, ReactNode, RefObject, SyntheticEvent } from 'react' import clsx from 'clsx' import { createPortal } from 'react-dom' @@ -16,31 +16,19 @@ const INLINE_PREVIEW_WIDTH = 300 const ANCHOR_GAP = 8 const VIEWPORT_MARGIN = 8 -/** - * Left edge of a compact card: beside the anchor's end edge, or beside its start edge when the measured card would - * cross the viewport's end and fits before the anchor instead; with neither side fitting, against the viewport's end - * margin over the anchor, as long as the viewport is wider than the card. - * @param anchor - the anchor wrapper's rect. - * @param width - the card's measured width, 0 before it mounts. - * @returns the card's left edge in viewport pixels. - */ -function compactLeft(anchor: DOMRect, width: number): number { - const end = anchor.right + ANCHOR_GAP - const limit = window.innerWidth - VIEWPORT_MARGIN - if (end + width <= limit) return end - const start = anchor.left - ANCHOR_GAP - width - return start >= VIEWPORT_MARGIN ? start : Math.max(VIEWPORT_MARGIN, limit - width) -} - +/** Where the script places a card; a compact card has no coordinates, since the stylesheet anchors it. */ interface CardPosition { - left: number - top: number + left?: number + top?: number width?: number maxWidth?: number maxHeight?: number bridge?: { left: number; top: number; width: number; height: number } } +/** The position of every compact card: one value, so placing it again renders nothing. */ +const ANCHORED: CardPosition = {} + /** * Render an anchor with a hover-triggered preview card independently of nested tooltips. * Touch entry does not open a preview or intercept the anchor's action. @@ -49,9 +37,10 @@ interface CardPosition { * readable and selectable, but it carries no dismissal affordance of its own. * @param props.openDelayMs - hover dwell before the card shows (default 500). * @param props.variant - compact card beside the anchor's end edge, or its start edge when only that side fits, or - * over the anchor at the viewport's end margin when neither fits; or a preview above/below it - * with 24px side insets, a 420px height cap, the frame-top clearance (capped below an anchor inside the top strip), - * and 100ms opacity transitions. + * below the anchor, else above it, when neither side fits, or in the viewport's bottom end corner when it is too + * tall for those, which the stylesheet decides by CSS anchor positioning; or a preview above/below it with 24px + * side insets, a 420px height cap, the frame-top clearance (capped below an anchor inside the top strip), and 100ms + * opacity transitions. * @param props.widthAnchorRef - optional element whose width and horizontal position size the preview. * @param props.inline - keep the anchor in prose; show a contained preview on hover or keyboard focus. * Its hover region connects the anchor and preview across the visual gap. @@ -84,6 +73,8 @@ export function HoverCard({ copyLabel?: string copiedLabel?: string })) { + const compact = variant !== 'preview' && !inline + const anchorName = `--dsh-hover-card-${useId().replaceAll(':', '')}` const rootRef = useRef(null) const cardRef = useRef(null) const portalRef = useRef(null) @@ -185,6 +176,8 @@ export function HoverCard({ // Fixed-position from the anchor rect before paint; track the anchor while // open (capture-phase scroll catches nested panes), as in Menu portal mode. + // The stylesheet anchors a compact card, so it needs neither the rect nor + // the tracking. useLayoutEffect(() => { if (!open) { setPos(null); return } const place = () => { @@ -195,6 +188,10 @@ export function HoverCard({ dismissImmediately() return } + if (compact) { + setPos(ANCHORED) + return + } const r = wrapper.getBoundingClientRect() const h = cardRef.current?.offsetHeight ?? 0 if (variant === 'preview') { @@ -213,32 +210,27 @@ export function HoverCard({ }) return } - if (inline) { - const height = Math.max(h, cardRef.current?.scrollHeight ?? 0) - const maxWidth = Math.max(0, Math.min(INLINE_PREVIEW_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2)) - const width = fitContent ? Math.min(cardRef.current?.offsetWidth ?? maxWidth, maxWidth) : maxWidth - const topMargin = overlayTopMargin(VIEWPORT_MARGIN, r, ANCHOR_GAP) - const belowTop = Math.max(topMargin, r.bottom + ANCHOR_GAP) - const above = Math.max(0, r.top - ANCHOR_GAP - topMargin) - const below = Math.max(0, window.innerHeight - belowTop - VIEWPORT_MARGIN) - const onTop = height > below && above > below - const maxHeight = onTop ? above : below - const left = Math.max(VIEWPORT_MARGIN, Math.min(r.left, window.innerWidth - width - VIEWPORT_MARGIN)) - const top = onTop ? r.top - ANCHOR_GAP - Math.min(height, maxHeight) : belowTop - const bridgeTop = onTop ? top + Math.min(height, maxHeight) : r.bottom - const bridgeLeft = Math.min(r.left, left) - setPos({ - left, top, ...fitContent ? {} : { width }, maxWidth, maxHeight, - bridge: { - left: bridgeLeft, top: bridgeTop, - width: Math.max(r.right, left + width) - bridgeLeft, - height: Math.max(0, (onTop ? r.top : top) - bridgeTop), - }, - }) - return - } - const top = r.top + h > window.innerHeight - VIEWPORT_MARGIN ? window.innerHeight - h - VIEWPORT_MARGIN : r.top - setPos({ left: compactLeft(r, cardRef.current?.offsetWidth ?? 0), top }) + const height = Math.max(h, cardRef.current?.scrollHeight ?? 0) + const maxWidth = Math.max(0, Math.min(INLINE_PREVIEW_WIDTH, window.innerWidth - VIEWPORT_MARGIN * 2)) + const width = fitContent ? Math.min(cardRef.current?.offsetWidth ?? maxWidth, maxWidth) : maxWidth + const topMargin = overlayTopMargin(VIEWPORT_MARGIN, r, ANCHOR_GAP) + const belowTop = Math.max(topMargin, r.bottom + ANCHOR_GAP) + const above = Math.max(0, r.top - ANCHOR_GAP - topMargin) + const below = Math.max(0, window.innerHeight - belowTop - VIEWPORT_MARGIN) + const onTop = height > below && above > below + const maxHeight = onTop ? above : below + const left = Math.max(VIEWPORT_MARGIN, Math.min(r.left, window.innerWidth - width - VIEWPORT_MARGIN)) + const top = onTop ? r.top - ANCHOR_GAP - Math.min(height, maxHeight) : belowTop + const bridgeTop = onTop ? top + Math.min(height, maxHeight) : r.bottom + const bridgeLeft = Math.min(r.left, left) + setPos({ + left, top, ...fitContent ? {} : { width }, maxWidth, maxHeight, + bridge: { + left: bridgeLeft, top: bridgeTop, + width: Math.max(r.right, left + width) - bridgeLeft, + height: Math.max(0, (onTop ? r.top : top) - bridgeTop), + }, + }) } place() // Observe only the anchor's ancestors: an offscreen drawer can hide without resizing its retained row. @@ -246,34 +238,21 @@ export function HoverCard({ for (let ancestor = rootRef.current?.parentElement; ancestor != null; ancestor = ancestor.parentElement) { visibility.observe(ancestor, { attributes: true, attributeFilter: ['inert', 'hidden'] }) } - const observer = (variant === 'preview' || inline) && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(place) : null + const observer = !compact && typeof ResizeObserver !== 'undefined' ? new ResizeObserver(place) : null for (const element of [cardRef.current, rootRef.current, widthAnchorRef?.current]) { if (element !== null && element !== undefined) observer?.observe(element) } - window.addEventListener('scroll', place, true) - window.addEventListener('resize', place) + if (!compact) { + window.addEventListener('scroll', place, true) + window.addEventListener('resize', place) + } return () => { observer?.disconnect() visibility.disconnect() window.removeEventListener('scroll', place, true) window.removeEventListener('resize', place) } - }, [open, variant, widthAnchorRef, positioned, inline, fitContent, dismissImmediately]) - - // The first placement ran before the card mounted (size read 0): once the - // card's real size is measurable, correct the bottom-edge clamp and the side. - // The correction converges — a corrected position satisfies both guards, so it runs once. - useLayoutEffect(() => { - if (!open || pos === null || variant === 'preview' || inline) return - const card = cardRef.current - const anchor = rootRef.current - /* v8 ignore next -- the card and anchor are mounted whenever pos is set, so the refs are attached here. */ - if (card === null || anchor === null) return - const h = card.offsetHeight - const left = compactLeft(anchor.getBoundingClientRect(), card.offsetWidth) - const top = pos.top + h > window.innerHeight - VIEWPORT_MARGIN ? window.innerHeight - h - VIEWPORT_MARGIN : pos.top - if (left !== pos.left || top !== pos.top) setPos({ left, top }) - }, [open, pos, variant, inline]) + }, [open, compact, variant, widthAnchorRef, positioned, fitContent, dismissImmediately]) const copy = async (text: string): Promise => { if (copied || copyingRef.current) return @@ -300,9 +279,13 @@ export function HoverCard({ const card = open && pos !== null && (
{ if (!disabled && event.target.matches(':focus-visible')) { cancelClose(); setPhase('open') } } : undefined} diff --git a/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts b/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts new file mode 100644 index 0000000000..8897727435 --- /dev/null +++ b/packages/client/ui-primitives/tests/hover-card-styles.client.spec.ts @@ -0,0 +1,50 @@ +/** + * The compact HoverCard's placement as CSS text: the component suite sees CSS + * Modules as class-name maps and jsdom lays out nothing, so only the stylesheet + * proves which positions the browser tries, and in which order. + */ +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const css = readFileSync(fileURLToPath(new URL('../src/HoverCard.module.css', import.meta.url)), 'utf8').replace(/\/\*[\s\S]*?\*\//g, ' ') + +function declarations(selector: string): Map { + const found = new Map() + for (const [, selectorList = '', body = ''] of css.matchAll(/([^{}]+)\{([^{}]*)\}/g)) { + if (!selectorList.split(',').map(value => value.trim()).includes(selector)) continue + for (const part of body.split(';')) { + const colon = part.indexOf(':') + if (colon !== -1) found.set(part.slice(0, colon).trim(), part.slice(colon + 1).trim().replace(/\s+/g, ' ')) + } + } + return found +} + +describe('HoverCard.module.css', () => { + it('places a compact card beside its anchor\'s end edge, top on the anchor\'s top, 8px from the anchor and the viewport', () => { + expect(declarations('.card').get('position')).toBe('fixed') + const compact = declarations('.compact') + expect([compact.get('position-area'), compact.get('inset')]).toEqual(['inline-end span-block-end', '0 8px 8px']) + }) + + it('tries the start side, then a bottom-held card on either side, then below the anchor and above it, then the viewport\'s corner', () => { + expect(declarations('.compact').get('position-try-fallbacks')).toBe( + 'flip-inline, --dsh-hover-card-low, --dsh-hover-card-low flip-inline, --dsh-hover-card-below, --dsh-hover-card-above, --dsh-hover-card-held', + ) + const low = declarations('@position-try --dsh-hover-card-low') + expect([low.get('position-area'), low.get('align-self')]).toEqual(['inline-end span-all', 'end']) + }) + + it('keeps a card that fits on neither side off its anchor: 8px below or above it, from the anchor\'s start edge', () => { + const below = declarations('@position-try --dsh-hover-card-below') + expect([below.get('position-area'), below.get('inset')]).toEqual(['block-end span-inline-end', '8px 8px 8px 0']) + const above = declarations('@position-try --dsh-hover-card-above') + expect([above.get('position-area'), above.get('inset')]).toEqual(['block-start span-inline-end', '8px 8px 8px 0']) + }) + + it('holds a card too tall to go below or above its anchor at the viewport\'s bottom and end margins, as the last fallback', () => { + const held = declarations('@position-try --dsh-hover-card-held') + expect([held.get('position-area'), held.get('justify-self'), held.get('align-self')]).toEqual(['span-all', 'end', 'end']) + }) +}) diff --git a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx index 9eec5fa2d6..a5ad226fab 100644 --- a/packages/client/ui-primitives/tests/hover-card.client.spec.tsx +++ b/packages/client/ui-primitives/tests/hover-card.client.spec.tsx @@ -137,8 +137,9 @@ describe('HoverCard', () => { expect(screen.getByText('card body')).toBeTruthy() }) - it('opens after the dwell delay, positioned right of the anchor', () => { + it('opens after the dwell delay, anchored to its wrapper by name for the stylesheet to place', () => { const { wrapper } = mount() + expect(wrapper.style.anchorName).toBe('') fireEvent.pointerEnter(wrapper) expect(screen.queryByText('card body')).toBeNull() act(() => { vi.advanceTimersByTime(499) }) @@ -146,8 +147,29 @@ describe('HoverCard', () => { act(() => { vi.advanceTimersByTime(1) }) const card = screen.getByText('card body').parentElement as HTMLElement expect(card.parentElement?.parentElement).toBe(document.body) - expect(card.style.left).toBe('208px') - expect(card.style.top).toBe('40px') + // The stylesheet places a compact card against the named anchor, so the script gives it no coordinates. + expect(wrapper.style.anchorName).toMatch(/^--dsh-hover-card-/) + expect(card.style.positionAnchor).toBe(wrapper.style.anchorName) + expect([card.style.left, card.style.top]).toEqual(['', '']) + // The name lasts as long as the card. + fireEvent.pointerLeave(wrapper) + act(() => { vi.advanceTimersByTime(POINTER_GRACE_MS) }) + expect(wrapper.style.anchorName).toBe('') + }) + + it('gives each compact card its own anchor name', () => { + render( + <> + first} content={
first body
} /> + second} content={
second body
} /> + , + ) + const wrappers = ['first', 'second'].map(text => screen.getByText(text).parentElement as HTMLElement) + for (const wrapper of wrappers) fireEvent.pointerEnter(wrapper) + act(() => { vi.advanceTimersByTime(500) }) + const names = wrappers.map(wrapper => wrapper.style.anchorName) + expect(new Set(names).size).toBe(2) + expect(['first body', 'second body'].map(text => (screen.getByText(text).parentElement as HTMLElement).style.positionAnchor)).toEqual(names) }) it('insets a preview by 24px on each side and follows anchor resizing', () => { @@ -600,76 +622,18 @@ describe('HoverCard', () => { expect(screen.queryByText('card body')).toBeNull() }) - it('corrects the bottom-edge clamp once the mounted card height is measurable', () => { - // First placement reads height 0 (card not yet mounted) and keeps the - // anchor top; the post-mount correction re-clamps with the real height. - window.innerHeight = 300 - const offsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight')! - Object.defineProperty(HTMLElement.prototype, 'offsetHeight', { configurable: true, get: () => 120 }) - try { - const { wrapper } = mount() - stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) - fireEvent.pointerEnter(wrapper) - act(() => { vi.advanceTimersByTime(500) }) - const card = screen.getByText('card body').parentElement as HTMLElement - // 300 - 120 - 8 = 172, instead of the anchor top 280. - expect(card.style.top).toBe('172px') - } finally { - Object.defineProperty(HTMLElement.prototype, 'offsetHeight', offsetHeight) - } - }) - - it('opens on the anchor\'s start side once the measured card would cross the viewport\'s end, and over the anchor when neither side fits', () => { - window.innerWidth = 1000 - const offsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth')! - Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { configurable: true, get: () => 244 }) - try { - const { wrapper } = mount() - // The anchor spans 880–980: 988 + 244 crosses 1000 - 8, and 880 - 8 - 244 = 628 fits. - stubAnchorRect(screen.getByText('row'), { top: 40, right: 980 }) - fireEvent.pointerEnter(wrapper) - act(() => { vi.advanceTimersByTime(500) }) - const card = screen.getByText('card body').parentElement as HTMLElement - expect(card.style.left).toBe('628px') - // Placement on scroll keeps the start side with the card already measured. - act(() => { fireEvent.scroll(document) }) - expect(card.style.left).toBe('628px') - // With room on neither side, the card keeps to the viewport's end margin: 400 - 8 - 244 = 148. - stubAnchorRect(screen.getByText('row'), { top: 40, right: 300 }) - window.innerWidth = 400 - act(() => { fireEvent.resize(window) }) - expect(card.style.left).toBe('148px') - // A viewport narrower than the card keeps its start margin. - window.innerWidth = 200 - act(() => { fireEvent.resize(window) }) - expect(card.style.left).toBe('8px') - } finally { - Object.defineProperty(HTMLElement.prototype, 'offsetWidth', offsetWidth) - window.innerWidth = 1024 - } - }) - - it('clamps inside placement itself when the card is already measured (resize path)', () => { - window.innerHeight = 300 + it('measures nothing for a compact card: not at open, on scroll, or on resize', () => { const { wrapper } = mount() - stubAnchorRect(screen.getByText('row'), { top: 280, right: 200 }) + const rect = vi.spyOn(wrapper, 'getBoundingClientRect') + const listen = vi.spyOn(window, 'addEventListener') fireEvent.pointerEnter(wrapper) act(() => { vi.advanceTimersByTime(500) }) const card = screen.getByText('card body').parentElement as HTMLElement - Object.defineProperty(card, 'offsetHeight', { value: 120 }) - act(() => { fireEvent.resize(window) }) - expect(card.style.top).toBe('172px') - }) - - it('repositions on capture-phase scroll while open and stops listening after close', () => { - const { wrapper } = mount() - fireEvent.pointerEnter(wrapper) - act(() => { vi.advanceTimersByTime(500) }) - stubAnchorRect(screen.getByText('row'), { top: 90, right: 300 }) act(() => { fireEvent.scroll(document) }) - const card = screen.getByText('card body').parentElement as HTMLElement - expect(card.style.left).toBe('308px') - expect(card.style.top).toBe('90px') + act(() => { fireEvent.resize(window) }) + expect(rect).not.toHaveBeenCalled() + expect(listen.mock.calls.map(([type]) => type).filter(type => type === 'scroll' || type === 'resize')).toEqual([]) + expect([card.style.left, card.style.top]).toEqual(['', '']) fireEvent.pointerLeave(wrapper) act(() => { vi.advanceTimersByTime(POINTER_GRACE_MS) }) expect(screen.queryByText('card body')).toBeNull()