An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] DropdownMenuSubMenu: docs match the shipped props and RTL flyout placement is measured (#8227)
Cindy Zhanga8b78c5e5b10
diff --git a/.changeset/dropdown-menu-submenu-docs.md b/.changeset/dropdown-menu-submenu-docs.mdnew file mode 100644index 0000000000..22854c11e3--- /dev/null+++ b/.changeset/dropdown-menu-submenu-docs.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[docs] `DropdownMenuSubMenu`'s documentation marks `label` and `children` as required, as its props type already does, and documents `menuDataTestId`, the test id for the sub-menu's own menu (the flyout, or the drilled-in list on a phone). The `presentation` prop's JSDoc now declares its `'adaptive'` default.++@cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d3b49978a2..3ea307eb17 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -3179,6 +3179,38 @@ jobs:retention-days: 30if-no-files-found: error+ # DropdownMenuSubMenu owns one menuitem row that reveals its own rows: the+ # popup state and wiring, the flyout beside the row, the drilled-in view,+ # the caret or spinner, and disabled paint. DropdownMenu owns the root+ # surface, the drill-in stack, and root keyboard navigation.+ - name: Run DropdownMenuSubMenu audit browser evidence+ if: ${{ !cancelled() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] DropdownMenuSubMenu:') }}+ env:+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ run: |+ status=0+ node .github/scripts/accessibility-audit.js \+ --storybook-dir apps/storybook/dist \+ --output dropdown-menu-submenu-a11y-report.json \+ --components DropdownMenuSubMenu \+ --baseline .github/a11y-baseline.json \+ --fail-on-new || status=1+ pnpm exec playwright test \+ packages/core/src/DropdownMenu/__tests__/DropdownMenuSubMenuAudit.a11y.chromium.spec.ts \+ --project chromium || status=1+ exit "$status"++ - name: Upload DropdownMenuSubMenu audit evidence+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] DropdownMenuSubMenu:')+ uses: actions/upload-artifact@v7+ with:+ name: dropdown-menu-submenu-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: |+ dropdown-menu-submenu-a11y-report.json+ dropdown-menu-submenu-audit-evidence/+ retention-days: 30+ if-no-files-found: error+# ContextMenu owns pointer and touch presentations across cursor anchoring,# selectable rows, sections, inline triggers, RTL, and narrow viewports.# Its audit lane binds the rendered matrix to the exact pull-request head.diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex 3f2beda80c..fad0dee4de 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -241,6 +241,18 @@"overlayRoot": "body"}},+ {+ "component": "DropdownMenuSubMenu",+ "storyId": "core-dropdownmenusubmenu--row-states",+ "dims": ["D4"],+ "setup": {+ "click": "[role=\"menuitem\"]:has-text(\"Share\")"+ },+ "selectors": {+ "overlay": "[data-testid=\"dropdown-menu-submenu-flyout\"]",+ "overlayRoot": "[role=\"menu\"]"+ }+ },{"component": "Layer","storyId": "core-layer--placements",diff --git a/apps/storybook/stories/DropdownMenuSubMenu.stories.tsx b/apps/storybook/stories/DropdownMenuSubMenu.stories.tsxnew file mode 100644index 0000000000..e2122f316a--- /dev/null+++ b/apps/storybook/stories/DropdownMenuSubMenu.stories.tsx@@ -0,0 +1,141 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DropdownMenuSubMenu.stories.tsx+ * @input One open menu whose sub-menu rows cover icon, description, loading, disabled, long-label, nested, and caller-callback states+ * @output Component-owned rendered evidence for DropdownMenuSubMenu rows, flyouts, and drilled-in views at each menu size+ * @position Storybook audit surface; header-and-footer sub-menus keep their DropdownMenu stories+ */++import type {Meta, StoryObj} from '@storybook/react';+import {useState} from 'react';+import {expect, within} from 'storybook/test';+import {+ DropdownMenu,+ DropdownMenuItem,+ DropdownMenuSubMenu,+ type DropdownMenuSubMenuPresentation,+} from '@astryxdesign/core/DropdownMenu';++type RowStatesArgs = {+ size: 'sm' | 'md' | 'lg';+ presentation: DropdownMenuSubMenuPresentation;+};++const meta: Meta<RowStatesArgs> = {+ title: 'Core/DropdownMenuSubMenu',+ tags: ['autodocs', 'visual-theme-matrix'],+ parameters: {+ // The menu opens from the inline start of the canvas so a flyout has room+ // beside its row in both directions; the viewport flip stays reachable at+ // narrow widths.+ layout: 'padded',+ docs: {+ description: {+ component:+ 'A menu row that reveals its own rows: a flyout beside the row, or a drilled-in view led by a Back row. The row owns its menuitem semantics, popup state, caret or spinner, and disabled paint; DropdownMenu owns the root surface and the drill-in stack.',+ },+ },+ },+ argTypes: {+ size: {control: 'inline-radio', options: ['sm', 'md', 'lg']},+ presentation: {+ control: 'inline-radio',+ options: ['adaptive', 'flyout', 'drill-in'],+ },+ },+ args: {size: 'md', presentation: 'adaptive'},+};++export default meta;+type Story = StoryObj<RowStatesArgs>;++function RowStatesFixture({size, presentation}: RowStatesArgs) {+ const [isMenuOpen, setIsMenuOpen] = useState(true);+ const [picked, setPicked] = useState('none');+ const [openCount, setOpenCount] = useState(0);+ const [closeCount, setCloseCount] = useState(0);+ // The Share sub-menu reports every open and close, so browser evidence can+ // observe the callback contract alongside the rendered state.+ const handleOpenChange = (isOpen: boolean) => {+ if (isOpen) {+ setOpenCount(count => count + 1);+ } else {+ setCloseCount(count => count + 1);+ }+ };+ return (+ <div+ data-testid="dropdown-menu-submenu-audit"+ data-picked={picked}+ data-open-count={openCount}+ data-close-count={closeCount}>+ <DropdownMenu+ button={{label: 'Actions', size}}+ isMenuOpen={isMenuOpen}+ onOpenChange={setIsMenuOpen}+ menuWidth={280}+ presentation="popover">+ <DropdownMenuItem label="Rename" onClick={() => setPicked('rename')} />+ <DropdownMenuSubMenu+ label="Share"+ icon="externalLink"+ presentation={presentation}+ menuDataTestId="dropdown-menu-submenu-flyout"+ onOpenChange={handleOpenChange}>+ <DropdownMenuItem+ label="Copy link"+ icon="copy"+ onClick={() => setPicked('copy-link')}+ />+ <DropdownMenuItem label="Email" onClick={() => setPicked('email')} />+ <DropdownMenuSubMenu label="Embed" presentation={presentation}>+ <DropdownMenuItem+ label="Inline frame"+ onClick={() => setPicked('inline-frame')}+ />+ </DropdownMenuSubMenu>+ </DropdownMenuSubMenu>+ <DropdownMenuSubMenu+ label="Move to"+ description="Choose a folder"+ presentation={presentation}>+ <DropdownMenuItem+ label="Folder A"+ onClick={() => setPicked('folder-a')}+ />+ </DropdownMenuSubMenu>+ <DropdownMenuSubMenu+ label="Export"+ hasSpinner+ presentation={presentation}>+ {null}+ </DropdownMenuSubMenu>+ <DropdownMenuSubMenu+ label="Archive"+ isDisabled+ presentation={presentation}>+ <DropdownMenuItem label="This year" onClick={() => {}} />+ </DropdownMenuSubMenu>+ <DropdownMenuSubMenu+ label="Send to every connected workspace, channel, and shared inbox"+ presentation={presentation}>+ <DropdownMenuItem label="All" onClick={() => setPicked('all')} />+ </DropdownMenuSubMenu>+ </DropdownMenu>+ </div>+ );+}++export const RowStates: Story = {+ render: args => <RowStatesFixture {...args} />,+ play: async () => {+ const [menu] = await within(document.body).findAllByRole('menu');+ const share = within(menu).getByRole('menuitem', {name: /^Share/});+ await expect(share).toHaveAttribute('aria-haspopup', 'menu');+ await expect(share).toHaveAttribute('aria-expanded', 'false');+ await expect(+ within(menu).getByRole('menuitem', {name: /^Archive/}),+ ).toHaveAttribute('aria-disabled', 'true');+ },+};diff --git a/packages/cli/test/core-prop-docs.known-drift.json b/packages/cli/test/core-prop-docs.known-drift.jsonindex 53352e9117..165ecdea95 100644--- a/packages/cli/test/core-prop-docs.known-drift.json+++ b/packages/cli/test/core-prop-docs.known-drift.json@@ -19,9 +19,6 @@"src/DropdownMenu/DropdownMenu.doc.mjs DropdownMenu.items required_mismatch","src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs DropdownMenuCheckboxItem.label required_mismatch","src/DropdownMenu/DropdownMenuCheckboxItem.doc.mjs DropdownMenuCheckboxItem.value required_mismatch",- "src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.children required_mismatch",- "src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.label required_mismatch",- "src/DropdownMenu/DropdownMenuSubMenu.doc.mjs DropdownMenuSubMenu.menuDataTestId not_in_doc","src/FieldStatus/FieldStatus.doc.mjs FieldStatus.variant type_mismatch","src/HoverCard/HoverCard.doc.mjs HoverCard.children required_mismatch","src/Icon/Icon.doc.mjs Icon.color type_mismatch",diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjsindex a0b03cbb57..b74358faba 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs@@ -16,6 +16,7 @@ export const docs = {{name: 'label',type: 'ReactNode',+ required: true,description: 'Primary label text for the trigger row.',},{@@ -32,6 +33,7 @@ export const docs = {{name: 'children',type: 'ReactNode',+ required: true,description:'The flyout menu items: the same components used at the top level (DropdownMenuItem, nested DropdownMenuSubMenu, selectable items).',},@@ -79,6 +81,12 @@ export const docs = {description:"Content below the sub-menu's rows and outside its menu, a door to where the options are managed, say. Same rules as header.",},+ {+ name: 'menuDataTestId',+ type: 'string',+ description:+ 'Test id for the sub-menu\'s own role="menu" element: the flyout, or the drilled-in list on a phone. The trigger row takes data-testid.',+ },{name: 'xstyle',type: 'StyleXStyles',@@ -115,6 +123,7 @@ export const docsDense = {header:'content above the rows, outside the menu; surface becomes a modal dialog named by the row (Tab wraps, Escape returns to the row)',footer: 'content below the rows, outside the menu; same rules as header',+ menuDataTestId: 'test id for the flyout or drilled-in role="menu"',xstyle: 'StyleX styles for the trigger row',ref: 'ref to the trigger row (role="menuitem")',},diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.spec.md b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.spec.mdnew file mode 100644index 0000000000..08d0562a97--- /dev/null+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.spec.md@@ -0,0 +1,225 @@+---+schema_version: 3+template_version: 7+kind: component+id: component:DropdownMenuSubMenu+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang]+review_triggers: [public-api, behavior, accessibility, theming, layout, testing]+verified_by:+ [+ packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx,+ packages/core/src/DropdownMenu/__tests__/SubMenuHeaderFooter.a11y.chromium.spec.ts,+ packages/core/src/DropdownMenu/__tests__/DropdownMenuDrillIn.a11y.chromium.spec.ts,+ packages/core/src/DropdownMenu/__tests__/DropdownMenuSubMenuAudit.a11y.chromium.spec.ts,+ apps/storybook/stories/DropdownMenuSubMenu.stories.tsx,+ apps/storybook/rtl-audit/targets.json,+ scripts/check-knowledge.mjs,+ ]+modules: []+families: []+design_specs: []+architecture:+ [+ architecture:public-component-api,+ architecture:component-theming-surface,+ architecture:component-test-sufficiency,+ architecture:interaction-modality,+ architecture:layer-runtime,+ architecture:react-component-runtime,+ ]+contributing: []+system_specs: [spec:AST-020, spec:AST-029, spec:AST-086]+---++# DropdownMenuSubMenu component contract++## Contract at a glance++| Area | Contract |+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | One `menuitem` row with a required label and children, optional icon, description, loading caret, disabled state, flyout width, presentation, header, footer, open callback, test ids, root inputs, and a ref. |+| Behavior | The row reveals its children as a flyout beside it or as a drilled-in view led by a Back row; with a header or footer that surface is a modal dialog named by the row. |+| End-user impact | Pointer, keyboard, and touch users reach nested commands from one row; assistive technology hears the row's popup kind and expanded state, and Escape or the close arrow returns to the row. |+| Builder impact | Place the row inside a DropdownMenu or ContextMenu and give it a label and rows; data-driven menus get it from a nested `items` array. |+| Compatibility/readiness | Released subcomponent; observational draft of current behavior. Authority stays `draft` until owner approval. |+| Review checks | Reject a second keyboard owner, a lost popup state, a flyout that does not flip under RTL, a disabled row that opens, dropped caller inputs, or an open callback that misses a transition. |+| Governing rules | WAI-ARIA menu pattern; `architecture:public-component-api/INV5–INV8`; `architecture:react-component-runtime/INV2`; `architecture:layer-runtime`; `spec:AST-020/FR1,FR2`; `spec:AST-086/FR8`. |++This table is a review projection; the body below is authoritative.++## Intent++DropdownMenuSubMenu turns one menu row into the entry point of a nested menu.+The row owns its `menuitem` semantics, popup state, caret or spinner, disabled+paint, and the surface its children render in: a flyout positioned beside the+row by the layer runtime, or a view the root menu shows in place of its own+rows. Each level owns its own roving focus, typeahead, and press model.+DropdownMenu owns the root surface, the drill-in view stack, and the surface+host that a sub-menu with a header or footer renders into.++## Compatibility and migration++- Released default preserved: yes (`isDisabled=false`, `hasSpinner=false`,+ `presentation='adaptive'`).+- Compatibility class: no public API change.+- Controlled behavior: the open state is internal; `onOpenChange` reports it.+- Migration decision: none.++Consumer migration instructions belong in consumer docs and release notes.++## Ownership boundary++**Owns**++- One row root with `role="menuitem"`, `aria-haspopup` (`menu`, or `dialog`+ with a header or footer), `aria-expanded`, and `aria-controls` while open.+- The flyout menu, its viewport-capped size, its keyboard handling, and its+ hover intent; the drilled-in list and its Back row.+- The header and footer regions and the modal dialog that holds them.+- Root composition of ref, supported host inputs, `className`, `style`,+ `xstyle`, and the composed `onClick`, `onKeyDown`, `onPointerMove`,+ `onMouseEnter`, and `onMouseLeave` handlers.++**Does not own / non-goals**++- The root menu surface, the drill-in view stack and its reset when the menu+ closes, and the surface host — owned by `component:DropdownMenu`.+- Leaf row behavior — owned by `component:DropdownMenuItem` and the selectable+ item contracts.+- Placement, flipping, and viewport insets — owned by+ `architecture:layer-runtime`.++## Public concepts++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ------------ | ------------------------------------------------ | ---------------------------------------------------------------------------- | ----------------------------------------- | -------- | ------------------------------- | --------- | -------------------------------------------------------- |+| Presentation | flyout; drill-in; adaptive | Where the children render; adaptive drills in when a finger opened the menu. | Every row; drill-in needs a menu root | adaptive | `component:DropdownMenuSubMenu` | stable | Unknown values are rejected by the public type. |+| Availability | enabled; disabled | Whether the row can open. | Every row | enabled | `component:DropdownMenuSubMenu` | stable | A disabled row never opens. |+| Loading | caret; spinner | Whether the row's end shows a spinner while its rows load. | Every row | caret | `component:DropdownMenuSubMenu` | stable | The row still opens; an empty flyout takes focus itself. |+| Regions | none; header; footer; both | Content beside the sub-menu's menu that turns its surface into a dialog. | Inside a DropdownMenu root | none | `component:DropdownMenuSubMenu` | stable | Without a surface host the regions are not rendered. |+| Open report | open; close | `onOpenChange` reports each transition of the row's surface. | Every row | omitted | `component:DropdownMenuSubMenu` | stable | See FR6 for the recorded gap. |+| Root surface | ref; DOM/data/ARIA; class/style/xstyle; handlers | Extends the row root while preserving its role and popup wiring. | Every row | omitted | public component API | stable | `role` and `tabIndex` are not accepted. |++## Behavioral and layout contract++Draft requirements identify their basis so observed code is not mistaken for an+intentional decision.++| ID | Candidate invariant | Basis | Draft review state |+| --- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |+| FR1 | The row MUST expose `role="menuitem"`, `aria-haspopup="menu"` (`"dialog"` with a header or footer), `aria-expanded` matching its surface, and `aria-controls` naming the surface while open. The surface MUST be labelled by the row. | WAI-ARIA menu pattern; current source and focused tests | verify |+| FR2 | A click, Enter, Space, or the inline-end arrow (inline-start under RTL) MUST open the surface; a keyboard open MUST focus its first row. Escape or the close arrow MUST close only this level and return focus to the row. A hover MUST open a flyout after an intent delay. | WAI-ARIA menu pattern; `architecture:interaction-modality`; tests | verify |+| FR3 | A flyout MUST sit beside the row on the inline-end side, flip with direction, and stay within the viewport; its block size MUST cap at the smaller of its own cap and the viewport. | `architecture:layer-runtime`; current source and browser evidence | verify |+| FR4 | A drilled-in view MUST replace the root's rows with a Back row named after the parent menu and then this row's children; Back, Escape, and the close arrow MUST return to the row. | Current source and focused tests | verify |+| FR5 | Selecting a leaf row inside the surface MUST close every level and the root menu. | Current source, focused tests, and browser evidence | verify |+| FR6 | `onOpenChange` MUST report `true` once when the surface opens and `false` once when it closes, from the action that caused the change. | Documented promise; `architecture:react-component-runtime/INV2` | objective gap: a drilled-in view reset by the root menu closing reports no `false` (owner: DropdownMenu) |+| FR7 | A disabled row MUST expose `aria-disabled="true"`, render no `tabindex`, take no hover focus, open on no input, and run no caller `onClick`. | Current source, focused tests, and browser evidence | verify |+| FR8 | With `hasSpinner` the row MUST show a decorative spinner in place of the caret and announce the busy start once the root menu shows. | `spec:AST-086/FR8`; current source | verify |+| FR9 | Ref, supported host attributes and handlers, `className`, `style`, and `xstyle` MUST reach or compose on the row root after the row's own behavior; the open keys and a disabled click stop before the caller's handler. | `architecture:public-component-api/INV5–INV8`; focused tests | verify |++### Allowed variation++- **AV1 — Content.** Label, icon, description, and children vary; long string+ labels truncate on one line.+- **AV2 — Size.** The row's padding follows the parent menu size.+- **AV3 — Width.** `menuWidth` sets the flyout's minimum width within the+ viewport cap.++### Representative states++| State | Required invariant | Allowed variation |+| -------- | --------------------------------------------------------------------- | ------------------------------------- |+| Closed | `aria-expanded=false`; caret or spinner at the row's end. | Content, size, theme, and mode. |+| Open | `aria-expanded=true`; flyout beside the row, labelled by it. | Pointer, keyboard, or press opening. |+| Drilled | Back row first, then the children, in the root's box. | Nested drill-in depth. |+| Regions | Modal dialog named by the row; Tab walks header, rows, footer, wraps. | Header or footer only. |+| Disabled | `aria-disabled=true`, no tab stop, half opacity, no opening. | Loading or not. |+| RTL | Caret mirrors once; flyout opens toward the inline end. | Placement flips at the viewport edge. |++### Transformation and precedence order++- **ORD1 — Click.** Disabled guard → drill-in push or flyout toggle → caller+ `onClick`.+- **ORD2 — Key.** Open keys handled and stopped → caller `onKeyDown` for any+ other key.+- **ORD3 — Leaf selection.** Leaf action → this level closes → parent levels+ close → root menu closes.++### Performance and resources++- **PR1 — Owned resources.** The row's only timers are the hover intent and a+ zero-delay focus check on blur; the flyout's overflow observation follows+ the shared menu overflow hook.++## Accessibility contract++- **AR1 — One entry row.** The row is one menu item whose popup kind and state+ are exposed through ARIA; its caret and spinner are decorative.+- **AR2 — Level-scoped keys.** Each level owns its own arrows, typeahead, and+ Escape; a deeper level's keys never act on its parent.+- **AR3 — Disabled discoverability.** Whether disabled rows stay+ keyboard-discoverable is owned by `component:DropdownMenu` (its OQ1).+- **AR4 — Focus visibility (objective gap).** Keyboard focus MUST be+ perceivable (WCAG 2.2 SC 2.4.7 and 1.4.11). The row currently paints focus+ only as the menu overlay tint with no outline, and paints nothing under+ forced colors. The remediation is a shared row-visual decision with+ `component:DropdownMenuItem` (its OQ2); this draft records the gap and does+ not settle it.++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | ------------------------------------------------------------- | -------------------------------- | -------------- | ------------------ |+| Row | Menu row paint, radius, and size padding; focus paint is AR4. | Current source and menu tokens | structural | FR1, AR4 |+| Caret / spinner | Mirrored caret, or a decorative spinner while loading. | Icon and Spinner owners | supporting | FR3, FR8 |+| Flyout | Popover surface, low shadow, container radius, viewport caps. | Current source and layer runtime | prominent | FR3 |+| Drilled view | Rows inside the root's box, led by a mirrored Back row. | Current source | structural | FR4 |+| Disabled | Half-opacity row with a default cursor. | Current source | supporting | FR7 |++No new component-local visual decision is settled by this draft.++## Family and system relationships++- `component:DropdownMenu` owns the root surface, the drill-in stack, the+ surface host, the `dropdown-menu`, `dropdown-menu-item`, and+ `dropdown-menu-indicator-icon` target inventory, and disabled keyboard+ discoverability (its OQ1).+- `architecture:layer-runtime` owns flyout placement, flipping, and insets.+- `architecture:public-component-api` owns root input and handler composition.+- `architecture:react-component-runtime` owns callback timing.+- `spec:AST-086` owns the loading announcement.+- `spec:AST-029` keeps this observational draft separate from the audit receipt.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------- | ----------------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------- | ------------------------------------- |+| FR1, FR2, AR2 | `DropdownMenuSubMenu.test.tsx` keyboard, hover, typeahead, and nesting suites | open, close, nested, loading | A lost popup state, wrong focus target, or double-stepped level fails | `audit:DropdownMenuSubMenu/§1,§4,§6` |+| FR3 | RTL D4 flyout target; exact-head LTR/RTL/narrow open frames | LTR, RTL, 320px | A flyout on the wrong side or outside the viewport fails | `audit:DropdownMenuSubMenu/§5,§9,§10` |+| FR4, FR5 | Drill-in and selection tests; exact-head drill-in and select frames | drilled, nested selection | A missing Back row or a stack that stays open fails | `audit:DropdownMenuSubMenu/§4` |+| FR6 | onOpenChange test (mutation-sensitive); browser select-frame counters | flyout open and close | Dropping the close report fails; the drill-in reset gap is recorded, not asserted | `audit:DropdownMenuSubMenu/§3,§4` |+| FR7, FR9 | Host-attribute, handler, and disabled tests; disabled-hover frames | disabled, caller handlers, test ids | A disabled open or dropped caller input fails | `audit:DropdownMenuSubMenu/§1,§3` |+| AR4 | Exact-head keyboard-focus and forced-colors frames with rendered contrast | Neutral/Butter focus, forced colors | Current frames record the gap; a remediation passes only with a perceivable indicator | `audit:DropdownMenuSubMenu/§1,§5` |++## Decision log++None. This draft records current facts and introduces no product decision.++## Open questions++- **OQ1 — Which owner reports a drilled-in view's close when the root menu+ closes?** (`human-api`) The flyout reports every close through its layer, but+ the root resets the drill-in stack without telling the row, so+ `onOpenChange(false)` never runs for that close. The stack is owned by+ `component:DropdownMenu`.++## Content boundary++This file does not duplicate consumer prop tables/examples, current audit scores,+screenshot matrices, implementation steps, or root/leaf contracts. The audit+pull request owns the closed run evidence required by `spec:AST-029/FR5`.diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsxindex a60bd05294..7e61b16df2 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx@@ -450,6 +450,54 @@ describe('DropdownMenuSubMenu host attributes', () => {).toHaveAttribute('aria-labelledby', 'move-row');});+ it('reports each flyout open and close to onOpenChange once', async () => {+ const user = userEvent.setup();+ const onOpenChange = vi.fn();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu label="Move to" onOpenChange={onOpenChange}>+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ expect(onOpenChange).not.toHaveBeenCalled();+ trigger.focus();+ await user.keyboard('{ArrowRight}');+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),+ );+ expect(onOpenChange.mock.calls).toEqual([[true]]);+ await user.keyboard('{Escape}');+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'false'),+ );+ expect(onOpenChange.mock.calls).toEqual([[true], [false]]);+ });++ it('menuDataTestId names the flyout menu, and data-testid the row', async () => {+ const user = userEvent.setup();+ render(+ <DropdownMenu button={{label: 'Actions'}}>+ <DropdownMenuSubMenu+ label="Move to"+ data-testid="move-row"+ menuDataTestId="move-menu">+ <DropdownMenuItem label="Folder A" onClick={() => {}} />+ </DropdownMenuSubMenu>+ </DropdownMenu>,+ );+ const trigger = await openRoot(user);+ expect(trigger).toHaveAttribute('data-testid', 'move-row');+ await user.click(trigger);+ await waitFor(() =>+ expect(trigger).toHaveAttribute('aria-expanded', 'true'),+ );+ expect(screen.getByTestId('move-menu')).toBe(+ screen.getByRole('menu', {name: 'Move to', hidden: true}),+ );+ });+it('a ref reaches the trigger row', async () => {const user = userEvent.setup();const ref = createRef<HTMLElement>();diff --git a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsxindex fba3193f41..ba205437fc 100644--- a/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx+++ b/packages/core/src/DropdownMenu/DropdownMenuSubMenu.tsx@@ -40,9 +40,6 @@* the row. The list keeps this level's own roving focus, typeahead and press* model, so nothing beside the row needs to know.*- * Prior art: legacy internal XDS `XDSDropdownSubMenuItem` (APG menubar-- * navigation submenu). This re-expresses the same contract on Astryx primitives.- ** SYNC: When modified, update these files to stay in sync:* - /packages/core/src/DropdownMenu/DropdownMenuSubMenu.doc.mjs* - /packages/core/src/DropdownMenu/DropdownMenuSubMenu.test.tsx@@ -347,7 +344,7 @@ interface DropdownMenuSubMenuBaseProps extends Omit<isDisabled?: boolean;/*** Show a spinner in place of the caret, e.g. while a lazy submenu's children- * are loading. Ported from the legacy `hasSpinner` async-submenu affordance.+ * are loading.* @default false*/hasSpinner?: boolean;@@ -364,7 +361,7 @@ interface DropdownMenuSubMenuBaseProps extends Omit<* box; `adaptive` drills in when a finger opened the menu — a* `(pointer: coarse)` device, decided when the menu opened — and flies out* otherwise. Drill-in needs a `DropdownMenu` or `ContextMenu` root.- * 'adaptive'+ * @default 'adaptive'*/presentation?: DropdownMenuSubMenuPresentation;/**@@ -386,7 +383,10 @@ interface DropdownMenuSubMenuBaseProps extends Omit<footer?: ReactNode;/** Test id for the trigger row. */'data-testid'?: string;- /** Test id for the flyout menu. */+ /**+ * Test id for the sub-menu's own `role="menu"` element: the flyout, or the+ * drilled-in list on a phone.+ */menuDataTestId?: string;/*** Ref forwarded to the trigger row — the element carrying `role="menuitem"`diff --git a/packages/core/src/DropdownMenu/__tests__/DropdownMenuSubMenuAudit.a11y.chromium.spec.ts b/packages/core/src/DropdownMenu/__tests__/DropdownMenuSubMenuAudit.a11y.chromium.spec.tsnew file mode 100644index 0000000000..b8edf27877--- /dev/null+++ b/packages/core/src/DropdownMenu/__tests__/DropdownMenuSubMenuAudit.a11y.chromium.spec.ts@@ -0,0 +1,670 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DropdownMenuSubMenuAudit.a11y.chromium.spec.ts+ * @input Exact-head DropdownMenuSubMenu row-state story (and the existing header-and-footer story) across states, themes, sizes, direction, pointer, forced colors, and viewport widths+ * @output Screenshots and fail-closed sensor receipts for the DropdownMenuSubMenu component audit+ * @position Component-owned Night Watch browser evidence; CI runs it only for a DropdownMenuSubMenu audit pull request+ */++import {createHash} from 'node:crypto';+import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {expect, test, type Locator, type Page} from '@playwright/test';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const OUTPUT = path.resolve('dropdown-menu-submenu-audit-evidence');+const ROW_STORY = 'core-dropdownmenusubmenu--row-states';+const REGIONS_STORY = 'core-dropdownmenu--sub-menu-header-and-footer';+const FLYOUT = '[data-testid="dropdown-menu-submenu-flyout"]';+const WIDE = {width: 1024, height: 768};+const NARROW = {width: 320, height: 720};++type Interaction =+ | 'rest'+ | 'hover'+ | 'focus'+ | 'open'+ | 'pressed'+ | 'disabled-hover'+ | 'drill-in'+ | 'select'+ | 'regions';+type AuditCase = {+ key: string;+ mode: 'light' | 'dark';+ direction: 'ltr' | 'rtl';+ theme: 'neutral' | 'butter';+ size: 'sm' | 'md' | 'lg';+ pointer: 'fine' | 'coarse';+ forcedColors: boolean;+ viewport: {width: number; height: number};+ interaction: Interaction;+};++const defaults: Omit<AuditCase, 'key' | 'interaction'> = {+ mode: 'light',+ direction: 'ltr',+ theme: 'neutral',+ size: 'md',+ pointer: 'fine',+ forcedColors: false,+ viewport: WIDE,+};++const states: Interaction[] = [+ 'rest',+ 'hover',+ 'focus',+ 'open',+ 'pressed',+ 'disabled-hover',+ 'drill-in',+ 'select',+ 'regions',+];++const overrides: (Partial<AuditCase> &+ Pick<AuditCase, 'key' | 'interaction'>)[] = [+ ...states.flatMap(interaction =>+ (['light', 'dark'] as const).map(mode => ({+ key: `neutral-${mode}-${interaction}`,+ mode,+ interaction,+ })),+ ),+ ...(['sm', 'lg'] as const).flatMap(size =>+ (['light', 'dark'] as const).map(mode => ({+ key: `size-${size}-${mode}-rest`,+ size,+ mode,+ interaction: 'rest' as const,+ })),+ ),+ {key: 'butter-light-rest', theme: 'butter', interaction: 'rest'},+ {key: 'butter-dark-rest', theme: 'butter', mode: 'dark', interaction: 'rest'},+ {key: 'butter-light-open', theme: 'butter', interaction: 'open'},+ {key: 'rtl-light-rest', direction: 'rtl', interaction: 'rest'},+ {key: 'rtl-dark-rest', direction: 'rtl', mode: 'dark', interaction: 'rest'},+ {key: 'rtl-light-open', direction: 'rtl', interaction: 'open'},+ {key: 'narrow-light-rest', viewport: NARROW, interaction: 'rest'},+ {+ key: 'narrow-dark-rest',+ viewport: NARROW,+ mode: 'dark',+ interaction: 'rest',+ },+ {key: 'narrow-light-open', viewport: NARROW, interaction: 'open'},+ {key: 'coarse-light-rest', pointer: 'coarse', interaction: 'rest'},+ {key: 'forced-colors-focus', forcedColors: true, interaction: 'focus'},+];+const cases: AuditCase[] = overrides.map(item => ({...defaults, ...item}));++// Authored before observation: whether the Share sub-menu is expanded after+// each interaction, which row holds focus, and what the callback counters read.+const expectedExpanded: Record<Interaction, boolean> = {+ rest: false,+ hover: true,+ focus: false,+ open: true,+ pressed: true,+ 'disabled-hover': false,+ 'drill-in': true,+ select: false,+ regions: true,+};+const expectedActive: Record<Interaction, string | null | undefined> = {+ rest: undefined,+ hover: 'Share',+ focus: 'Share',+ open: 'Copy link',+ pressed: 'Share',+ 'disabled-hover': undefined,+ 'drill-in': undefined,+ select: undefined,+ regions: undefined,+};+const expectedCounters: Record<+ Interaction,+ {picked: string; open: number; close: number} | null+> = {+ rest: {picked: 'none', open: 0, close: 0},+ hover: {picked: 'none', open: 1, close: 0},+ focus: {picked: 'none', open: 0, close: 0},+ open: {picked: 'none', open: 1, close: 0},+ pressed: {picked: 'none', open: 1, close: 0},+ 'disabled-hover': {picked: 'none', open: 0, close: 0},+ 'drill-in': {picked: 'none', open: 1, close: 0},+ select: {picked: 'copy-link', open: 1, close: 1},+ regions: null,+};++let server: StaticServer;+let checkoutSha: string;+let storybookSha: string;++function storyUrl(item: AuditCase) {+ const story = item.interaction === 'regions' ? REGIONS_STORY : ROW_STORY;+ const presentation =+ item.interaction === 'drill-in' ? 'drill-in' : 'adaptive';+ const args =+ item.interaction === 'regions'+ ? ''+ : `&args=size:${item.size};presentation:${presentation}`;+ return `${server.origin}/iframe.html?id=${story}&viewMode=story${args}&globals=colorMode:${item.mode};astryxTheme:${item.theme};direction:${item.direction}`;+}++async function settle(page: Page) {+ await holdMotionStill(page);+ await page.evaluate(async () => document.fonts.ready);+ await page.waitForTimeout(60);+}++const row = (scope: Locator, name: string) =>+ scope.getByRole('menuitem', {name: new RegExp(`^${name}`)}).first();++test.beforeAll(async () => {+ fs.mkdirSync(OUTPUT, {recursive: true});+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {+ encoding: 'utf8',+ }).trim();+ const expected = process.env.ASTRYX_HEAD_SHA;+ if (expected && expected !== checkoutSha) {+ throw new Error(+ `checkout ${checkoutSha} does not match expected head ${expected}`,+ );+ }+ server = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+ const response = await fetch(`${server.origin}/astryx-build-sha.txt`);+ if (!response.ok) {+ throw new Error(`Storybook build has no SHA stamp (${response.status})`);+ }+ storybookSha = (await response.text()).trim();+ if (storybookSha !== checkoutSha) {+ throw new Error(+ `Storybook ${storybookSha} does not match checkout ${checkoutSha}`,+ );+ }+});++test.afterAll(async () => {+ await server?.close();+ const receipts = fs+ .readdirSync(OUTPUT)+ .filter(file => file.endsWith('.sensors.json'))+ .sort();+ fs.writeFileSync(+ path.join(OUTPUT, 'manifest.json'),+ `${JSON.stringify(+ {+ schemaVersion: 1,+ component: 'core/DropdownMenuSubMenu',+ build: checkoutSha,+ expectedFrames: cases.map(item => item.key),+ receipts: receipts.map(file => {+ const receipt = JSON.parse(+ fs.readFileSync(path.join(OUTPUT, file), 'utf8'),+ );+ return {+ key: file.replace('.sensors.json', ''),+ passed: receipt.passed,+ };+ }),+ },+ null,+ 2,+ )}\n`,+ );+});++for (const item of cases) {+ test(item.key, async ({browser}) => {+ const coarse = item.pointer === 'coarse';+ const context = await browser.newContext({+ viewport: item.viewport,+ colorScheme: item.mode,+ reducedMotion: 'reduce',+ forcedColors: item.forcedColors ? 'active' : 'none',+ hasTouch: coarse,+ isMobile: coarse,+ });+ const page = await context.newPage();+ const pageErrors: string[] = [];+ page.on('pageerror', error => pageErrors.push(String(error)));+ await page.goto(storyUrl(item), {waitUntil: 'load'});+ await page.locator('#storybook-root').waitFor();++ const isRegions = item.interaction === 'regions';+ const rowName = isRegions ? 'Labels' : 'Share';+ if (isRegions) {+ await page.getByRole('button', {name: 'Session'}).click();+ }+ const menu = page.getByRole('menu').first();+ await expect(menu).toBeVisible();+ const subject = row(menu, rowName);+ await expect(subject).toBeVisible();+ const flyout = page.locator(FLYOUT);+ const openKey = item.direction === 'rtl' ? 'ArrowLeft' : 'ArrowRight';++ if (item.interaction === 'hover') {+ await subject.hover();+ await expect(flyout).toBeVisible();+ } else if (item.interaction === 'focus' || item.interaction === 'open') {+ await page.getByRole('button', {name: 'Actions'}).focus();+ await page.keyboard.press('ArrowDown');+ await expect(row(menu, 'Rename')).toBeFocused();+ await page.keyboard.press('ArrowDown');+ await expect(subject).toBeFocused();+ if (item.interaction === 'open') {+ await page.keyboard.press(openKey);+ await expect(flyout).toBeVisible();+ await expect(row(flyout, 'Copy link')).toBeFocused();+ }+ } else if (item.interaction === 'pressed') {+ await subject.hover();+ await expect(flyout).toBeVisible();+ await page.mouse.down();+ } else if (item.interaction === 'disabled-hover') {+ await row(menu, 'Archive').hover();+ await page.waitForTimeout(600);+ } else if (item.interaction === 'drill-in') {+ await subject.click();+ await expect(flyout).toBeVisible();+ await expect(row(flyout, 'Back to Actions')).toBeVisible();+ } else if (item.interaction === 'select') {+ await subject.click();+ await expect(flyout).toBeVisible();+ await row(flyout, 'Copy link').click();+ await expect(flyout).toBeHidden();+ await expect(menu).toBeHidden();+ } else if (isRegions) {+ await subject.click();+ await expect(+ page.getByRole('dialog', {name: 'Labels', includeHidden: false}),+ ).toBeVisible();+ }+ await settle(page);++ // Geometry must be settled before a frame is trusted: read every row and+ // open surface box, wait two animation frames plus a pause, read again.+ const settledGeometry = await page.evaluate(async () => {+ const read = () =>+ Array.from(+ document.querySelectorAll(+ 'button, [role="menu"], [role="menuitem"], [role="dialog"]',+ ),+ )+ .filter(node => node.getClientRects().length > 0)+ .map(node => {+ const box = node.getBoundingClientRect();+ return [box.x, box.y, box.width, box.height]+ .map(value => value.toFixed(2))+ .join(',');+ })+ .join('|');+ const first = read();+ await new Promise<void>(resolve => {+ requestAnimationFrame(() =>+ requestAnimationFrame(() => setTimeout(resolve, 120)),+ );+ });+ const second = read();+ return {stable: first === second, boxes: first.split('|').length};+ });++ const observed = await page.evaluate(+ ({rowName, flyoutSelector}) => {+ const canvas = document.createElement('canvas');+ canvas.width = 1;+ canvas.height = 1;+ const ctx = canvas.getContext('2d', {willReadFrequently: true});+ if (ctx === null) {+ throw new Error('2d canvas context is unavailable');+ }+ type Rgba = [number, number, number, number];+ const rgba = (color: string): Rgba => {+ ctx.clearRect(0, 0, 1, 1);+ ctx.fillStyle = '#000';+ ctx.fillStyle = color;+ ctx.fillRect(0, 0, 1, 1);+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;+ return [r, g, b, a / 255];+ };+ const over = (top: Rgba, bottom: Rgba): Rgba => {+ const alpha = top[3] + bottom[3] * (1 - top[3]);+ if (alpha === 0) {+ return [0, 0, 0, 0];+ }+ const mix = (i: number) =>+ (top[i] * top[3] + bottom[i] * bottom[3] * (1 - top[3])) / alpha;+ return [mix(0), mix(1), mix(2), alpha];+ };+ const backdrop = (node: Element): Rgba => {+ const layers: Rgba[] = [];+ for (let n: Element | null = node; n; n = n.parentElement) {+ layers.push(rgba(getComputedStyle(n).backgroundColor));+ }+ let acc: Rgba = [255, 255, 255, 1];+ for (let i = layers.length - 1; i >= 0; i--) {+ acc = over(layers[i], acc);+ }+ return acc;+ };+ const luminance = ([r, g, b]: Rgba) => {+ const f = (v: number) => {+ const c = v / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);+ };+ const ratio = (fg: Rgba, bg: Rgba) => {+ const [hi, lo] = [luminance(over(fg, bg)), luminance(bg)].sort(+ (a, b) => b - a,+ );+ return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;+ };+ const hex = (c: Rgba) =>+ `#${c+ .slice(0, 3)+ .map(v => Math.round(v).toString(16).padStart(2, '0'))+ .join('')}${c[3] < 1 ? `@${c[3].toFixed(2)}` : ''}`;+ const text = (node: Element | null) =>+ node?.textContent?.replace(/\s+/g, ' ').trim() ?? '';+ const boxOf = (node: Element) => {+ const box = node.getBoundingClientRect();+ return {x: box.x, y: box.y, width: box.width, height: box.height};+ };+ const describeRows = (scope: Element) => {+ const scopeBackdrop = backdrop(scope);+ return Array.from(+ scope.querySelectorAll<HTMLElement>('[role="menuitem"]'),+ )+ .filter(+ node =>+ node.closest('[role="menu"]') === scope &&+ node.getClientRects().length > 0,+ )+ .map(node => {+ const style = getComputedStyle(node);+ const opacity = Number(style.opacity);+ const rowBackdrop = backdrop(node);+ const indicator = node.querySelector<HTMLElement>(+ '.astryx-dropdown-menu-indicator-icon',+ );+ const spinner = node.querySelector('.astryx-spinner');+ return {+ name: text(node),+ haspopup: node.getAttribute('aria-haspopup'),+ expanded: node.getAttribute('aria-expanded'),+ disabled: node.getAttribute('aria-disabled'),+ tabIndex: node.getAttribute('tabindex'),+ focused: document.activeElement === node,+ cursor: style.cursor,+ opacity,+ outline: `${style.outlineStyle} ${style.outlineWidth}`,+ background: hex(rgba(style.backgroundColor)),+ rowAgainstSurface: ratio(rowBackdrop, scopeBackdrop),+ indicatorTransform:+ indicator === null+ ? null+ : getComputedStyle(indicator).transform,+ spinnerHidden:+ spinner === null+ ? null+ : spinner.closest('[aria-hidden="true"]') !== null,+ texts: Array.from(node.querySelectorAll('span'))+ .filter(n => n.children.length === 0 && n.textContent?.trim())+ .map(n => {+ const color = rgba(getComputedStyle(n).color);+ const nodeBackdrop = backdrop(n);+ return {+ text: (n.textContent ?? '').trim().slice(0, 24),+ fontSize: getComputedStyle(n).fontSize,+ color: hex(color),+ backdrop: hex(nodeBackdrop),+ contrast: ratio(+ [color[0], color[1], color[2], color[3] * opacity],+ nodeBackdrop,+ ),+ };+ }),+ geometry: boxOf(node),+ };+ });+ };+ const menus = Array.from(+ document.querySelectorAll<HTMLElement>('[role="menu"]'),+ ).filter(node => node.getClientRects().length > 0);+ const rootMenu = menus[0] ?? null;+ const subject =+ rootMenu === null+ ? null+ : (Array.from(+ rootMenu.querySelectorAll<HTMLElement>('[role="menuitem"]'),+ ).find(node => text(node).startsWith(rowName)) ?? null);+ const flyout = document.querySelector<HTMLElement>(flyoutSelector);+ const flyoutShown =+ flyout !== null && flyout.getClientRects().length > 0;+ const dialog = Array.from(+ document.querySelectorAll<HTMLElement>('[role="dialog"]'),+ ).find(node => node.getClientRects().length > 0);+ const fixture = document.querySelector(+ '[data-testid="dropdown-menu-submenu-audit"]',+ );+ return {+ theme:+ document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme') ?? null,+ mode: document.documentElement.getAttribute('data-theme'),+ // A closed menu leaves only its trigger to read direction from.+ direction: getComputedStyle(+ rootMenu ?? document.querySelector('button') ?? document.body,+ ).direction,+ viewport: {width: innerWidth, height: innerHeight},+ media: {+ pointerCoarse: matchMedia('(pointer: coarse)').matches,+ forcedColors: matchMedia('(forced-colors: active)').matches,+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)')+ .matches,+ devicePixelRatio,+ },+ fonts: document.fonts.status,+ horizontalOverflow:+ document.documentElement.scrollWidth > innerWidth + 1,+ activeElement: text(document.activeElement).slice(0, 40),+ activeRole: document.activeElement?.getAttribute('role') ?? null,+ rootMenu:+ rootMenu === null+ ? null+ : {+ box: boxOf(rootMenu),+ backdrop: hex(backdrop(rootMenu)),+ rows: describeRows(rootMenu),+ },+ subject:+ subject === null+ ? null+ : {+ name: text(subject),+ haspopup: subject.getAttribute('aria-haspopup'),+ expanded: subject.getAttribute('aria-expanded'),+ controls: subject.getAttribute('aria-controls'),+ box: boxOf(subject),+ },+ flyout: flyoutShown+ ? {+ box: boxOf(flyout),+ labelledBy: flyout.getAttribute('aria-labelledby'),+ label: flyout.getAttribute('aria-label'),+ backdrop: hex(backdrop(flyout)),+ rows: describeRows(flyout),+ }+ : null,+ dialog:+ dialog === undefined+ ? null+ : {+ modal: dialog.getAttribute('aria-modal'),+ labelledBy: dialog.getAttribute('aria-labelledby'),+ hasField: dialog.querySelector('input') !== null,+ hasButton: dialog.querySelector('button') !== null,+ hasMenu: dialog.querySelector('[role="menu"]') !== null,+ box: boxOf(dialog),+ },+ counters:+ fixture === null+ ? null+ : {+ picked: fixture.getAttribute('data-picked'),+ open: Number(fixture.getAttribute('data-open-count')),+ close: Number(fixture.getAttribute('data-close-count')),+ },+ };+ },+ {rowName, flyoutSelector: FLYOUT},+ );++ const rows = observed.rootMenu?.rows ?? [];+ const subjectBox = observed.subject?.box;+ const flyoutBox = observed.flyout?.box ?? observed.dialog?.box;+ const opensSideways =+ expectedExpanded[item.interaction] &&+ item.interaction !== 'drill-in' &&+ item.viewport.width === WIDE.width;+ const active = expectedActive[item.interaction];+ const counters = expectedCounters[item.interaction];+ const findRow = (name: string) =>+ rows.find(entry => entry.name.startsWith(name));+ const checks = {+ build: storybookSha === checkoutSha,+ noPageErrors: pageErrors.length === 0,+ theme: observed.theme === item.theme,+ mode: observed.mode === item.mode,+ direction: observed.direction === item.direction,+ viewport:+ observed.viewport.width === item.viewport.width &&+ observed.viewport.height === item.viewport.height,+ pointer: observed.media.pointerCoarse === (item.pointer === 'coarse'),+ forcedColors: observed.media.forcedColors === item.forcedColors,+ reducedMotion: observed.media.reducedMotion,+ fonts: observed.fonts === 'loaded',+ noHorizontalOverflow: !observed.horizontalOverflow,+ // A closed menu leaves only its trigger, one box.+ geometrySettled: settledGeometry.stable && settledGeometry.boxes >= 1,+ // A nested selection dismisses the whole stack, root menu included.+ rootClosed:+ (item.interaction === 'select') === (observed.rootMenu === null),+ subjectSemantics:+ item.interaction === 'select' ||+ (observed.subject !== null &&+ observed.subject.haspopup === (isRegions ? 'dialog' : 'menu') &&+ observed.subject.expanded ===+ String(expectedExpanded[item.interaction])),+ surface: isRegions+ ? observed.dialog !== null &&+ observed.dialog.modal === 'true' &&+ observed.dialog.hasField &&+ observed.dialog.hasButton &&+ observed.dialog.hasMenu+ : expectedExpanded[item.interaction] === (observed.flyout !== null),+ drillIn:+ item.interaction !== 'drill-in' ||+ (observed.flyout?.rows[0]?.name.startsWith('Back to Actions') ===+ true &&+ rows.length === 0),+ flyoutSide:+ !opensSideways ||+ (subjectBox !== undefined &&+ flyoutBox !== undefined &&+ (item.direction === 'rtl'+ ? flyoutBox.x + flyoutBox.width <= subjectBox.x + 2+ : flyoutBox.x >= subjectBox.x + subjectBox.width - 2)),+ flyoutInViewport:+ flyoutBox === undefined ||+ (flyoutBox.x >= -1 &&+ flyoutBox.x + flyoutBox.width <= item.viewport.width + 1),+ activeRow:+ active === undefined+ ? true+ : observed.activeElement.startsWith(active ?? ''),+ rowStates:+ isRegions ||+ item.interaction === 'select' ||+ item.interaction === 'drill-in' ||+ (findRow('Archive')?.disabled === 'true' &&+ findRow('Archive')?.tabIndex === null &&+ findRow('Export')?.spinnerHidden === true &&+ findRow('Share')?.haspopup === 'menu'),+ indicatorMirror:+ item.interaction === 'drill-in' ||+ rows+ .filter(entry => entry.indicatorTransform !== null)+ .every(entry =>+ item.direction === 'rtl'+ ? entry.indicatorTransform?.startsWith('matrix(-1') === true+ : entry.indicatorTransform === 'none',+ ),+ rowGeometry: rows.every(+ entry => entry.geometry.width > 0 && entry.geometry.height >= 24,+ ),+ counters:+ counters === null ||+ (observed.counters !== null &&+ observed.counters.picked === counters.picked &&+ observed.counters.open === counters.open &&+ observed.counters.close === counters.close),+ };++ const png = await page.screenshot({animations: 'disabled'});+ if (item.interaction === 'pressed') {+ await page.mouse.up();+ }+ const image = `${item.key}.png`;+ const receipt = {+ schemaVersion: 1,+ expected: {+ build: checkoutSha,+ storyId: isRegions ? REGIONS_STORY : ROW_STORY,+ ...item,+ expanded: expectedExpanded[item.interaction],+ activeRow: active ?? null,+ counters,+ },+ observed: {+ build: storybookSha,+ browser: context.browser()?.version() ?? null,+ ...observed,+ settledGeometry,+ pageErrors,+ },+ image: {+ file: image,+ sha256: createHash('sha256').update(png).digest('hex'),+ width: png.readUInt32BE(16),+ height: png.readUInt32BE(20),+ },+ checks,+ passed: Object.values(checks).every(Boolean),+ };+ fs.writeFileSync(path.join(OUTPUT, image), png);+ fs.writeFileSync(+ path.join(OUTPUT, `${item.key}.sensors.json`),+ `${JSON.stringify(receipt, null, 2)}\n`,+ );+ await context.close();+ expect(+ Object.entries(checks)+ .filter(([, passed]) => !passed)+ .map(([name]) => name),+ ).toEqual([]);+ });+}