An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] CollapsibleGroup: restore browser audit coverage (#6944)
Cindy Zhangb9f454beff8f
diff --git a/.changeset/collapsible-group-stable-context.md b/.changeset/collapsible-group-stable-context.mdnew file mode 100644index 0000000000..fb7df55878--- /dev/null+++ b/.changeset/collapsible-group-stable-context.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Preserve `CollapsibleGroup` context identity when a controlled string value is unchanged, avoiding unnecessary grouped-item rerenders.++@cixzhangdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex e19cd4b606..ef21c9aa02 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -1307,6 +1307,35 @@ jobs:retention-days: 30if-no-files-found: ignore+ # CollapsibleGroup's shared Collapsible story previously left the audit+ # owner with no routable browser fixture. Its dedicated matrix now emits+ # semantic-state, geometry, direction, theme, and viewport receipts.+ - name: Run CollapsibleGroup audit browser evidence+ if: github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CollapsibleGroup:')+ env:+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ run: |+ node .github/scripts/accessibility-audit.js \+ --storybook-dir apps/storybook/dist \+ --output collapsible-group-a11y-report.json \+ --components CollapsibleGroup \+ --baseline .github/a11y-baseline.json \+ --fail-on-new+ pnpm exec playwright test \+ packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.chromium.spec.ts \+ --project chromium++ - name: Upload CollapsibleGroup audit evidence+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] CollapsibleGroup:')+ uses: actions/upload-artifact@v7+ with:+ name: collapsible-group-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}+ path: |+ collapsible-group-a11y-report.json+ test-results/collapsible-group-audit-evidence/+ retention-days: 30+ if-no-files-found: error+# Component-owned metadata fixtures retain exact-head browser receipts on# audit PRs, including failed pre-fix cases for before/after comparison.- name: Run ChatMessageMetadata audit browser evidencediff --git a/apps/storybook/stories/CollapsibleGroup.stories.tsx b/apps/storybook/stories/CollapsibleGroup.stories.tsxnew file mode 100644index 0000000000..0badd98a0e--- /dev/null+++ b/apps/storybook/stories/CollapsibleGroup.stories.tsx@@ -0,0 +1,138 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import * as stylex from '@stylexjs/stylex';+import {Collapsible, CollapsibleGroup} from '@astryxdesign/core/Collapsible';+import {Heading} from '@astryxdesign/core/Heading';+import {VStack} from '@astryxdesign/core/Layout';+import {+ colorVars,+ spacingVars,+ typographyVars,+} from '@astryxdesign/core/theme/tokens.stylex';++const styles = stylex.create({+ canvas: {+ backgroundColor: colorVars['--color-background-body'],+ color: colorVars['--color-text-primary'],+ fontFamily: typographyVars['--font-family-body'],+ maxWidth: 720,+ padding: spacingVars['--spacing-6'],+ },+ body: {+ color: colorVars['--color-text-secondary'],+ marginBlock: 0,+ },+});++const meta: Meta<typeof CollapsibleGroup> = {+ title: 'Core/CollapsibleGroup',+ component: CollapsibleGroup,+ tags: ['autodocs', 'visual-theme-matrix'],+ parameters: {layout: 'centered'},+};++export default meta;+type Story = StoryObj<typeof meta>;++export const AuditMatrix: Story = {+ render: () => (+ <VStack gap={6} xstyle={styles.canvas}>+ <section aria-labelledby="collapsible-group-single-heading">+ <VStack gap={2}>+ <Heading level={2} id="collapsible-group-single-heading">+ Single selection with leading chevrons+ </Heading>+ <CollapsibleGroup+ type="single"+ hasDividers+ chevronPosition="start"+ defaultValue="profile">+ <Collapsible trigger="Profile settings" value="profile">+ <p {...stylex.props(styles.body)}>+ Update the profile details shown to other people.+ </p>+ </Collapsible>+ <Collapsible trigger="Privacy settings" value="privacy">+ <p {...stylex.props(styles.body)}>+ Choose who can see profile activity.+ </p>+ </Collapsible>+ </CollapsibleGroup>+ </VStack>+ </section>++ <section aria-labelledby="collapsible-group-multiple-heading">+ <VStack gap={2}>+ <Heading level={2} id="collapsible-group-multiple-heading">+ Multiple selection with compact rows+ </Heading>+ <CollapsibleGroup+ type="multiple"+ hasDividers+ density="compact"+ defaultValue={['deployment', 'logs']}>+ <Collapsible trigger="Deployment details" value="deployment">+ <p {...stylex.props(styles.body)}>+ The current release is available to everyone.+ </p>+ </Collapsible>+ <Collapsible trigger="Environment variables" value="environment">+ <p {...stylex.props(styles.body)}>+ Twelve variables are configured.+ </p>+ </Collapsible>+ <Collapsible trigger="Build logs" value="logs">+ <p {...stylex.props(styles.body)}>+ The latest build completed successfully.+ </p>+ </Collapsible>+ </CollapsibleGroup>+ </VStack>+ </section>++ <section aria-labelledby="collapsible-group-plain-heading">+ <VStack gap={2}>+ <Heading level={2} id="collapsible-group-plain-heading">+ Plain group with default unpadded rows+ </Heading>+ <CollapsibleGroup type="single" defaultValue="access">+ <Collapsible trigger="Account access" value="access">+ <p {...stylex.props(styles.body)}>+ People with access can sign in to this workspace.+ </p>+ </Collapsible>+ <Collapsible trigger="Notifications" value="notifications">+ <p {...stylex.props(styles.body)}>+ Email notifications are sent for important changes.+ </p>+ </Collapsible>+ </CollapsibleGroup>+ </VStack>+ </section>++ <section aria-labelledby="collapsible-group-spacious-heading">+ <VStack gap={2}>+ <Heading level={2} id="collapsible-group-spacious-heading">+ Spacious group without dividers+ </Heading>+ <CollapsibleGroup+ type="multiple"+ density="spacious"+ defaultValue={['retention']}>+ <Collapsible trigger="Data retention" value="retention">+ <p {...stylex.props(styles.body)}>+ Records are retained for the configured period.+ </p>+ </Collapsible>+ <Collapsible trigger="Audit exports" value="exports">+ <p {...stylex.props(styles.body)}>+ Exports are available to workspace administrators.+ </p>+ </Collapsible>+ </CollapsibleGroup>+ </VStack>+ </section>+ </VStack>+ ),+};diff --git a/packages/core/src/Collapsible/CollapsibleGroup.spec.md b/packages/core/src/Collapsible/CollapsibleGroup.spec.mdnew file mode 100644index 0000000000..f2f8cd5f37--- /dev/null+++ b/packages/core/src/Collapsible/CollapsibleGroup.spec.md@@ -0,0 +1,192 @@+---+schema_version: 3+template_version: 7+kind: component+id: component:CollapsibleGroup+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang, imdreamrunner]+review_triggers: [public-api, behavior, layout, accessibility, theming]+verified_by:+ [+ packages/core/src/Collapsible/CollapsibleGroup.test.tsx,+ packages/core/src/Collapsible/Collapsible.test.tsx,+ packages/core/src/Collapsible/__tests__/Collapsible.a11y.test.tsx,+ packages/core/src/Collapsible/__tests__/Collapsible.a11y.chromium.spec.ts,+ packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.chromium.spec.ts,+ packages/core/src/theme/themingTargets.test.ts,+ apps/storybook/stories/CollapsibleGroup.stories.tsx,+ ]+modules: []+families: []+design_specs: []+architecture:+ [+ architecture:public-component-api,+ architecture:react-component-runtime,+ architecture:component-theming-surface,+ architecture:component-test-sufficiency,+ ]+contributing: [contributing:api-conventions]+system_specs: [spec:AST-029]+---++# CollapsibleGroup component contract++## Contract at a glance++| Area | Contract |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `CollapsibleGroup` coordinates public `Collapsible` children in `single` or `multiple` mode, supports controlled and uncontrolled values, and optionally supplies divider, density, and chevron-position presentation defaults. |+| Behavior | Direct children with a `value` read group state; opening an item replaces or extends the open-value set according to mode. The group renders no wrapper unless divider chrome is enabled. |+| End-user impact | People can reveal one section or several sections without disclosure state drifting between sibling rows; divided groups keep one coherent visual and directional treatment. |+| Builder impact | Builders choose state ownership and selection mode, give participating items stable values, and may opt into divided-row presentation. |+| Compatibility/readiness | Released DOM output, props, defaults, targets, and migration promises are unchanged. An unchanged controlled string preserves the coordination broadcast identity instead of rerendering every consumer. |+| Review checks | Reject lost single/multiple coordination, controlled state that mutates internally, uncontrolled state that stops updating, presentation leakage into nested disclosures, or a wrapper appearing when dividers are absent. |+| Governing rules | `component:Collapsible/FR7–FR9,DEC-2`; `architecture:public-component-api/INV1,INV5–INV9`; `architecture:react-component-runtime/INV1,INV8–INV9`; `architecture:component-theming-surface/INV3–INV7`. |++This table is a review projection; the body below is authoritative only after owner approval.++## Intent++Coordinate a set of disclosure items so their open state follows one group owner while each `Collapsible` continues to own its trigger, region, and disclosure semantics.++## Compatibility and migration++- Released default preserved: yes+- Compatibility class: compatible runtime efficiency correction; no DOM output, public type, default, target, export, or migration change+- Controlled/uncontrolled behavior: unchanged+- Migration decision: none++Consumer migration instructions belong in consumer docs and release notes.++## Ownership boundary++**Owns**++- sibling open-value coordination in single and multiple modes;+- controlled and uncontrolled group state ownership and the shape delivered to `onChange`;+- the optional divided-row wrapper, density default, and group presentation context; and+- direct-item defaults for density and chevron position.++**Does not own / non-goals**++- disclosure trigger, region, chevron artwork, semantics, or nested presentation reset — owned by `component:Collapsible`;+- caller content, item labels, or the meaning and uniqueness of caller-supplied values — owned by the product callsite; or+- arbitrary selection models beyond the released single and multiple modes.++## Public concepts++| Concept | Closed values or states | Meaning | Availability | Default | Owner | Stability | Invalid-value behavior |+| -------------------- | ------------------------------------------- | --------------------------------------------------------------------------- | --------------------- | ------------------------------ | ---------------------------- | --------- | --------------------------- |+| coordination mode | `single`, `multiple` | Replaces the open set or toggles one member within it. | Every group. | `single` | `component:CollapsibleGroup` | stable | rejected by the public type |+| state ownership | uncontrolled, controlled | Internal state starts from `defaultValue`, or `value` remains caller-owned. | Every group. | uncontrolled | `component:CollapsibleGroup` | stable | ordinary React semantics |+| divided presentation | absent, present | Adds one wrapper and asks direct items to draw row dividers. | Every group. | absent | `component:CollapsibleGroup` | stable | rejected by the public type |+| row density | unpadded, `compact`, `balanced`, `spacious` | Supplies direct-item block padding; divided groups fall back to balanced. | Direct grouped items. | unpadded; balanced if divided | `component:CollapsibleGroup` | stable | rejected by the public type |+| chevron default | absent, `start`, `end` | Supplies the position default owned by `component:Collapsible`. | Direct grouped items. | absent; item resolves to `end` | `component:Collapsible` | stable | rejected by the public type |++## Behavioral and layout contract++| ID | Candidate invariant | Basis | Draft review state |+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | ------------------ |+| FR1 | In `single` mode, toggling a closed direct item MUST replace the open-value set with that item, and toggling the open item MUST clear the set. | shipped source, consumer docs, and focused interaction tests | verify |+| FR2 | In `multiple` mode, toggling a direct item MUST add or remove only that value while preserving the state of other values. | shipped source, consumer docs, and focused interaction tests | verify |+| FR3 | Supplying `value` MUST keep state caller-owned and report requested changes through `onChange`; omitting it MUST keep state internal after initialization from `defaultValue`. | `architecture:react-component-runtime/INV1,INV8`; shipped controlled and uncontrolled tests | verify |+| FR4 | A direct `Collapsible` with a `value` MUST use group coordination; an item without a value MUST retain standalone ownership. | shipped hook behavior and focused group/standalone tests | verify |+| FR5 | With `hasDividers=false`, the group MUST add no DOM wrapper. With dividers enabled it MUST render one wrapper that receives documented root props and the `collapsible-group` target. | `architecture:public-component-api/INV5–INV8`; `architecture:component-theming-surface/INV3–INV7` | verify |+| FR6 | Density, divider, and chevron defaults MUST reach direct items without leaking through a direct item's revealed content into nested independent disclosures. | `component:Collapsible/FR7–FR8,DEC-2`; focused nesting tests | settled |+| FR7 | Presentation context identity MUST remain stable while divider, density, and chevron inputs are unchanged; coordination identity MUST change only when the open-value behavior it broadcasts changes. | `architecture:react-component-runtime/INV9`; memoized source and interaction tests | verify |++### Allowed variation++- **AV1 — Internal state representation.** The group may represent open values with arrays or another private structure while preserving FR1–FR4 and callback output.+- **AV2 — Wrapper implementation.** Divider mode may change internal layout technique while retaining one painting wrapper, the public target, root-prop reachability, and direct-item results.+- **AV3 — Item composition.** Callers may place direct Collapsible items beside non-participating content; only valued Collapsible children join coordination.++### Representative states++| State | Required invariant | Allowed variation |+| ---------------------------------- | ----------------------------------------------------------------------------- | ----------------------------- |+| single, uncontrolled | One valued item or none is open and internal state updates after each toggle. | Item labels and content. |+| multiple, uncontrolled | Any number of valued items may remain open. | Item order and content. |+| controlled | Rendered state follows `value`; `onChange` reports requested next state. | Parent update timing. |+| divided, density omitted | One wrapper paints the group target and direct items use balanced density. | Theme paint. |+| plain, density omitted | No wrapper appears and direct items remain unpadded. | Surrounding caller layout. |+| group position with nested content | Direct items inherit the group position; nested disclosures reset it. | Item-level explicit override. |++### Transformation and precedence order++- **ORD1 — State ownership.** Controlled `value` when present → internal value initialized from `defaultValue` otherwise → mode-specific toggle → callback in the mode's documented output shape.+- **ORD2 — Density.** Explicit group density → `balanced` when dividers are enabled → no group density.+- **ORD3 — Chevron position.** Explicit item position → direct group position → Collapsible default `end`, as owned by `component:Collapsible/ORD1`.++### Performance and resources++- **PR1 — Render-owned coordination.** The group derives output from props, state, and context and owns no Effect, listener, observer, timer, request, subscription, or imperative browser resource.+- **PR2 — Stable broadcasts.** Memoized context values prevent unchanged semantic payloads from broadcasting new identities to direct consumers.++## Accessibility contract++- **AR1 — Child semantics remain primary.** Group coordination MUST preserve each Collapsible button's accessible name, `aria-expanded`, `aria-controls`, controlled region, and keyboard activation.+- **AR2 — Presentation adds no competing interaction.** The divider wrapper MUST NOT add a role, focus target, accessible name, or keyboard behavior.+- **AR3 — Direction stays with Collapsible.** Group chevron defaults MUST preserve `component:Collapsible/AR1–AR3`, including the inward leading cue under LTR and RTL.++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | ------------------------------------------------------------------------- | ------------------------------- | ------------------- | ------------------ |+| Group container | Optional divider chrome visually associates sibling disclosures as a set. | observed shipped representation | aggregate container | FR5–FR6, AR2 |+| Direct item | Density and chevron defaults remain consistent across sibling rows. | `component:Collapsible/FR7–FR8` | disclosure row | FR6, AR3 |++No current design record prescribes exact CollapsibleGroup pixels. This observational draft records the shipped divided and plain relationships without deciding new visual direction.++### Theming anatomy++<!-- anatomy-theming:v1 -->++```json+{+ "Container": {"target": "collapsible"},+ "Trigger": {"target": "collapsible-trigger"},+ "Chevron": {+ "delegatesTo": {"owner": "component:Icon", "target": "icon"}+ },+ "Content": {"target": "collapsible-content"},+ "Group container": {"target": "collapsible-group"}+}+```++The Group container is CollapsibleGroup's conditional aggregate wrapper. The other anatomy rows remain owned by `component:Collapsible`; they are repeated in this observational subcomponent map only because the released consumer anatomy and target inventory are shared. Trigger, content, chevron, open state, disabled state, density padding, and per-item dividers remain with Collapsible's contract.++## Family and system relationships++- `component:Collapsible` owns direct-item disclosure semantics, chevron representation, item-level theming anatomy, and nested presentation reset.+- `architecture:public-component-api` owns export reachability, documented root-prop behavior, controlled API stability, styling composition, and conditional ref reachability.+- `architecture:react-component-runtime` owns render-derived state, stable context broadcast identity, and controlled-state ownership boundaries.+- `architecture:component-theming-surface` owns target qualification, target placement, visual-axis reflection, and delegated item ownership.+- `architecture:component-test-sufficiency` owns the rational evidence set across state coordination, browser accessibility, direction, and rendered presentation.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ---------------------- | ----------------------------------------------------------------------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------- |+| FR1–FR4, ORD1 | `CollapsibleGroup.test.tsx`; `useCollapsible.test.tsx` | single/multiple; controlled/uncontrolled; valued/unvalued | A sibling stays open in single mode, closes in multiple mode, controlled state mutates internally, or an unvalued item loses local state. | `audit:CollapsibleGroup/behavior` |+| FR5–FR6, ORD2–ORD3 | `CollapsibleGroup.test.tsx`; `Collapsible.test.tsx`; `themingTargets.test.ts` | plain/divided; each density; group/item/nested position | Wrapper/target reachability changes, defaults stop reaching direct items, or presentation leaks into nested content. | `audit:CollapsibleGroup/theming` |+| AR1–AR3 | DOM and Chromium accessibility suites; component-owned Storybook fixture; RTL audit | open/closed; single/multiple; leading/trailing; LTR/RTL | Disclosure semantics diverge from state, the wrapper becomes interactive, or leading direction stops mirroring. | `audit:CollapsibleGroup/accessibility` |+| PR1–PR2, FR7 | source review plus context and interaction tests | unchanged and changed state/presentation inputs | An Effect/resource appears, unchanged payload broadcasts a new identity, or changed group behavior fails to reach consumers. | `audit:CollapsibleGroup/code-health` |+| Consumer documentation | CLI component projection, docs checks, and `CollapsibleGroup.stories.tsx` | every public concept and representative composition | A released prop/default is undiscoverable or the owned browser route loses representative state coverage. | `audit:CollapsibleGroup/docs` |++## Decision log++None. This audit records shipped behavior and delegates chevron representation to the current Collapsible contract; it makes no new product decision.++## Open questions++None. This observational draft does not broaden the released coordination modes or decide new presentation.++## Content boundary++This file does not duplicate consumer prop tables, examples, current audit scores, implementation steps, or Collapsible's disclosure and chevron rules. It links to their owners.diff --git a/packages/core/src/Collapsible/CollapsibleGroup.test.tsx b/packages/core/src/Collapsible/CollapsibleGroup.test.tsxindex 4cb7765988..f85aaeafb9 100644--- a/packages/core/src/Collapsible/CollapsibleGroup.test.tsx+++ b/packages/core/src/Collapsible/CollapsibleGroup.test.tsx@@ -9,11 +9,13 @@* SYNC: When Collapsible.tsx or CollapsibleGroup.tsx changes, update tests*/+import {memo, use} from 'react';import {describe, it, expect, vi} from 'vitest';import {render, screen} from '@testing-library/react';import userEvent from '@testing-library/user-event';import {Collapsible} from './Collapsible';import {CollapsibleGroup} from './CollapsibleGroup';+import {CollapsibleGroupContext} from './CollapsibleGroupContext';// =============================================================================// Collapsible — standalone behavior@@ -242,6 +244,29 @@ describe('CollapsibleGroup', () => {expect(screen.getByText('Content A')).not.toBeVisible();expect(screen.getByText('Content B')).toBeVisible();});++ it('preserves the context value on an unchanged controlled-string rerender', () => {+ const renderProbe = vi.fn();+ const Probe = memo(function Probe() {+ use(CollapsibleGroupContext);+ renderProbe();+ return null;+ });++ const {rerender} = render(+ <CollapsibleGroup type="single" value="a">+ <Probe />+ </CollapsibleGroup>,+ );+ expect(renderProbe).toHaveBeenCalledTimes(1);++ rerender(+ <CollapsibleGroup type="single" value="a">+ <Probe />+ </CollapsibleGroup>,+ );+ expect(renderProbe).toHaveBeenCalledTimes(1);+ });});describe('defaultValue', () => {diff --git a/packages/core/src/Collapsible/CollapsibleGroup.tsx b/packages/core/src/Collapsible/CollapsibleGroup.tsxindex 5753556fcc..37006e4111 100644--- a/packages/core/src/Collapsible/CollapsibleGroup.tsx+++ b/packages/core/src/Collapsible/CollapsibleGroup.tsx@@ -197,9 +197,10 @@ export function CollapsibleGroup({normalizeToArray(defaultValue),);- const openValues = isControlled- ? normalizeToArray(controlledValue)- : internalValue;+ const openValues = useMemo(+ () => (isControlled ? normalizeToArray(controlledValue) : internalValue),+ [controlledValue, internalValue, isControlled],+ );const isOpen = useCallback((itemValue: string) => openValues.includes(itemValue),diff --git a/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.chromium.spec.ts b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.chromium.spec.tsnew file mode 100644index 0000000000..6f855df215--- /dev/null+++ b/packages/core/src/Collapsible/__tests__/CollapsibleGroup.a11y.chromium.spec.ts@@ -0,0 +1,558 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file CollapsibleGroup.a11y.chromium.spec.ts+ * @input Uses the component-owned Storybook fixture and exact-head build stamp+ * @output Chromium screenshots and fail-closed semantic sensor receipts+ * @position Browser evidence for the CollapsibleGroup audit+ */++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 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('test-results/collapsible-group-audit-evidence');+const STORY_ID = 'core-collapsiblegroup--audit-matrix';+const WIDE = {width: 1024, height: 900};+const NARROW = {width: 320, height: 720};+const EXPANDED_NAMES = [+ 'Profile settings',+ 'Deployment details',+ 'Build logs',+ 'Account access',+ 'Data retention',+];+const COLLAPSED_NAMES = [+ 'Privacy settings',+ 'Environment variables',+ 'Notifications',+ 'Audit exports',+];++interface Case {+ state: string;+ mode: 'light' | 'dark';+ direction: 'ltr' | 'rtl';+ viewport: {width: number; height: number};+}++const CASES: Case[] = [+ {state: 'wide-light-ltr', mode: 'light', direction: 'ltr', viewport: WIDE},+ {state: 'wide-dark-ltr', mode: 'dark', direction: 'ltr', viewport: WIDE},+ {state: 'wide-light-rtl', mode: 'light', direction: 'rtl', viewport: WIDE},+ {state: 'wide-dark-rtl', mode: 'dark', direction: 'rtl', viewport: WIDE},+ {+ state: 'narrow-light',+ mode: 'light',+ direction: 'ltr',+ viewport: NARROW,+ },+ {+ state: 'narrow-dark',+ mode: 'dark',+ direction: 'ltr',+ viewport: NARROW,+ },+];++const frames: Record<string, unknown>[] = [];+const stateVisualMatrix: Record<string, unknown>[] = [];+const contrastPairMatrix: Record<string, unknown>[] = [];+let storybook: StaticServer;+let checkoutSha: string;+let storybookSha: string;+let browserVersion = 'unknown';++test.beforeAll(async () => {+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {+ encoding: 'utf8',+ }).trim();+ const expectedHead = process.env.ASTRYX_HEAD_SHA;+ if (expectedHead && expectedHead !== checkoutSha) {+ throw new Error('The audited checkout does not match the PR head');+ }+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+ const stamp = await fetch(`${storybook.origin}/astryx-build-sha.txt`);+ if (!stamp.ok) {+ throw new Error(+ `The Storybook build has no source stamp (${stamp.status})`,+ );+ }+ storybookSha = (await stamp.text()).trim();+ if (storybookSha !== checkoutSha) {+ throw new Error(+ 'The served Storybook build does not match the audited checkout',+ );+ }+ fs.mkdirSync(OUTPUT, {recursive: true});+});++test.afterAll(async () => {+ if (checkoutSha && storybookSha) {+ fs.writeFileSync(+ path.join(OUTPUT, 'manifest.json'),+ `${JSON.stringify(+ {+ version: 1,+ component: 'core/CollapsibleGroup',+ headSha: checkoutSha,+ storybookSha,+ browser: browserVersion,+ frames,+ stateVisualMatrix,+ contrastPairMatrix,+ },+ null,+ 2,+ )}\n`,+ );+ }+ await storybook?.close();+});++async function capture(page: Page, scenario: Case) {+ const errors: string[] = [];+ const onError = (error: Error) => errors.push(String(error));+ page.on('pageerror', onError);+ try {+ await page.setViewportSize(scenario.viewport);+ await page.emulateMedia({reducedMotion: 'reduce'});+ browserVersion = page.context().browser()?.version() ?? 'unknown';+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY_ID}&viewMode=story&globals=colorMode:${scenario.mode};astryxTheme:neutral;direction:${scenario.direction}`,+ );+ const canvas = page.locator('#storybook-root');+ const subject = canvas.locator(':scope > *').first();+ await canvas.waitFor();+ await subject.waitFor();+ await holdMotionStill(page);+ await page.evaluate(async () => document.fonts.ready);+ await page.waitForFunction(+ expected =>+ document.documentElement.getAttribute('data-theme') === expected,+ scenario.mode,+ );+ await page.waitForFunction(+ expected =>+ document.querySelector('#storybook-root [dir]')?.getAttribute('dir') ===+ expected,+ scenario.direction,+ );++ await expect(canvas).toBeVisible();+ await expect(subject).toBeVisible();+ await canvas.scrollIntoViewIfNeeded();+ await page.evaluate(async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });+ const initialBox = await canvas.boundingBox();+ if (initialBox == null) {+ throw new Error(+ `${scenario.state}: the Storybook canvas has no layout box`,+ );+ }+ await page.evaluate(async () => {+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ });+ const box = await canvas.boundingBox();+ if (box == null) {+ throw new Error(+ `${scenario.state}: the Storybook canvas lost its layout box before capture`,+ );+ }+ const geometryDelta = Math.max(+ Math.abs(box.x - initialBox.x),+ Math.abs(box.y - initialBox.y),+ Math.abs(box.width - initialBox.width),+ Math.abs(box.height - initialBox.height),+ );++ const observed = await subject.evaluate(node => {+ const buttons = [...node.querySelectorAll('button')];+ const groups = [...node.querySelectorAll('.astryx-collapsible-group')];+ const chevrons = buttons.flatMap(button => {+ const chevron = button.querySelector('svg');+ return chevron ? [chevron] : [];+ });+ const geometry = (element: Element) => {+ const rect = element.getBoundingClientRect();+ return {+ x: rect.x,+ y: rect.y,+ width: rect.width,+ height: rect.height,+ };+ };+ type Color = {r: number; g: number; b: number; a: number};+ const parseColor = (value: string): Color => {+ const channels = value.match(/[\d.]+/g)?.map(Number);+ if (!channels || channels.length < 3) {+ throw new Error(`Cannot parse computed color: ${value}`);+ }+ return {+ r: channels[0] ?? 0,+ g: channels[1] ?? 0,+ b: channels[2] ?? 0,+ a: channels[3] ?? 1,+ };+ };+ const composite = (foreground: Color, background: Color): Color => {+ const a = foreground.a + background.a * (1 - foreground.a);+ if (a === 0) {+ return {r: 0, g: 0, b: 0, a: 0};+ }+ return {+ r:+ (foreground.r * foreground.a ++ background.r * background.a * (1 - foreground.a)) /+ a,+ g:+ (foreground.g * foreground.a ++ background.g * background.a * (1 - foreground.a)) /+ a,+ b:+ (foreground.b * foreground.a ++ background.b * background.a * (1 - foreground.a)) /+ a,+ a,+ };+ };+ const renderedBackground = (element: Element): Color => {+ const layers: Color[] = [];+ let current: Element | null = element;+ while (current) {+ const layer = parseColor(getComputedStyle(current).backgroundColor);+ if (layer.a > 0) {+ layers.push(layer);+ }+ if (layer.a >= 0.999) {+ break;+ }+ current = current.parentElement;+ }+ return layers+ .reverse()+ .reduce(+ (background, foreground) => composite(foreground, background),+ {r: 255, g: 255, b: 255, a: 1},+ );+ };+ const formatColor = ({r, g, b, a}: Color) =>+ `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${a.toFixed(3)})`;+ const luminance = ({r, g, b}: Color) => {+ const channel = (value: number) => {+ const normalized = value / 255;+ return normalized <= 0.04045+ ? normalized / 12.92+ : ((normalized + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);+ };+ const contrast = (left: Color, right: Color) => {+ const leftLuminance = luminance(left);+ const rightLuminance = luminance(right);+ return (+ (Math.max(leftLuminance, rightLuminance) + 0.05) /+ (Math.min(leftLuminance, rightLuminance) + 0.05)+ );+ };+ const isVisible = (element: Element) => {+ const rect = element.getBoundingClientRect();+ const style = getComputedStyle(element);+ return (+ rect.width > 0 &&+ rect.height > 0 &&+ style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ style.opacity !== '0'+ );+ };+ const visibleContent = buttons+ .filter(button => button.getAttribute('aria-expanded') === 'true')+ .flatMap(button => {+ const id = button.getAttribute('aria-controls');+ const controlled = id ? document.getElementById(id) : null;+ return controlled ? [...controlled.querySelectorAll('p')] : [];+ });+ const contrastPairs = [+ ...node.querySelectorAll('h2'),+ ...buttons,+ ...visibleContent,+ ...chevrons,+ ]+ .filter(isVisible)+ .map(element => {+ const style = getComputedStyle(element);+ const background = renderedBackground(element);+ const foreground = parseColor(style.color);+ const renderedForeground = composite(foreground, background);+ const ratio = contrast(renderedForeground, background);+ const fontSize = Number.parseFloat(style.fontSize);+ const fontWeight =+ style.fontWeight === 'bold'+ ? 700+ : Number.parseFloat(style.fontWeight) || 400;+ const threshold =+ element.tagName === 'svg'+ ? 3+ : fontSize >= 24 || (fontSize >= 18.66 && fontWeight >= 700)+ ? 3+ : 4.5;+ const ownerButton = element.closest('button');+ const ownerText = ownerButton?.innerText.trim();+ const text =+ element instanceof HTMLElement ? element.innerText.trim() : '';+ const part =+ element.tagName === 'svg'+ ? `chevron: ${ownerText ?? 'unknown trigger'}`+ : element.tagName === 'H2'+ ? `heading: ${text}`+ : element.tagName === 'BUTTON'+ ? `trigger: ${text}`+ : `content: ${text}`;+ return {+ part,+ state:+ element.tagName === 'BUTTON' || element.tagName === 'svg'+ ? (ownerButton ?? element).getAttribute('aria-expanded') ===+ 'true'+ ? 'expanded-rest'+ : 'collapsed-rest'+ : 'rest',+ meaningful: true,+ foreground: style.color,+ renderedForeground: formatColor(renderedForeground),+ renderedBackdrop: formatColor(background),+ fontSize,+ fontWeight,+ ratio: Number(ratio.toFixed(2)),+ threshold,+ exception: null,+ passed: ratio + 1e-6 >= threshold,+ };+ });+ return {+ direction: groups[0]+ ? getComputedStyle(groups[0]).direction+ : getComputedStyle(node).direction,+ groupDirections: groups.map(+ element => getComputedStyle(element).direction,+ ),+ buttonDirections: buttons.map(+ element => getComputedStyle(element).direction,+ ),+ text: (node as HTMLElement).innerText,+ sectionCount: node.querySelectorAll('section').length,+ headingCount: node.querySelectorAll('h2').length,+ groupCount: groups.length,+ buttonCount: buttons.length,+ chevronCount: chevrons.length,+ expandedNames: buttons+ .filter(button => button.getAttribute('aria-expanded') === 'true')+ .map(button => (button as HTMLElement).innerText.trim()),+ collapsedNames: buttons+ .filter(button => button.getAttribute('aria-expanded') === 'false')+ .map(button => (button as HTMLElement).innerText.trim()),+ groupGeometry: groups.map(geometry),+ buttonGeometry: buttons.map(geometry),+ chevronGeometry: chevrons.map(geometry),+ contrastPairs,+ };+ });+ const environment = await page.evaluate(() => ({+ theme: document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme'),+ declaredDirection: document+ .querySelector('#storybook-root [dir]')+ ?.getAttribute('dir'),+ mode: document.documentElement.getAttribute('data-theme'),+ colorScheme: getComputedStyle(document.documentElement).colorScheme,+ fonts: document.fonts.status,+ viewport: {width: innerWidth, height: innerHeight},+ dpr: devicePixelRatio,+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,+ forcedColors: matchMedia('(forced-colors: active)').matches,+ horizontalOverflow: document.documentElement.scrollWidth > innerWidth + 1,+ storyError: [+ ...document.querySelectorAll(+ '.sb-errordisplay, [data-testid="story-error"]',+ ),+ ].some(element => {+ const errorBox = element.getBoundingClientRect();+ const style = getComputedStyle(element);+ return (+ errorBox.width > 0 &&+ errorBox.height > 0 &&+ style.display !== 'none' &&+ style.visibility !== 'hidden' &&+ style.opacity !== '0'+ );+ }),+ }));++ // Every expectation is authored from the fixture and current component+ // contract before the page is observed. A failed sensor mints no frame.+ expect(await page.locator('#storybook-root > *').count()).toBe(1);+ expect(await subject.isVisible()).toBe(true);+ expect(geometryDelta).toBeLessThanOrEqual(0.5);+ expect(observed.direction).toBe(scenario.direction);+ expect(observed.groupDirections).toEqual([+ scenario.direction,+ scenario.direction,+ ]);+ expect(observed.buttonDirections).toEqual(+ Array.from({length: 9}, () => scenario.direction),+ );+ expect(observed.sectionCount).toBe(4);+ expect(observed.headingCount).toBe(4);+ expect(observed.groupCount).toBe(2);+ expect(observed.buttonCount).toBe(9);+ expect(observed.chevronCount).toBe(9);+ expect(observed.expandedNames).toEqual(EXPANDED_NAMES);+ expect(observed.collapsedNames).toEqual(COLLAPSED_NAMES);+ expect(observed.text).toContain('Single selection with leading chevrons');+ expect(observed.text).toContain('Multiple selection with compact rows');+ expect(observed.text).toContain('Plain group with default unpadded rows');+ expect(observed.text).toContain('Spacious group without dividers');+ expect(box.width).toBeGreaterThan(0);+ expect(box.height).toBeGreaterThan(0);+ for (const geometry of [+ ...observed.groupGeometry,+ ...observed.buttonGeometry,+ ...observed.chevronGeometry,+ ]) {+ expect(geometry.width).toBeGreaterThan(0);+ expect(geometry.height).toBeGreaterThan(0);+ }+ expect(observed.contrastPairs).toHaveLength(27);+ for (const pair of observed.contrastPairs) {+ expect(pair.passed, `${scenario.state}: ${pair.part}`).toBe(true);+ expect(+ pair.ratio,+ `${scenario.state}: ${pair.part}`,+ ).toBeGreaterThanOrEqual(pair.threshold);+ }+ expect(environment.theme).toBe('neutral');+ expect(environment.declaredDirection).toBe(scenario.direction);+ expect(environment.mode).toBe(scenario.mode);+ expect(environment.colorScheme).toBe(scenario.mode);+ expect(environment.fonts).toBe('loaded');+ expect(environment.viewport).toEqual(scenario.viewport);+ expect(environment.reducedMotion).toBe(true);+ expect(environment.forcedColors).toBe(false);+ expect(environment.horizontalOverflow).toBe(false);+ expect(environment.storyError).toBe(false);+ expect(errors).toEqual([]);++ const file = `CollapsibleGroup__${scenario.state}.png`;+ const stateVisualRows = [+ {+ stateCaptured:+ 'rest matrix: divided balanced, divided compact, plain default-unpadded, and plain spacious groups with expanded and collapsed disclosure semantics',+ screenshot: file,+ approvedRepresentation:+ 'Rest — base tokens, no interaction (Design Conventions §Consistent State Representations)',+ tokenSignature:+ 'base group, divider, default-unpadded, compact, balanced, spacious, text, and chevron tokens; no hover, focus, pressed, selected, disabled, loading, or status treatment',+ tokenSignaturePresent: true,+ matchesReference: 'yes',+ verdict: 'pass',+ note: 'Expanded and collapsed content are disclosure semantics delegated to the current Collapsible contract, not a novel interaction-state paint.',+ },+ ];+ const contrastRows = observed.contrastPairs.map(pair => ({+ screenshot: file,+ theme: 'neutral',+ mode: scenario.mode,+ direction: scenario.direction,+ viewport: scenario.viewport,+ ...pair,+ }));+ const png = await canvas.screenshot({animations: 'disabled'});+ expect(png.length).toBeGreaterThan(100);+ const receipt = {+ expected: {+ build: checkoutSha,+ storyId: STORY_ID,+ captureRoot: '#storybook-root',+ theme: 'neutral',+ mode: scenario.mode,+ direction: scenario.direction,+ viewport: scenario.viewport,+ rootCount: 1,+ sectionCount: 4,+ headingCount: 4,+ groupCount: 2,+ buttonCount: 9,+ chevronCount: 9,+ expandedNames: EXPANDED_NAMES,+ collapsedNames: COLLAPSED_NAMES,+ },+ observed: {+ build: storybookSha,+ storyId: STORY_ID,+ rootCount: await page.locator('#storybook-root > *').count(),+ ...observed,+ ...environment,+ pageErrors: errors.length,+ selectorVisible: await subject.isVisible(),+ captureRootVisible: await canvas.isVisible(),+ geometry: box,+ settledRender: {+ initial: initialBox,+ final: box,+ maxDelta: geometryDelta,+ },+ },+ image: {+ file,+ sha256: createHash('sha256').update(png).digest('hex'),+ width: png.readUInt32BE(16),+ height: png.readUInt32BE(20),+ },+ stateVisualMatrix: stateVisualRows,+ contrastPairMatrix: contrastRows,+ browser: browserVersion,+ passed: true,+ };+ fs.writeFileSync(path.join(OUTPUT, file), png);+ fs.writeFileSync(+ path.join(OUTPUT, `${file}.sensors.json`),+ `${JSON.stringify(receipt, null, 2)}\n`,+ );+ frames.push({+ state: scenario.state,+ receipt: `${file}.sensors.json`,+ image: receipt.image,+ });+ stateVisualMatrix.push(...stateVisualRows);+ contrastPairMatrix.push(...contrastRows);+ } finally {+ page.off('pageerror', onError);+ }+}++test('captures the complete group matrix with sensor receipts', async ({+ page,+}: {+ page: Page;+}) => {+ for (const scenario of CASES) {+ await capture(page, scenario);+ }+});