// // Copyright 2026 DXOS.org // import { expect, userEvent, waitFor, within } from 'storybook/test'; import { type Size } from '../sizes.ts'; /** Expected geometry per size in px (decision 12); asserting literals checks the theme, not just self-consistency. */ export const GEOMETRY: Record = { xs: { block: 20, inset: 1, icon: 12 }, sm: { block: 24, inset: 2, icon: 14 }, md: { block: 32, inset: 2, icon: 16 }, lg: { block: 40, inset: 3, icon: 20 }, xl: { block: 48, inset: 3, icon: 24 }, }; /** Control height per size: the block less its inset on both sides. */ export const controlSize = (size: Size) => GEOMETRY[size].block - 2 * GEOMETRY[size].inset; /** * A trailing icon (a control's caret, trigger or stepper; a row's icon-only action) sits in the block-wide end cell of * whatever ends at `end`: its centre half a block from that edge and its box the control icon size, so every trailing * icon of a form column shares one column and one size. */ export const expectEndCell = async (icon: Element | null | undefined, end: number, size: Size, message: string) => { const box = icon?.getBoundingClientRect(); await expect(box && box.left + box.width / 2, `${message} centre`).toBeCloseTo(end - GEOMETRY[size].block / 2, 0); await expect(box?.width, `${message} icon`).toBeCloseTo(GEOMETRY[size].icon, 0); }; export const byTestId = (root: HTMLElement, testId: string) => { const element = root.querySelector(`[data-testid="${testId}"]`); if (!element) { throw new Error(`missing ${testId}`); } return element; }; /** The `withSizes` row (`stories.tsx`) holding the story rendered at `size`. */ export const sizeRow = (root: HTMLElement, size: Size) => byTestId(root, `size-${size}`); export const centreY = (rect: DOMRect) => rect.top + rect.height / 2; export const centreX = (rect: DOMRect) => rect.left + rect.width / 2; /** * The surface a popup is painted on: the popup itself, or the ScrollArea frame of a scrolling popup (Menu, Select, * Combobox), whose viewport is the Ark content. */ export const popupFrame = (popup: HTMLElement) => popup.closest('.dx-popup') ?? popup; /** * Asserts a popup renders at `size` (Phase 4 decision 2): its surface carries the `data-size` and resolves that size's * block, so its rows take that size's metrics. */ export const expectPopupSize = async (popup: HTMLElement, size: Size) => { const frame = popupFrame(popup); await expect(frame).toHaveAttribute('data-size', size); await expect(getComputedStyle(frame).getPropertyValue('--dx-block-size')).toBe(`${GEOMETRY[size].block / 16}rem`); }; /** A popup's arrow part, if it renders one; a scrolling popup draws it in its frame, outside the clipping viewport. */ const arrowOf = (popup: HTMLElement) => popupFrame(popup).querySelector('[data-part="arrow"]'); /** The popup's box grown by its arrow, whose outer edge is the popup's edge facing the anchor. */ const withArrow = (popup: HTMLElement) => { const rect = popupFrame(popup).getBoundingClientRect(); const arrow = arrowOf(popup)?.getBoundingClientRect(); return { top: Math.min(rect.top, arrow?.top ?? rect.top), bottom: Math.max(rect.bottom, arrow?.bottom ?? rect.bottom), }; }; /** Floating UI's default `overflowPadding`: a popup is shifted to keep this far from the viewport edge. */ const OVERFLOW_PADDING = 8; /** * Waits until `popup` sits 0–3px below `anchor` (the 2px gutter plus rounding) with its start edge or centre aligned * to the anchor's, allowing only the shift that keeps it inside the viewport; an unpositioned popup sits at the * viewport origin and fails. */ export const expectAnchoredBelow = async ( anchor: HTMLElement, popup: HTMLElement, align: 'start' | 'center' = 'start', ) => { await waitFor(async () => { const anchorRect = anchor.getBoundingClientRect(); const popupRect = popup.getBoundingClientRect(); const gap = withArrow(popup).top - anchorRect.bottom; const ideal = align === 'start' ? anchorRect.left : centreX(anchorRect) - popupRect.width / 2; const maxLeft = popup.ownerDocument.documentElement.clientWidth - OVERFLOW_PADDING - popupRect.width; const expected = Math.min(Math.max(ideal, OVERFLOW_PADDING), maxLeft); const where = `popup ${JSON.stringify(popupRect)}, anchor ${JSON.stringify(anchorRect)}`; await expect(gap >= 0 && gap <= 3, `gap ${gap}: ${where}`).toBe(true); await expect(Math.abs(popupRect.left - expected) <= 1, `left ${popupRect.left} != ${expected}: ${where}`).toBe( true, ); }); }; type ArrowSide = 'top' | 'right' | 'bottom' | 'left'; const ARROW_SIDES: readonly ArrowSide[] = ['top', 'right', 'bottom', 'left']; const isArrowSide = (value: string | null): value is ArrowSide => ARROW_SIDES.some((side) => side === value); /** * Per side a popup opens on: a box's distance from the anchor (`gap`), its edge facing the anchor (`edge`), and the * axis along which the arrow is centred on the anchor (`across`). */ const ARROW_AXIS: Record< ArrowSide, { gap: (anchor: DOMRect, box: DOMRect) => number; edge: (box: DOMRect) => number; across: 'x' | 'y' } > = { bottom: { gap: (anchor, box) => box.top - anchor.bottom, edge: (box) => box.top, across: 'x' }, top: { gap: (anchor, box) => anchor.top - box.bottom, edge: (box) => box.bottom, across: 'x' }, right: { gap: (anchor, box) => box.left - anchor.right, edge: (box) => box.left, across: 'y' }, left: { gap: (anchor, box) => anchor.left - box.right, edge: (box) => box.right, across: 'y' }, }; /** * Asserts `popup` shows an arrow in its own surface colour on the side facing `anchor` (any of the four), within the * anchor's span and with its tip 0–3px (the gutter) from it; the popup body keeps the arrow's half-size further off. * The arrow sits under the popup's content but over its surface, so the popup must be a stacking context: otherwise * the surface and its ring paint over the arrow's base and leave only a sliver of it. */ export const expectArrow = async (anchor: HTMLElement, popup: HTMLElement) => { const arrow = arrowOf(popup); await expect(arrow, 'arrow').not.toBeNull(); const frame = popupFrame(popup); const tip = arrow?.querySelector('[data-part="arrow-tip"]'); await expect(tip && getComputedStyle(tip).backgroundColor).toBe(getComputedStyle(frame).backgroundColor); await expect(arrow?.parentElement && getComputedStyle(arrow.parentElement).isolation, 'arrow stacking context').toBe( 'isolate', ); await waitFor(async () => { const anchorRect = anchor.getBoundingClientRect(); const popupRect = frame.getBoundingClientRect(); const arrowRect = arrow?.getBoundingClientRect() ?? popupRect; const dataSide = popup.getAttribute('data-side'); const side = isArrowSide(dataSide) ? dataSide : popupRect.top >= anchorRect.bottom ? 'bottom' : 'top'; const { gap, edge, across } = ARROW_AXIS[side]; const tipGap = gap(anchorRect, arrowRect); const bodyGap = gap(anchorRect, popupRect); const half = (across === 'x' ? arrowRect.height : arrowRect.width) / 2; const where = `${side}: arrow ${JSON.stringify(arrowRect)}, popup ${JSON.stringify(popupRect)}, anchor ${JSON.stringify(anchorRect)}`; await expect(tipGap >= 0 && tipGap <= 3, `tip gap ${tipGap}: ${where}`).toBe(true); await expect(bodyGap - tipGap, `arrow overhang: ${where}`).toBeCloseTo(half, 0); // The rotated tip's corners touch the arrow box, so it overhangs neither the box nor the gutter. const tipRect = tip?.getBoundingClientRect(); await expect( Math.abs((tipRect ? edge(tipRect) : Number.NaN) - edge(arrowRect)) <= 0.5, `tip overhang: ${where}`, ).toBe(true); const centre = across === 'x' ? centreX(arrowRect) : centreY(arrowRect); const [start, end] = across === 'x' ? [anchorRect.left, anchorRect.right] : [anchorRect.top, anchorRect.bottom]; await expect(centre >= start && centre <= end, `arrow centre ${centre}: ${where}`).toBe(true); }); }; /** * Asserts a long popup scrolls in a Next ScrollArea (DESIGN.md follow-up 49): its viewport (the Ark content) overflows, * shows no native bar, and keeps the highlighted item in view while ArrowDown walks `steps` items past the fold. */ export const expectScrollingPopup = async (popup: HTMLElement, steps: number) => { await expect(popup).toHaveClass('dx-scroll-viewport'); // A direct child: a dev slot-warning wrapper in between would break the frame's child rules. await expect(popup.parentElement).toBe(popupFrame(popup)); await expect(popup.scrollHeight, 'popup overflows').toBeGreaterThan(popup.clientHeight); await expect(getComputedStyle(popup).scrollbarWidth, 'no native scrollbar').toBe('none'); for (let step = 0; step < steps; step++) { await userEvent.keyboard('{ArrowDown}'); } await waitFor(async () => { const item = popup.querySelector('[data-highlighted]'); await expect(item, 'highlighted item').not.toBeNull(); const itemRect = item?.getBoundingClientRect() ?? new DOMRect(); const viewRect = popup.getBoundingClientRect(); const where = `item ${JSON.stringify(itemRect)}, viewport ${JSON.stringify(viewRect)}`; await expect(popup.scrollTop, `scrolled: ${where}`).toBeGreaterThan(0); await expect(itemRect.top >= viewRect.top - 0.5 && itemRect.bottom <= viewRect.bottom + 0.5, where).toBe(true); }); await expectThumbReserve(popup); }; /** * Asserts an overflowing popup's overlay thumb sits inside the viewport's inset focus ring, and that the popup reserves * the thumb's strip so no item (nor its last part, e.g. a shortcut) reaches the thumb. */ export const expectThumbReserve = async (popup: HTMLElement) => { await waitFor(async () => { const thumb = popupFrame(popup).querySelector('[data-scroll-thumb="vertical"]'); await expect(thumb, 'vertical thumb').not.toBeNull(); await expect(popupFrame(popup)).toHaveAttribute('data-overflow-y'); const thumbRect = thumb?.getBoundingClientRect() ?? new DOMRect(); const ring = parseFloat(getComputedStyle(popup).getPropertyValue('--dx-focus-ring-width')); await expect(ring, 'focus ring width').toBeGreaterThan(0); await expect(thumbRect.right, 'thumb inside ring').toBeLessThanOrEqual( popup.getBoundingClientRect().right - ring + 0.5, ); const items = popup.querySelectorAll('[role="option"], [role^="menuitem"]'); await expect(items.length, 'items').toBeGreaterThan(0); for (const item of items) { for (const part of [item, item.lastElementChild]) { await expect(part?.getBoundingClientRect().right ?? Infinity, 'item clears the thumb').toBeLessThanOrEqual( thumbRect.left + 0.5, ); } } }); }; /** Asserts a popup that fits shows no thumb and reserves no strip for one. */ export const expectNonScrollingPopup = async (popup: HTMLElement) => { await expect(popup.scrollHeight, 'popup fits').toBeLessThanOrEqual(popup.clientHeight); await expect(popupFrame(popup)).not.toHaveAttribute('data-overflow-y'); await expect(popupFrame(popup).querySelector('[data-scroll-thumb]')).toBeNull(); // Its inline inset is the same on both sides; a reserved strip would widen only the end. const style = getComputedStyle(popup); await expect(style.paddingRight, 'no reserve').toBe(style.paddingLeft); }; /** Hovers with a real pointer (the storybook runner's Playwright), since synthetic events never apply `:hover`. */ export const realHover = async (element: HTMLElement) => { const { userEvent: pointer } = await import('vitest/browser'); await pointer.hover(element); }; /** Moves the real pointer off `element` (to the page's top-left corner), so `pointerleave` and `:hover` follow. */ export const realUnhover = async (element: HTMLElement) => { const { userEvent: pointer } = await import('vitest/browser'); await pointer.unhover(element); }; /** * Records "ResizeObserver loop" errors from now until the returned check runs, which fails if any arrived; the browser * reports them as window `error` events, which the runner logs without failing the test. */ export const watchResizeObserverLoop = (root: HTMLElement) => { const view = root.ownerDocument.defaultView ?? window; const messages: string[] = []; const listener = (event: ErrorEvent) => { if (event.message.includes('ResizeObserver loop')) { messages.push(event.message); } }; view.addEventListener('error', listener); return async () => { // A loop is reported at the end of the frame that caused it. await new Promise((resolve) => view.requestAnimationFrame(() => view.requestAnimationFrame(resolve))); view.removeEventListener('error', listener); await expect(messages, 'ResizeObserver loop errors').toEqual([]); }; }; // Theme utilities share the `dx-` prefix but style any element (a story's layout wrapper), so they mark no part. const THEME_UTILITY = /^dx-(scope|expand|fill|fullscreen|grow|shrink|.+-surface)$/; /** Every themed part carries Ark's scope/part attributes (decision 10). */ export const expectScoped = async (root: HTMLElement) => { for (const part of root.querySelectorAll('[class*="dx-"]')) { const themed = [...part.classList].some((name) => name.startsWith('dx-') && !THEME_UTILITY.test(name)); if (themed) { await expect(part.hasAttribute('data-scope'), part.className).toBe(true); } } }; /** Icons without a label are decorative and hidden from assistive tech (decision 9). */ export const expectDecorativeIconsHidden = async (root: HTMLElement) => { for (const icon of root.querySelectorAll('svg[data-scope="icon"]:not([aria-label])')) { await expect(icon.getAttribute('aria-hidden')).toBe('true'); } }; /** Watches for `ms` and fails if any tooltip appears meanwhile, even briefly (a flash). */ export const expectNoTooltip = async (root: HTMLElement, ms = 500) => { const doc = root.ownerDocument; let seen = doc.querySelector('[role="tooltip"]') !== null; const observer = new MutationObserver(() => { seen ||= doc.querySelector('[role="tooltip"]') !== null; }); observer.observe(doc.body, { childList: true, subtree: true, attributes: true }); await new Promise((resolve) => setTimeout(resolve, ms)); observer.disconnect(); await expect(seen, 'a tooltip appeared').toBe(false); }; /** Waits for the one open tooltip to show `text` within the 2px gutter (+ rounding) of `trigger`, and returns it. */ export const expectTooltip = async (trigger: HTMLElement, text: string) => { const body = within(trigger.ownerDocument.body); await waitFor(() => expect(body.getByRole('tooltip')).toHaveTextContent(text)); const tooltip = body.getByRole('tooltip'); await waitFor(() => { const anchor = trigger.getBoundingClientRect(); const popup = withArrow(tooltip); const gap = Math.max(popup.top - anchor.bottom, anchor.top - popup.bottom); return expect(gap >= 0 && gap <= 3).toBe(true); }); return tooltip; };