Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

[Component Audit] ChatSendButton: preserve send and stop actions with custom clicks (#6653)

Cindy Zhangdb932981e779
diff --git a/.changeset/chat-send-button-composed-click.md b/.changeset/chat-send-button-composed-click.md
new file mode 100644
index 0000000000..97153378dc
--- /dev/null
+++ b/.changeset/chat-send-button-composed-click.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Compose accepted `onClick` handlers with ChatSendButton's send and stop actions instead of replacing them (#6653). Consumers that used `onClick` to replace sending should move that logic to `onSend`, because both handlers now run.
+
+@cixzhang
diff --git a/.github/scripts/lib/a11y-story-identity.js b/.github/scripts/lib/a11y-story-identity.js
index fb3f540398..05d8f88639 100644
--- a/.github/scripts/lib/a11y-story-identity.js
+++ b/.github/scripts/lib/a11y-story-identity.js
@@ -5,7 +5,7 @@
/**
* @file Canonical owners and audited legacy-baseline aliases for a11y contract stories.
- * @input Stable Storybook IDs from the checked-in Button, Checkbox, and Radio inventories.
+ * @input Stable Storybook IDs from checked-in a11y inventories and audit fixtures.
* @output Canonical package owners plus exact prior baseline story identities.
* @position Migration boundary between reusable contract fixtures and the a11y baseline.
*/
@@ -15,6 +15,7 @@ const A11Y_STORY_OWNER_PREFIXES = Object.freeze([
['a11y-button-pattern--clickable-card-', 'core/ClickableCard'],
['a11y-button-pattern--sidenav-collapse-', 'core/SideNavCollapseButton'],
['a11y-button-pattern--chat-send', 'core/ChatSendButton'],
+ ['a11y-chatsendbutton-audit--', 'core/ChatSendButton'],
['a11y-button-pattern--button-', 'core/Button'],
['a11y-checkbox-pattern--list-item-', 'core/CheckboxListItem'],
['a11y-checkbox-pattern--menu-item-', 'core/DropdownMenuCheckboxItem'],
diff --git a/.github/scripts/lib/a11y-story-identity.test.mjs b/.github/scripts/lib/a11y-story-identity.test.mjs
index 6890e632cb..e4778093a5 100644
--- a/.github/scripts/lib/a11y-story-identity.test.mjs
+++ b/.github/scripts/lib/a11y-story-identity.test.mjs
@@ -77,6 +77,11 @@ describe('a11y story identity migration', () => {
'core/SideNavCollapseButton',
],
['a11y-button-pattern--chat-send', 'core/ChatSendButton'],
+ ['a11y-chatsendbutton-audit--chat-send-small', 'core/ChatSendButton'],
+ [
+ 'a11y-chatsendbutton-audit--chat-send-stop-small',
+ 'core/ChatSendButton',
+ ],
['a11y-checkbox-pattern--input-checked', 'core/CheckboxInput'],
[
'a11y-checkbox-pattern--menu-item-checked',
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a8d5759499..3d0ce47cdf 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1044,6 +1044,35 @@ jobs:
retention-days: 30
if-no-files-found: ignore
+ # ChatSendButton's component audit grades real interaction paint, disabled
+ # stability, both sizes, and narrow coarse-pointer geometry. Keep those
+ # receipts exact-head and bounded to its audit PR title.
+ - name: Run ChatSendButton audit browser evidence
+ if: github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatSendButton:')
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ node .github/scripts/accessibility-audit.js \
+ --storybook-dir apps/storybook/dist \
+ --output chat-send-button-a11y-report.json \
+ --components ChatSendButton \
+ --baseline .github/a11y-baseline.json \
+ --fail-on-new
+ pnpm exec playwright test \
+ packages/core/src/Chat/__tests__/ChatSendButton.a11y.chromium.spec.ts \
+ --project chromium
+
+ - name: Upload ChatSendButton audit evidence
+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatSendButton:')
+ uses: actions/upload-artifact@v7
+ with:
+ name: chat-send-button-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: |
+ chat-send-button-a11y-report.json
+ test-results/chat-send-button-audit-evidence/
+ retention-days: 30
+ if-no-files-found: error
+
# Run the exhaustive contract/fixture matrix at release time. PRs retain
# scoped axe validation and the fast interaction guards above; they must
# not pay for every component's browser bindings on every change.
diff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.json
index d776c1ba5d..66890e4bd8 100644
--- a/apps/storybook/rtl-audit/targets.json
+++ b/apps/storybook/rtl-audit/targets.json
@@ -170,6 +170,11 @@
"next": ".astryx-chat-message-bubble[data-sender=\"user\"]"
}
},
+ {
+ "component": "ChatSendButton",
+ "storyId": "core-chatcomposer--with-streaming",
+ "dims": []
+ },
{
"component": "DropdownMenu",
"storyId": "core-dropdownmenu--alignment-end",
diff --git a/apps/storybook/rtl-audit/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index c85e486ba6..71f1be626e 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -227,10 +227,20 @@
"apps/storybook/stories/ChatComposer.stories.tsx": "sha256:355778a847934f9af02adf3b42846089ade03ee37d935c2a30d32fba3e3cd291",
"packages/core/src/Chat/ChatComposer.tsx": "sha256:aa955ff0f59901285eadf7de209f78530d0f8deb0ef162f6baa4e9faa3661880",
"packages/core/src/Chat/ChatComposerInput.tsx": "sha256:19a9ed5be57e083a270f20d0348d2719c493d94fc270169ce91b43fe0bab13d4",
- "packages/core/src/Chat/ChatSendButton.tsx": "sha256:0e4948ab7b94b456da37d04cefc2473f893b79d12cde954a7b8923085923a2be",
+ "packages/core/src/Chat/ChatSendButton.tsx": "sha256:e966e7fe3b0fc24678a0db4f230b903f47f66b133baf9cad8e3d0ccfa9517612",
"packages/core/src/Chat/index.ts": "sha256:1e1883f9baa0b9661fefe855a7df6db2a0d0e69118734b3d309543a6c5518b46"
}
},
+ {
+ "component": "core/ChatSendButton",
+ "reason": "ChatSendButton composes one centered square Button and adds no inline-axis layout or positioning. Its upward send arrow and stop mark both express block-axis actions and must remain unchanged in RTL; the shared Button uses logical padding and centered icon-only geometry. The component owns no left/right glyph, inline ordering, horizontal scrolling or dragging, side-placed overlay, or directional keyboard behavior. The dedicated small-size audit stories are excluded only from stable visual baselines: they remain routed to the ChatSendButton a11y owner, while this source-hashed N/A record and the browser evidence's LTR/RTL coarse-hit matrix cover their direction-neutral geometry.",
+ "evidence": {
+ "apps/storybook/stories/ChatComposer.stories.tsx": "sha256:355778a847934f9af02adf3b42846089ade03ee37d935c2a30d32fba3e3cd291",
+ "apps/storybook/stories/ChatSendButtonAudit.stories.tsx": "sha256:8a72613f67ffebdb1e5624b3acc53ed5bb2a752457a312664ea5b8d834020862",
+ "packages/core/src/Chat/ChatSendButton.tsx": "sha256:e966e7fe3b0fc24678a0db4f230b903f47f66b133baf9cad8e3d0ccfa9517612",
+ "packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"
+ }
+ },
{
"component": "core/ChatDictationButton",
"reason": "ChatDictationButton is a symmetric inline-flex icon control. Its microphone glyph and five centered equalizer bars are direction-neutral; the component owns no inline-axis placement, ordering, directional glyph, horizontal scrolling or dragging, overlay placement, or horizontal keyboard behavior.",
diff --git a/apps/storybook/stories/ChatSendButtonAudit.stories.tsx b/apps/storybook/stories/ChatSendButtonAudit.stories.tsx
new file mode 100644
index 0000000000..7216387801
--- /dev/null
+++ b/apps/storybook/stories/ChatSendButtonAudit.stories.tsx
@@ -0,0 +1,45 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatSendButtonAudit.stories.tsx
+ * @input Uses ChatSendButton with explicit small send and stop configurations
+ * @output Checked-in single-subject fixtures for the component audit browser lane
+ * @position Browser evidence fixtures for appearance-only size coverage that does
+ * not belong in the shared Button semantic-state inventory
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {ChatSendButton} from '@astryxdesign/core/Chat';
+
+const meta = {
+ title: 'a11y/ChatSendButton audit',
+ component: ChatSendButton,
+ tags: ['no-visual'],
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Single-subject small-size fixtures for exact-head screenshot evidence. They are excluded only from stable visual baselines; the ChatSendButton a11y owner scans both stories, while the verified RTL N/A record and coarse LTR/RTL matrix cover directionality.',
+ },
+ },
+ },
+} satisfies Meta<typeof ChatSendButton>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+export const ChatSendSmall: Story = {
+ args: {
+ isDisabled: false,
+ onSend: () => {},
+ size: 'sm',
+ },
+};
+
+export const ChatSendStopSmall: Story = {
+ args: {
+ isStopShown: true,
+ onStop: () => {},
+ size: 'sm',
+ },
+};
diff --git a/packages/core/src/Chat/ChatSendButton.doc.mjs b/packages/core/src/Chat/ChatSendButton.doc.mjs
index 5e90b254ab..7c1460d973 100644
--- a/packages/core/src/Chat/ChatSendButton.doc.mjs
+++ b/packages/core/src/Chat/ChatSendButton.doc.mjs
@@ -69,6 +69,38 @@ export const docs = {
description: 'StyleX styles for layout customization (margins, positioning, sizing). Must be a stylex.create() value: not an inline style object like style={{}}.',
},
],
+ usage: {
+ description: 'Use ChatSendButton as ChatComposer’s send control when the action should switch between sending and stopping. Inside ChatComposer it reads readiness, streaming state, and action callbacks from context; standalone usage supplies those values explicitly.',
+ bestPractices: [
+ {
+ guidance: true,
+ description: 'Place ChatSendButton inside ChatComposer when its readiness and send or stop lifecycle should follow composer context.',
+ },
+ {
+ guidance: true,
+ description: 'For standalone use, provide the state and matching onSend or onStop callback explicitly.',
+ },
+ {
+ guidance: true,
+ description: 'Keep the translated Send or Stop accessible name intact when supplying custom icon artwork; the icon is decorative and must not be the only name source.',
+ },
+ {
+ guidance: false,
+ description: 'Do not render the stop state without a working onStop callback from props or ChatComposer context.',
+ },
+ {
+ guidance: false,
+ description: 'Do not expect isDisabled to disable the stop action; it applies only to the send state.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'Action button',
+ required: true,
+ description: 'Circular icon-only Button that exposes the translated Send or Stop name and carries the chat-send-button theme target.',
+ },
+ ],
+ },
};
export const docsZh = {
diff --git a/packages/core/src/Chat/ChatSendButton.spec.md b/packages/core/src/Chat/ChatSendButton.spec.md
new file mode 100644
index 0000000000..240cccdce7
--- /dev/null
+++ b/packages/core/src/Chat/ChatSendButton.spec.md
@@ -0,0 +1,227 @@
+---
+schema_version: 3
+template_version: 6
+kind: component
+id: component:ChatSendButton
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, theming, accessibility, testing]
+verified_by:
+ [
+ packages/core/src/Chat/ChatSendButton.test.tsx,
+ packages/core/src/Chat/__tests__/ChatSendButton.a11y.chromium.spec.ts,
+ packages/core/src/theme/themingTargets.test.ts,
+ apps/storybook/stories/ChatComposer.stories.tsx,
+ apps/storybook/stories/ChatSendButtonAudit.stories.tsx,
+ apps/storybook/rtl-audit/verified-not-applicable.json,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:icon-resolution-and-component-slots,
+ architecture:component-theming-surface,
+ architecture:interaction-modality,
+ architecture:component-test-sufficiency,
+ architecture:knowledge-contracts,
+ ]
+contributing: []
+system_specs: [spec:AST-002, spec:AST-020, spec:AST-029, spec:AST-032]
+---
+
+# ChatSendButton component contract
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | The exported control selects send or stop presentation from props over ChatComposer context, accepts `sm` or `md`, supports icon overrides, and extends the rendered Button with supported Button DOM, event, styling, and ref inputs. |
+| Behavior | Send is disabled from explicit or composer readiness, stop remains enabled, state-specific actions run before a composed generic click handler, and current send artwork resolves from an explicit override before the shared fallback. |
+| End-user impact | People receive a translated, state-appropriate send or stop action whose availability follows composer readiness. |
+| Builder impact | Builders can use the context defaults or supply every state and action explicitly for standalone composition. |
+| Compatibility/readiness | This draft records current or remediated observable behavior. It adds no public prop, default, target, or compatibility promise. Consumers that used `onClick` to replace sending migrate that logic to `onSend`; implementation of the AST-032 component-slot requirement remains pending. |
+| Review checks | Reject lost send/stop routing, consumer events that replace the state action, a disabled stop action, unlabelled icon-only output, dropped root inputs, or send fallback drift from the observed explicit-then-shared order. |
+| Governing rules | `spec:AST-032/FR2-FR3` (current requirement, implementation pending with its owner); `architecture:public-component-api/INV5-INV8`; `architecture:interaction-modality`; `architecture:component-test-sufficiency`; `spec:AST-020`; `spec:AST-029`. |
+
+This table is a review projection. The draft body below records checkable current
+or remediated behavior and does not create product policy.
+
+## Intent
+
+ChatSendButton is the compact action control used by ChatComposer. It translates
+composer readiness and streaming state into a shared Button while keeping action,
+icon, styling, and ref seams available for standalone composition.
+
+## Compatibility and migration
+
+- Released default preserved: no public default changes are made by this audit.
+- Compatibility class: patch-compatible event-composition repair plus observational documentation and evidence coverage.
+- Controlled/uncontrolled behavior: not applicable; explicit props take precedence over context-derived values.
+- Migration decision: consumers that previously used `onClick` to replace sending should move that logic to `onSend`, because the repaired component now runs the state action and then the accepted generic click.
+
+Consumer migration instructions belong in consumer docs and release notes.
+
+## Ownership boundary
+
+**Owns**
+
+- Selection of the send or stop state.
+- State-specific translated accessible names and Button variants.
+- Composer-context fallback for readiness and actions.
+- Send and stop icon selection at the component seam.
+- Composition of the state action with an accepted generic click handler.
+- The `chat-send-button` theme target and circular root treatment.
+
+**Does not own / non-goals**
+
+- ChatComposer value editing, submission lifecycle, streaming lifecycle, or placement.
+- Shared Button activation, focus, disabled semantics, hit area, or base styling.
+- Shared icon artwork or theme icon registration.
+- A public policy for whether `isStopShown` may appear without a stop action.
+
+## Public concepts
+
+Consumer syntax remains in `ChatSendButton.doc.mjs`. This inventory closes the
+observable semantic surface without duplicating the prop table.
+
+| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |
+| ------------ | -------------------------------------------------------------- | -------------------------------------------------------------------------------------- | ----------------------------------------- | ----------------------------------------------------------- | ----------------------------------- | -------------------------- | ------------------------------------------------------------------------------------------- |
+| Action state | send; stop | Selects the name, Button variant, icon role, disabled rule, and state action. | Every render. | Composer `isStopShown`, otherwise send. | `component:ChatSendButton` | Observed released surface | Values outside the boolean prop type are unsupported. |
+| Availability | enabled; disabled | Prevents send activation when content is not ready. Stop intentionally ignores it. | Disabled applies only to send. | Explicit `isDisabled`, otherwise inverse composer canSend. | component and ChatComposer context | Observed released surface | Values outside the boolean prop type are unsupported. |
+| Action | state callback; composer fallback; composed generic click | Runs the state action and then an accepted consumer click handler. | Enabled send and stop activation. | `onSend` or submit current value; `onStop` or context stop. | component, context, and caller | Remediated observable path | With no state callback or matching context action, only a supplied generic click can run. |
+| Send icon | explicit content; shared fallback | Selects artwork for the send state. | Send state. | `sendIcon`, then shared `arrowUp`. | component and caller | Observed released surface | Unsupported React content follows the shared Button rendering boundary. |
+| Stop icon | explicit content; shared fallback | Selects artwork for the stop state. | Stop state. | `stopIcon`, then shared `stop`. | component and caller | Observed released surface | Unsupported React content follows the shared Button rendering boundary. |
+| Size | `sm`; `md` | Selects the delegated Button size while preserving circular treatment. | Both states. | `md`. | `component:ChatSendButton` | Observed released surface | Values outside the public union are rejected by TypeScript. |
+| Root surface | ref; supported Button DOM/data/ARIA/events; style/class/xstyle | Extends and styles the rendered Button without replacing component-owned action logic. | Every render. | Omitted. | `architecture:public-component-api` | Remediated observable path | Unsupported BaseProps omissions remain unsupported; owned semantics win accidental clashes. |
+
+## Behavioral and layout contract
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |
+| FR1 | The send state MUST render a primary icon-only Button named by the send translation, and it MUST be disabled when explicit or context-derived readiness is false. | Current implementation, docs, tests, `spec:AST-020`, and shared Button behavior | Verified current behavior |
+| FR2 | The stop state MUST render a secondary icon-only Button named by the stop translation, remain enabled regardless of send readiness, and invoke explicit or context stop behavior. | Current implementation, docs, and tests | Verified current behavior; the missing-handler public boundary is owned by `component:ChatComposer/OQ4` |
+| FR3 | Send icon resolution currently prefers `sendIcon` and otherwise resolves shared `arrowUp`. `spec:AST-032/FR2-FR3` separately owns a current requirement to add a component-icon slot; its implementation remains pending with that owner. | Current implementation, docs, tests, and current owner requirement in `spec:AST-032` | Verified shipped two-stage behavior; the required AST-032 stage is not described as shipped |
+| FR4 | Stop icon resolution currently prefers `stopIcon` and otherwise resolves the shared `stop` icon. | Current implementation, docs, and tests | Verified shipped behavior; this draft does not invent a stop component slot |
+| FR5 | Explicit state, disabled, callback, icon, and size props MUST win over their context or component fallback. A generic accepted click handler MUST compose after the selected state action rather than replace it. | Current implementation after audit repair plus `architecture:public-component-api/INV5-INV7` and API contributor guide | Settled objective repair with red-before-green focused tests |
+| FR6 | Supported Button DOM, data, ARIA, className, style, xstyle, and ref inputs MUST reach or compose on the rendered Button while component-owned label, state, and activation behavior remain intact. | Current implementation plus `architecture:public-component-api/INV5-INV8` | Verify through source, type checks, and focused tests |
+| FR7 | The component MUST paint through the shared Button on the co-located `chat-send-button` target and preserve its circular component treatment. | Current implementation, Chat consumer docs, and `architecture:component-theming-surface` | Verified current target and composition |
+
+### Allowed variation
+
+- **AV1 — Context or standalone composition.** A builder may rely on ChatComposer
+ context or provide all state, action, and disabled values explicitly.
+- **AV2 — Artwork.** Explicit send and stop content and shared fallback artwork may
+ vary within the observed icon-resolution behavior.
+- **AV3 — Consumer styling.** Supported styling inputs may extend the Button while
+ component-owned state and activation behavior remain.
+
+### Representative states
+
+| State | Required invariant | Allowed variation |
+| ---------------------- | ----------------------------------------------------------------------------------- | ----------------------------------------------- |
+| Send, disabled | Primary translated send action is unavailable and does not run callbacks. | Icon source, size, theme, and consumer styling. |
+| Send, enabled | Primary translated send action runs explicit or context submission. | Icon source, size, theme, and consumer styling. |
+| Stop | Secondary translated stop action remains enabled and runs explicit or context stop. | Icon source, size, theme, and consumer styling. |
+| Explicit override | Explicit state, callback, icon, disabled value, and size win their fallback seams. | Context may still supply unspecified values. |
+| Composed generic click | State action and accepted generic click both run without one replacing the other. | Either handler may be absent. |
+
+### Transformation and precedence order
+
+- **ORD1 — Resolve state.** Explicit `isStopShown` wins, then composer context,
+ then the send state.
+- **ORD2 — Resolve action.** Explicit state callback wins its composer fallback.
+ The selected state action runs before the accepted generic click handler because
+ this component does not promise consumer cancellation of its state action.
+- **ORD3 — Resolve availability.** Stop remains enabled. Send uses explicit
+ `isDisabled`, then inverse composer readiness, then disabled outside context.
+- **ORD4 — Resolve artwork.** In send, explicit `sendIcon` wins, then shared
+ `arrowUp`; in stop, explicit `stopIcon` wins, then shared `stop`.
+- **ORD5 — Compose root.** Apply component-owned Button semantics and the
+ `chat-send-button` target while preserving supported consumer root inputs.
+
+### Performance and resources
+
+- **PR1 — Render-only projection.** The component adds no Effect, observer,
+ listener, timer, state mirror, or owned async lifecycle.
+
+## Accessibility contract
+
+- **AR1 — Native action semantics.** The delegated Button MUST own native button
+ activation, keyboard behavior, focus indication, and disabled semantics.
+- **AR2 — State-appropriate name.** The icon-only control MUST expose the current
+ translated send or stop label independently of icon artwork.
+- **AR3 — Disabled send behavior.** A disabled send action MUST not invoke either
+ the state action or a consumer click handler.
+- **AR4 — Modality parity.** Pointer and keyboard activation MUST traverse the same
+ state-action and composed-event path.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------------ | ------------------ |
+| Action button | Circular compact Button carrying the current send or stop action. | Current source and consumer docs; exact tuning stays in code | Primary/secondary action | FR1, FR2, FR7 |
+| Send artwork | Upward send glyph unless explicit content wins; AST-032 currently requires a component slot whose implementation is pending. | Current source and docs; current requirement in `spec:AST-032/FR2-FR3` | Action cue | FR3 |
+| Stop artwork | Shared stop glyph unless explicit content wins. | Current source and consumer docs | Action cue | FR4 |
+
+This observational draft does not select new dimensions, variants, icon artwork,
+color roles, or visual prominence.
+
+The Chat family consumer doc catalogs `chat-send-button`. Button owns the
+underlying painting and interaction-state styling; the component target is
+co-located on that painting element.
+
+## Family and system relationships
+
+- ChatComposer owns value, readiness, submission, stop lifecycle, and placement.
+- Button owns shared activation, focus, disabled semantics, hit area, and paint.
+- `architecture:public-component-api` owns BaseProps reachability, style/ref
+ composition, and deliberate event composition.
+- `architecture:icon-resolution-and-component-slots` owns the shared slot model;
+ `spec:AST-032/FR2-FR3` currently requires that stage in send resolution, and
+ its implementation remains pending with the owner. This draft does not describe
+ the unshipped stage as current behavior.
+- `architecture:component-theming-surface` owns the qualification and placement
+ of the co-located `chat-send-button` target.
+- `architecture:interaction-modality` and `spec:AST-020` own pointer, keyboard,
+ focus, and accessibility parity inherited through Button.
+- `architecture:component-test-sufficiency` owns public-seam regression coverage.
+- `spec:AST-029` owns this Night Watch observational backfill and prevents it from
+ settling new product meaning.
+
+## Verification map
+
+| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
+| ------------------------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------ |
+| FR1, FR2, AR1-AR4 | `ChatSendButton.test.tsx`, `ChatSendButton.a11y.chromium.spec.ts`, and `ChatComposer.test.tsx` | Enabled/disabled send, stop with and without handler, context stop, keyboard/pointer, light/dark interaction states | Label, disabled, native activation, state routing, or interaction paint drift fails focused or exact-head browser evidence. | `audit:ChatSendButton/accessibility` |
+| FR3 | `ChatSendButton.test.tsx`; current AST-032 owner requirement and its pending implementation | Explicit and shared-fallback send icon | Losing the observed two-stage precedence fails focused tests; the AST-032 owner verifies the required component-slot stage. | `audit:ChatSendButton/theming` |
+| FR4 | `ChatSendButton.test.tsx` | Explicit and fallback stop icon | Losing explicit precedence or registry resolution fails focused assertions. | `audit:ChatSendButton/behavior` |
+| FR5, FR6 | Red-before-green callback composition, ordering, size, root passthrough, disabled-click, and keyboard tests; types and lint | Send, stop, `sm`/`md`, ref/class/data/ARIA, Enter/Space | Consumer events replacing state actions, cancellation reordering, lost root inputs, or modality drift fails focused tests. | `audit:ChatSendButton/api` |
+| FR7 | `themingTargets.test.ts`, exact-head browser receipts, and source inspection | Send and stop themes | Target removal, movement off paint, or undocumented target drift fails tests or browser evidence. | `audit:ChatSendButton/theming` |
+| RTL relation | RTL shared-fixture route plus refreshed verified-N/A source receipts for ChatSendButton and ChatComposer | Send and stop | Directional artwork, physical positioning, or transform invalidates the checked-in receipts. | `audit:ChatSendButton/i18n-rtl` |
+| Browser matrix | `ChatSendButton.a11y.chromium.spec.ts` exact-head 10-sensor receipts | Light/dark send and stop rest/hover/focus/press, disabled rest/hover, `sm`/`md`, 320px coarse pointer, D7 contrast pairs | A stale build, decoy selector, missing state, changed disabled paint, absent interaction pixels, failed contrast, or geometry miss fails closed. | `audit:ChatSendButton/visual` |
+| Documentation and surface | Consumer docs, export checks, Storybook, and `check:knowledge` | Props, public subpath, states, draft contract | Missing or stale docs, exports, relationships, or required draft structure fails validation. | `audit:ChatSendButton/docs` |
+
+## Decision log
+
+None. This draft records current facts, one objective event-composition repair,
+and one current AST-032 requirement whose implementation remains pending with its
+owner. It introduces no component-local public API, default, compatibility,
+ownership, or subjective visual decision.
+
+## Open questions
+
+- **Cross-reference: stop without handler.** `component:ChatComposer/OQ4` owns
+ the unresolved policy for a visible stop action without an explicit or context
+ `onStop`. This component draft records and tests the current enabled no-op
+ branch without duplicating that question.
+
+## Content boundary
+
+This file does not duplicate consumer examples, audit scores, screenshots,
+eligibility data, or shared Button and icon-system rules. It links to their owners.
diff --git a/packages/core/src/Chat/ChatSendButton.test.tsx b/packages/core/src/Chat/ChatSendButton.test.tsx
index b4656069af..c6b6757555 100644
--- a/packages/core/src/Chat/ChatSendButton.test.tsx
+++ b/packages/core/src/Chat/ChatSendButton.test.tsx
@@ -4,12 +4,14 @@
* @file ChatSendButton.test.tsx
* @input Uses vitest, @testing-library/react, the global icon registry
* @output Unit tests for ChatSendButton
- * @position Colocated unit test; covers the send/stop labels and icons, the
- * disabled rules, click routing, and the ChatComposer context defaults
+ * @position Colocated unit test; covers labels and icons, disabled rules,
+ * composed consumer clicks, state-action routing, and ChatComposer defaults
*/
+import {createRef} from 'react';
import {describe, it, expect, vi, afterEach} from 'vitest';
import {render, screen, fireEvent} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import {ChatSendButton} from './ChatSendButton';
import {ChatComposer} from './ChatComposer';
import {Button} from '../Button';
@@ -38,6 +40,55 @@ describe('ChatSendButton', () => {
expect(screen.getByRole('button', {name: 'Send'})).toBeEnabled();
});
+ it('forwards ref, className, data, and ARIA inputs to the Button root', () => {
+ const ref = createRef<HTMLButtonElement>();
+ render(
+ <>
+ <ChatSendButton
+ ref={ref}
+ isDisabled={false}
+ onSend={() => {}}
+ className="consumer-class"
+ data-audit-root="forwarded"
+ aria-describedby="send-help"
+ />
+ <span id="send-help">Sends the current message</span>
+ </>,
+ );
+ const button = screen.getByRole('button', {name: 'Send'});
+ expect(ref.current).toBe(button);
+ expect(button).toHaveClass('consumer-class');
+ expect(button).toHaveAttribute('data-audit-root', 'forwarded');
+ expect(button).toHaveAccessibleDescription('Sends the current message');
+ });
+
+ it('reflects both supported Button sizes', () => {
+ render(
+ <>
+ <ChatSendButton
+ data-testid="send-small"
+ isDisabled={false}
+ onSend={() => {}}
+ size="sm"
+ />
+ <ChatSendButton
+ data-testid="send-medium"
+ isDisabled={false}
+ onSend={() => {}}
+ size="md"
+ />
+ </>,
+ );
+ expect(screen.getByTestId('send-small')).toHaveAttribute(
+ 'data-size',
+ 'sm',
+ );
+ expect(screen.getByTestId('send-medium')).toHaveAttribute(
+ 'data-size',
+ 'md',
+ );
+ });
+
it('calls onSend when clicked', () => {
const onSend = vi.fn();
render(<ChatSendButton isDisabled={false} onSend={onSend} />);
@@ -45,13 +96,53 @@ describe('ChatSendButton', () => {
expect(onSend).toHaveBeenCalledTimes(1);
});
- it('swallows the click while disabled', () => {
+ it('composes the consumer onClick with onSend', () => {
+ const onClick = vi.fn();
+ const onSend = vi.fn();
+ render(
+ <ChatSendButton isDisabled={false} onClick={onClick} onSend={onSend} />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Send'}));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(onSend).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs onSend exactly once before a consumer click prevents default', () => {
+ const order: string[] = [];
+ const onSend = vi.fn(() => order.push('send'));
+ const onClick = vi.fn(event => {
+ order.push('click');
+ event.preventDefault();
+ });
+ render(
+ <ChatSendButton isDisabled={false} onClick={onClick} onSend={onSend} />,
+ );
+ fireEvent.click(screen.getByRole('button', {name: 'Send'}));
+ expect(order).toEqual(['send', 'click']);
+ expect(onSend).toHaveBeenCalledTimes(1);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('supports native Enter and Space activation', async () => {
+ const user = userEvent.setup();
+ const onSend = vi.fn();
+ render(<ChatSendButton isDisabled={false} onSend={onSend} />);
+ const button = screen.getByRole('button', {name: 'Send'});
+ button.focus();
+ await user.keyboard('{Enter}');
+ await user.keyboard(' ');
+ expect(onSend).toHaveBeenCalledTimes(2);
+ });
+
+ it('swallows both state and consumer clicks while disabled', () => {
// isDisabled already defaults true here (no composer context), so this
// pins the click routing through a disabled Button, not the prop.
const onSend = vi.fn();
- render(<ChatSendButton onSend={onSend} />);
+ const onClick = vi.fn();
+ render(<ChatSendButton onClick={onClick} onSend={onSend} />);
fireEvent.click(screen.getByRole('button', {name: 'Send'}));
expect(onSend).not.toHaveBeenCalled();
+ expect(onClick).not.toHaveBeenCalled();
});
it('styles the send state as a primary button', () => {
@@ -133,6 +224,38 @@ describe('ChatSendButton', () => {
expect(onSend).not.toHaveBeenCalled();
});
+ it('composes the consumer onClick with onStop', () => {
+ const onClick = vi.fn();
+ const onStop = vi.fn();
+ render(<ChatSendButton isStopShown onClick={onClick} onStop={onStop} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Stop'}));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(onStop).toHaveBeenCalledTimes(1);
+ });
+
+ it('runs onStop exactly once before a consumer click prevents default', () => {
+ const order: string[] = [];
+ const onStop = vi.fn(() => order.push('stop'));
+ const onClick = vi.fn(event => {
+ order.push('click');
+ event.preventDefault();
+ });
+ render(<ChatSendButton isStopShown onClick={onClick} onStop={onStop} />);
+ fireEvent.click(screen.getByRole('button', {name: 'Stop'}));
+ expect(order).toEqual(['stop', 'click']);
+ expect(onStop).toHaveBeenCalledTimes(1);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it('remains an enabled no-op without onStop while generic onClick still runs', () => {
+ const onClick = vi.fn();
+ render(<ChatSendButton isStopShown onClick={onClick} />);
+ const stop = screen.getByRole('button', {name: 'Stop'});
+ expect(stop).toBeEnabled();
+ fireEvent.click(stop);
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
it('resolves its default icon from the registry stop entry', () => {
registerIcons({
stop: (
diff --git a/packages/core/src/Chat/ChatSendButton.tsx b/packages/core/src/Chat/ChatSendButton.tsx
index a0e317df1a..53a7705d1b 100644
--- a/packages/core/src/Chat/ChatSendButton.tsx
+++ b/packages/core/src/Chat/ChatSendButton.tsx
@@ -10,7 +10,8 @@
*
* Reads composer state from ChatComposerContext by default so it "just
* works" inside ChatComposer. All context-derived values can be
- * overridden via props for standalone usage.
+ * overridden via props for standalone usage. Accepted `onClick` handlers
+ * compose after the selected send or stop action.
*
* States:
* - **Send** — accent/primary, arrowUp icon, disabled when nothing to send.
@@ -24,7 +25,7 @@ import {useIcon} from '../Icon';
import {useChatComposerContext} from './ChatContext';
import type {BaseProps} from '../BaseProps';
-import {mergeProps} from '../utils';
+import {composeEventHandlers, mergeProps} from '../utils';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
@@ -85,6 +86,7 @@ export function ChatSendButton(props: ChatSendButtonProps): ReactNode {
isDisabled = !(context?.canSend ?? false),
onSend,
onStop = context?.onStop,
+ onClick,
sendIcon,
stopIcon,
size = 'md',
@@ -116,7 +118,7 @@ export function ChatSendButton(props: ChatSendButtonProps): ReactNode {
}
isIconOnly
isDisabled={!isStopShown && isDisabled}
- onClick={isStopShown ? onStop : handleSend}
+ onClick={composeEventHandlers(isStopShown ? onStop : handleSend, onClick)}
{...rest}
{...mergeProps(themeProps('chat-send-button'), {className}, style)}
xstyle={[styles.root, xstyle]}
diff --git a/packages/core/src/Chat/__tests__/ChatSendButton.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/ChatSendButton.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..c147dd8d7e
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatSendButton.a11y.chromium.spec.ts
@@ -0,0 +1,1522 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatSendButton.a11y.chromium.spec.ts
+ * @input Exact-head Storybook build plus checked-in ChatSendButton audit fixtures
+ * @output Chromium PNGs, 10-sensor receipts, D7 contrast pairs, coarse hit pairs,
+ * and a fail-closed manifest
+ * @position Real-browser evidence for the ChatSendButton component 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 Browser,
+ type BrowserContext,
+ type Locator,
+ type Page,
+} from '@playwright/test';
+// @ts-expect-error -- pngjs ships no declarations; runtime support is pinned.
+import {PNG} from 'pngjs';
+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/chat-send-button-audit-evidence');
+const NARROW_STORY = 'core-chatcomposer--disabled-streaming-narrow';
+const SUBJECT = '.astryx-chat-send-button';
+
+// A stale prior run must never fill a missing receipt. Run this file serially
+// without retries, and clear its output once before the exact-head matrix starts.
+test.describe.configure({mode: 'serial', retries: 0});
+
+type Mode = 'light' | 'dark';
+type Direction = 'ltr' | 'rtl';
+type Interaction = 'rest' | 'hover' | 'focus-visible' | 'pressed';
+type State = 'send' | 'disabled-send' | 'stop';
+type Size = 'sm' | 'md';
+type Rgba = {r: number; g: number; b: number; a: number};
+
+interface ContrastPair {
+ part: 'icon' | 'focus-indicator' | 'boundary';
+ meaningful: boolean;
+ foreground: string;
+ backdrop: string;
+ resolvedBackdrop: string;
+ ratio: number | null;
+ threshold: number | null;
+ exception: string | null;
+ passed: boolean;
+}
+
+interface Fixture {
+ key: string;
+ storyId: string;
+ name: 'Send' | 'Stop';
+ state: State;
+ size: Size;
+ disabled: boolean;
+}
+
+const FIXTURES: Record<string, Fixture> = {
+ sendMd: {
+ key: 'send-md',
+ storyId: 'a11y-button-pattern--chat-send',
+ name: 'Send',
+ state: 'send',
+ size: 'md',
+ disabled: false,
+ },
+ disabledMd: {
+ key: 'send-disabled-md',
+ storyId: 'a11y-button-pattern--chat-send-disabled',
+ name: 'Send',
+ state: 'disabled-send',
+ size: 'md',
+ disabled: true,
+ },
+ stopMd: {
+ key: 'stop-md',
+ storyId: 'a11y-button-pattern--chat-send-stop',
+ name: 'Stop',
+ state: 'stop',
+ size: 'md',
+ disabled: false,
+ },
+ sendSm: {
+ key: 'send-sm',
+ storyId: 'a11y-chatsendbutton-audit--chat-send-small',
+ name: 'Send',
+ state: 'send',
+ size: 'sm',
+ disabled: false,
+ },
+ stopSm: {
+ key: 'stop-sm',
+ storyId: 'a11y-chatsendbutton-audit--chat-send-stop-small',
+ name: 'Stop',
+ state: 'stop',
+ size: 'sm',
+ disabled: false,
+ },
+};
+
+interface Shot {
+ file: string;
+ sha256: string;
+ width: number;
+ height: number;
+ distinctColors: number;
+ nonBlank: boolean;
+}
+
+interface Receipt {
+ frame: string;
+ passed: boolean;
+ failures: string[];
+ build: {expected: string; checkout: string; storybook: string};
+ story: {id: string; expectedName: string};
+ theme: {requested: 'neutral'; observed: string | null};
+ mode: {
+ requested: Mode;
+ observed: string | null;
+ colorScheme: string;
+ surfaceBackground: string;
+ surfaceLuminanceClass: 'light' | 'dark' | 'unknown';
+ };
+ direction: {requested: Direction; observed: string};
+ viewport: {width: number; height: number};
+ devicePixelRatio: number;
+ media: {
+ reducedMotion: boolean;
+ forcedColors: boolean;
+ coarsePointer: boolean;
+ hoverCapable: boolean;
+ touchPoints: number;
+ };
+ semantics: {
+ role: string | null;
+ accessibleName: string | null;
+ disabled: boolean;
+ size: string | null;
+ variant: string | null;
+ };
+ geometry: {
+ selectorCount: number;
+ visibleCount: number;
+ width: number;
+ height: number;
+ circular: boolean;
+ };
+ interaction: {
+ requested: Interaction;
+ matchesHover: boolean;
+ matchesFocusVisible: boolean;
+ matchesActive: boolean;
+ cursor: string;
+ color: string;
+ backgroundColor: string;
+ backgroundImage: string;
+ opacity: string;
+ transform: string;
+ outlineColor: string;
+ outlineOffset: string;
+ outlineStyle: string;
+ outlineWidth: string;
+ representation: string;
+ tokenSignaturePresent: boolean;
+ restSha256?: string;
+ changedPixels?: boolean;
+ };
+ contrastPairs: ContrastPair[];
+ sensors: Record<
+ | 'Build'
+ | 'Story'
+ | 'Theme'
+ | 'Color mode'
+ | 'Direction'
+ | 'Viewport/media'
+ | 'Rendered state'
+ | 'Subject geometry'
+ | 'Settled render'
+ | 'Image',
+ {expected: unknown; observed: unknown; passed: boolean}
+ >;
+ settled: {fontsReady: boolean; pageErrors: string[]; storyError: boolean};
+ image: Shot;
+}
+
+interface CoarseHitPair {
+ fixture: string;
+ size: Size;
+ state: 'send' | 'stop';
+ direction: Direction;
+ coarsePointer: boolean;
+ touchPoints: number;
+ selectorCount: number;
+ visibleCount: number;
+ target: {x: number; y: number; width: number; height: number};
+ hit: boolean;
+ centered: boolean;
+ passed: boolean;
+}
+
+let server: StaticServer;
+let head = '';
+let build = '';
+let browserVersion = 'unknown';
+const receipts: Receipt[] = [];
+const coarseHitPairs: CoarseHitPair[] = [];
+
+function pngShot(file: string, bytes: Buffer): Shot {
+ const png = PNG.sync.read(bytes);
+ const colors = new Set<string>();
+ for (let index = 0; index < png.data.length; index += 4) {
+ colors.add(
+ `${png.data[index]},${png.data[index + 1]},${png.data[index + 2]},${png.data[index + 3]}`,
+ );
+ }
+ return {
+ file,
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ width: png.width,
+ height: png.height,
+ distinctColors: colors.size,
+ nonBlank: colors.size > 1,
+ };
+}
+
+function parseRgb(value: string): Rgba | null {
+ const match = value.match(/rgba?\(([^)]+)\)/);
+ const channels = match?.[1].match(/[\d.]+/g)?.map(Number) ?? [];
+ if (channels.length < 3) {
+ return null;
+ }
+ return {r: channels[0], g: channels[1], b: channels[2], a: channels[3] ?? 1};
+}
+
+function composite(foreground: Rgba, background: Rgba): Rgba {
+ const alpha = foreground.a + background.a * (1 - foreground.a);
+ const channel = (front: number, back: number) =>
+ alpha === 0
+ ? 0
+ : (front * foreground.a + back * background.a * (1 - foreground.a)) /
+ alpha;
+ return {
+ r: channel(foreground.r, background.r),
+ g: channel(foreground.g, background.g),
+ b: channel(foreground.b, background.b),
+ a: alpha,
+ };
+}
+
+function luminance(color: Rgba): number {
+ const linear = [color.r, color.g, color.b].map(channel => {
+ const value = channel / 255;
+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
+}
+
+function ratio(
+ foreground: Rgba | null,
+ background: Rgba | null,
+): number | null {
+ if (foreground == null || background == null) {
+ return null;
+ }
+ const first = luminance(foreground);
+ const second = luminance(background);
+ return Number(
+ (
+ (Math.max(first, second) + 0.05) /
+ (Math.min(first, second) + 0.05)
+ ).toFixed(2),
+ );
+}
+
+function colorString(color: Rgba): string {
+ return `rgb(${Math.round(color.r)}, ${Math.round(color.g)}, ${Math.round(color.b)})`;
+}
+
+function sameColor(first: Rgba | null, second: Rgba | null): boolean {
+ return (
+ first != null &&
+ second != null &&
+ Math.abs(first.r - second.r) < 0.01 &&
+ Math.abs(first.g - second.g) < 0.01 &&
+ Math.abs(first.b - second.b) < 0.01 &&
+ Math.abs(first.a - second.a) < 0.001
+ );
+}
+
+function isIdentityTransform(transform: string): boolean {
+ if (transform === 'none') {
+ return true;
+ }
+ const values = transform
+ .slice(transform.indexOf('(') + 1, transform.lastIndexOf(')'))
+ .match(/-?[\d.]+/g)
+ ?.map(Number);
+ const close = (actual: number, expected: number) =>
+ Math.abs(actual - expected) < 0.001;
+ if (transform.startsWith('matrix3d(') && values?.length === 16) {
+ const expected = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+ return values.every((value, index) => close(value, expected[index]));
+ }
+ if (transform.startsWith('matrix(') && values?.length === 6) {
+ const expected = [1, 0, 0, 1, 0, 0];
+ return values.every((value, index) => close(value, expected[index]));
+ }
+ return false;
+}
+
+function isScale098(transform: string): boolean {
+ const values = transform
+ .slice(transform.indexOf('(') + 1, transform.lastIndexOf(')'))
+ .match(/-?[\d.]+/g)
+ ?.map(Number);
+ const close = (actual: number, expected: number) =>
+ Math.abs(actual - expected) < 0.001;
+ if (transform.startsWith('matrix3d(') && values?.length === 16) {
+ const expected = [0.98, 0, 0, 0, 0, 0.98, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
+ return values.every((value, index) => close(value, expected[index]));
+ }
+ if (transform.startsWith('matrix(') && values?.length === 6) {
+ const expected = [0.98, 0, 0, 0.98, 0, 0];
+ return values.every((value, index) => close(value, expected[index]));
+ }
+ return false;
+}
+
+function resolveBackdrop(
+ backgroundColor: string,
+ backgroundImage: string,
+ surfaceBackground: string,
+): {
+ color: Rgba | null;
+ css: string;
+ overlay: Rgba | null;
+} {
+ const base = parseRgb(backgroundColor);
+ const surface = parseRgb(surfaceBackground);
+ const resolvedBase =
+ base != null && base.a < 1 && surface != null
+ ? composite(base, surface)
+ : base;
+ const gradientColor = backgroundImage.match(/rgba?\([^)]+\)/)?.[0];
+ const overlay = gradientColor ? parseRgb(gradientColor) : null;
+ const color =
+ resolvedBase != null && overlay != null
+ ? composite(overlay, resolvedBase)
+ : resolvedBase;
+ return {
+ color,
+ css: color == null ? backgroundColor : colorString(color),
+ overlay,
+ };
+}
+
+function contrastPairs(
+ actual: Awaited<ReturnType<typeof readSensors>>,
+ fixture: Fixture,
+ interaction: Interaction,
+): ContrastPair[] {
+ const backdrop = resolveBackdrop(
+ actual.backgroundColor,
+ actual.backgroundImage,
+ actual.surfaceBackground,
+ );
+ const surface = parseRgb(actual.surfaceBackground);
+ const iconRatio = ratio(parseRgb(actual.color), backdrop.color);
+ const inactive = fixture.disabled;
+ const pairs: ContrastPair[] = [
+ {
+ part: 'icon',
+ meaningful: !inactive,
+ foreground: actual.color,
+ backdrop: `${actual.backgroundColor}; overlay ${actual.backgroundImage}`,
+ resolvedBackdrop: backdrop.css,
+ ratio: iconRatio,
+ threshold: inactive ? null : 3,
+ exception: inactive ? 'WCAG inactive-control exception' : null,
+ passed: inactive || (iconRatio != null && iconRatio >= 3),
+ },
+ {
+ part: 'boundary',
+ meaningful: false,
+ foreground: backdrop.css,
+ backdrop: actual.surfaceBackground,
+ resolvedBackdrop: actual.surfaceBackground,
+ ratio: ratio(backdrop.color, surface),
+ threshold: null,
+ exception:
+ 'Decorative boundary: the meaningful icon and accessible name identify the control.',
+ passed: true,
+ },
+ ];
+ if (interaction === 'focus-visible') {
+ const focusRatio = ratio(parseRgb(actual.outlineColor), surface);
+ pairs.push({
+ part: 'focus-indicator',
+ meaningful: true,
+ foreground: actual.outlineColor,
+ backdrop: actual.surfaceBackground,
+ resolvedBackdrop: actual.surfaceBackground,
+ ratio: focusRatio,
+ threshold: 3,
+ exception: null,
+ passed: focusRatio != null && focusRatio >= 3,
+ });
+ }
+ return pairs;
+}
+
+function storyUrl(
+ storyId: string,
+ mode: Mode,
+ direction: Direction = 'ltr',
+): string {
+ return (
+ `${server.origin}/iframe.html?id=${storyId}&viewMode=story` +
+ `&globals=colorMode:${mode};astryxTheme:neutral;direction:${direction}`
+ );
+}
+
+async function openFixture(
+ page: Page,
+ fixture: Fixture,
+ mode: Mode,
+ direction: Direction = 'ltr',
+): Promise<{target: Locator; errors: string[]}> {
+ const errors: string[] = [];
+ page.removeAllListeners('pageerror');
+ page.on('pageerror', error => errors.push(String(error)));
+ browserVersion = page.context().browser()?.version() ?? 'unknown';
+ await page.goto(storyUrl(fixture.storyId, mode, direction));
+ await page.locator(SUBJECT).first().waitFor();
+ await page.waitForFunction(
+ expected =>
+ document.documentElement.getAttribute('data-theme') === expected,
+ mode,
+ );
+ await holdMotionStill(page);
+ await page.evaluate(async () => {
+ await document.fonts.ready;
+ if (document.activeElement instanceof HTMLElement) {
+ document.activeElement.blur();
+ }
+ });
+ await page.mouse.move(0, 0);
+ return {target: page.locator(SUBJECT), errors};
+}
+
+async function settleStoryPlayAndBlur(page: Page): Promise<void> {
+ await page.waitForFunction(
+ () =>
+ document
+ .querySelector('[data-testid="disabled-streaming-fixture"]')
+ ?.getAttribute('data-stop-requests') === '1',
+ );
+ await page.evaluate(() => {
+ if (document.activeElement instanceof HTMLElement) {
+ document.activeElement.blur();
+ }
+ });
+ await page
+ .locator(SUBJECT)
+ .first()
+ .evaluate(element => {
+ if (element.matches(':focus-visible')) {
+ throw new Error(
+ 'ChatSendButton retained focus-visible after story play',
+ );
+ }
+ });
+}
+
+async function readSensors(page: Page, interaction: Interaction) {
+ return page.locator(SUBJECT).evaluateAll((elements, expected) => {
+ const visible = elements.filter(element => {
+ const style = getComputedStyle(element);
+ const box = element.getBoundingClientRect();
+ return (
+ box.width > 0 &&
+ box.height > 0 &&
+ style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ style.opacity !== '0'
+ );
+ });
+ const element = visible[0] as HTMLButtonElement | undefined;
+ const style = element ? getComputedStyle(element) : null;
+ const box = element?.getBoundingClientRect();
+ const radius = style ? Number.parseFloat(style.borderTopLeftRadius) : 0;
+ const parseRgb = (value: string) => {
+ const channels = value.match(/[\d.]+/g)?.map(Number) ?? [];
+ return channels.length >= 3
+ ? {r: channels[0], g: channels[1], b: channels[2], a: channels[3] ?? 1}
+ : null;
+ };
+ const relativeLuminance = (color: {r: number; g: number; b: number}) => {
+ const linear = [color.r, color.g, color.b].map(channel => {
+ const value = channel / 255;
+ return value <= 0.04045
+ ? value / 12.92
+ : ((value + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
+ };
+ const resolveColorToken = (name: string) => {
+ if (element == null) {
+ return '';
+ }
+ const probe = document.createElement('span');
+ probe.style.backgroundColor = `var(${name})`;
+ probe.style.display = 'none';
+ element.appendChild(probe);
+ const resolved = getComputedStyle(probe).backgroundColor;
+ probe.remove();
+ return resolved;
+ };
+ const ancestors: Element[] = [];
+ for (
+ let current = element?.parentElement;
+ current != null;
+ current = current.parentElement
+ ) {
+ ancestors.push(current);
+ }
+ const surfaceBackground = [
+ ...ancestors,
+ document.querySelector('[data-astryx-theme]'),
+ document.querySelector('#storybook-root'),
+ document.body,
+ document.documentElement,
+ ]
+ .map(candidate =>
+ candidate == null ? null : getComputedStyle(candidate).backgroundColor,
+ )
+ .find(value => {
+ const color = value == null ? null : parseRgb(value);
+ return color != null && color.a > 0.99;
+ });
+ const surfaceColor = surfaceBackground ? parseRgb(surfaceBackground) : null;
+ const surfaceLuminanceClass: 'light' | 'dark' | 'unknown' =
+ surfaceColor == null
+ ? 'unknown'
+ : relativeLuminance(surfaceColor) > 0.5
+ ? 'light'
+ : 'dark';
+ return {
+ selectorCount: elements.length,
+ visibleCount: visible.length,
+ role:
+ element?.getAttribute('role') ?? element?.tagName.toLowerCase() ?? null,
+ accessibleName: element?.getAttribute('aria-label') ?? null,
+ disabled: element?.disabled ?? false,
+ size: element?.getAttribute('data-size') ?? null,
+ variant: element?.getAttribute('data-variant') ?? null,
+ direction: style?.direction ?? '',
+ width: box?.width ?? 0,
+ height: box?.height ?? 0,
+ circular:
+ box != null &&
+ Math.abs(box.width - box.height) < 0.5 &&
+ radius >= Math.min(box.width, box.height) / 2 - 0.5,
+ matchesHover: element?.matches(':hover') ?? false,
+ matchesFocusVisible: element?.matches(':focus-visible') ?? false,
+ matchesActive: element?.matches(':active') ?? false,
+ cursor: style?.cursor ?? '',
+ color: style?.color ?? '',
+ backgroundColor: style?.backgroundColor ?? '',
+ backgroundImage: style?.backgroundImage ?? '',
+ hoverOverlayToken: resolveColorToken('--color-overlay-hover'),
+ pressedOverlayToken: resolveColorToken('--color-overlay-pressed'),
+ opacity: style?.opacity ?? '',
+ transform: style?.transform ?? '',
+ outlineColor: style?.outlineColor ?? '',
+ outlineOffset: style?.outlineOffset ?? '',
+ outlineStyle: style?.outlineStyle ?? '',
+ outlineWidth: style?.outlineWidth ?? '',
+ mode: document.documentElement.getAttribute('data-theme'),
+ theme:
+ document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme') ?? null,
+ colorScheme: getComputedStyle(document.documentElement).colorScheme,
+ surfaceBackground: surfaceBackground ?? 'transparent',
+ surfaceLuminanceClass,
+ fontsReady: document.fonts.status === 'loaded',
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ forcedColors: matchMedia('(forced-colors: active)').matches,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ hoverCapable: matchMedia('(hover: hover)').matches,
+ touchPoints: navigator.maxTouchPoints,
+ storyError: [
+ ...document.querySelectorAll(
+ '.sb-errordisplay, [data-testid="story-error"]',
+ ),
+ ].some(node => {
+ const nodeStyle = getComputedStyle(node);
+ const nodeBox = node.getBoundingClientRect();
+ return (
+ nodeBox.width > 0 &&
+ nodeBox.height > 0 &&
+ nodeStyle.display !== 'none' &&
+ nodeStyle.visibility !== 'hidden' &&
+ nodeStyle.opacity !== '0'
+ );
+ }),
+ expectedInteraction: expected,
+ storyId: new URL(location.href).searchParams.get('id'),
+ };
+ }, interaction);
+}
+
+async function screenshotTarget(page: Page, frame: string): Promise<Shot> {
+ const target = page.locator(SUBJECT).first();
+ await page.locator('[data-a11y-activations] > p').evaluateAll(nodes => {
+ for (const node of nodes) {
+ (node as HTMLElement).style.visibility = 'hidden';
+ }
+ });
+ const box = await target.boundingBox();
+ if (box == null) {
+ throw new Error(`${frame}: ChatSendButton has no layout box`);
+ }
+ const padding = 8;
+ const viewport = page.viewportSize();
+ const clip = {
+ x: Math.max(0, box.x - padding),
+ y: Math.max(0, box.y - padding),
+ width: Math.min(
+ (viewport?.width ?? box.x + box.width) - Math.max(0, box.x - padding),
+ box.width + padding * 2,
+ ),
+ height: Math.min(
+ (viewport?.height ?? box.y + box.height) - Math.max(0, box.y - padding),
+ box.height + padding * 2,
+ ),
+ };
+ const bytes = await page.screenshot({animations: 'disabled', clip});
+ const file = `chat-send-button__${frame}.png`;
+ fs.writeFileSync(path.join(OUTPUT, file), bytes);
+ return pngShot(file, bytes);
+}
+
+async function writeContactSheet(page: Page): Promise<void> {
+ const cards = receipts
+ .map(receipt => {
+ const bytes = fs.readFileSync(path.join(OUTPUT, receipt.image.file));
+ const source = `data:image/png;base64,${bytes.toString('base64')}`;
+ return `<figure><img src="${source}" alt=""><figcaption>${receipt.frame}</figcaption></figure>`;
+ })
+ .join('');
+ await page.setViewportSize({width: 1200, height: 900});
+ await page.setContent(`<!doctype html>
+ <style>
+ html { color-scheme: light; background: #f3f4f6; }
+ body { margin: 20px; font: 12px/1.35 system-ui, sans-serif; color: #111827; }
+ h1 { margin: 0 0 16px; font-size: 20px; }
+ main { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; }
+ figure { margin: 0; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px; background: white; }
+ img { display: block; width: 100%; height: 96px; object-fit: contain; }
+ figcaption { margin-top: 8px; overflow-wrap: anywhere; }
+ </style>
+ <h1>ChatSendButton exact-head state evidence</h1>
+ <main>${cards}</main>`);
+ await page.locator('img').evaluateAll(async images => {
+ await Promise.all(
+ images.map(async image => {
+ const candidate = image as HTMLImageElement;
+ if (candidate.complete) {
+ return;
+ }
+ await new Promise<void>((resolve, reject) => {
+ candidate.addEventListener('load', () => resolve(), {once: true});
+ candidate.addEventListener(
+ 'error',
+ () => reject(new Error('image failed')),
+ {once: true},
+ );
+ });
+ }),
+ );
+ });
+ await page.screenshot({
+ path: path.join(OUTPUT, 'chat-send-button__contact-sheet.png'),
+ fullPage: true,
+ animations: 'disabled',
+ });
+}
+
+async function capture(
+ page: Page,
+ fixture: Fixture,
+ mode: Mode,
+ interaction: Interaction,
+ errors: string[],
+ options: {
+ direction?: Direction;
+ restSha256?: string;
+ expectChangedPixels?: boolean;
+ expectCoarse?: boolean;
+ expectedViewport?: {width: number; height: number};
+ frameSuffix?: string;
+ } = {},
+): Promise<Receipt> {
+ const direction = options.direction ?? 'ltr';
+ const frame = `${fixture.key}__${interaction}__${mode}${options.frameSuffix ?? ''}`;
+ const actual = await readSensors(page, interaction);
+ const image = await screenshotTarget(page, frame);
+ const viewport = await page.evaluate(() => ({
+ width: innerWidth,
+ height: innerHeight,
+ dpr: devicePixelRatio,
+ }));
+ const expectedViewport = options.expectedViewport ?? {
+ width: 1280,
+ height: 720,
+ };
+ const expectedCoarse = options.expectCoarse ?? false;
+ const changedPixels =
+ options.restSha256 == null
+ ? undefined
+ : image.sha256 !== options.restSha256;
+ const resolvedBackdrop = resolveBackdrop(
+ actual.backgroundColor,
+ actual.backgroundImage,
+ actual.surfaceBackground,
+ );
+ const overlayIsAlpha =
+ resolvedBackdrop.overlay != null &&
+ resolvedBackdrop.overlay.a > 0 &&
+ resolvedBackdrop.overlay.a < 1;
+ const hoverOverlayMatches = sameColor(
+ resolvedBackdrop.overlay,
+ parseRgb(actual.hoverOverlayToken),
+ );
+ const pressedOverlayMatches = sameColor(
+ resolvedBackdrop.overlay,
+ parseRgb(actual.pressedOverlayToken),
+ );
+ const representation = fixture.disabled
+ ? 'Disabled: native disabled, muted and non-interactive'
+ : interaction === 'hover'
+ ? 'Hovered: overlay style'
+ : interaction === 'focus-visible'
+ ? 'Focused: outline style'
+ : interaction === 'pressed'
+ ? 'Pressed: scale(0.98) plus pressed overlay'
+ : 'Rest: base tokens with no interaction';
+ const interactionStateIsExclusive =
+ interaction === 'rest'
+ ? !actual.matchesHover &&
+ !actual.matchesFocusVisible &&
+ !actual.matchesActive &&
+ actual.outlineStyle === 'none'
+ : interaction === 'hover'
+ ? actual.matchesHover &&
+ !actual.matchesFocusVisible &&
+ !actual.matchesActive &&
+ actual.outlineStyle === 'none'
+ : interaction === 'focus-visible'
+ ? !actual.matchesHover &&
+ actual.matchesFocusVisible &&
+ !actual.matchesActive &&
+ actual.outlineStyle !== 'none'
+ : actual.matchesHover &&
+ !actual.matchesFocusVisible &&
+ actual.matchesActive &&
+ actual.outlineStyle === 'none';
+ const tokenSignaturePresent = fixture.disabled
+ ? actual.disabled &&
+ actual.cursor === 'default' &&
+ Number.parseFloat(actual.opacity) < 1 &&
+ actual.backgroundImage === 'none' &&
+ isIdentityTransform(actual.transform) &&
+ interactionStateIsExclusive
+ : interaction === 'hover'
+ ? overlayIsAlpha && hoverOverlayMatches && interactionStateIsExclusive
+ : interaction === 'focus-visible'
+ ? actual.outlineStyle !== 'none' &&
+ Number.parseFloat(actual.outlineWidth) >= 2 &&
+ Number.parseFloat(actual.outlineOffset) >= 3 &&
+ interactionStateIsExclusive
+ : interaction === 'pressed'
+ ? overlayIsAlpha &&
+ pressedOverlayMatches &&
+ isScale098(actual.transform) &&
+ interactionStateIsExclusive
+ : interactionStateIsExclusive;
+ const renderedContrastPairs = contrastPairs(actual, fixture, interaction);
+ const failures: string[] = [];
+ const check = (condition: boolean, message: string) => {
+ if (!condition) {
+ failures.push(message);
+ }
+ };
+
+ check(
+ actual.selectorCount === 1,
+ 'expected exactly one ChatSendButton selector match',
+ );
+ check(
+ actual.visibleCount === 1,
+ 'expected exactly one visible ChatSendButton',
+ );
+ check(actual.storyId === fixture.storyId, 'Storybook story id drifted');
+ check(actual.role === 'button', 'native button role drifted');
+ check(actual.accessibleName === fixture.name, 'accessible name drifted');
+ check(actual.disabled === fixture.disabled, 'disabled state drifted');
+ check(actual.size === fixture.size, 'size attribute drifted');
+ check(
+ actual.variant === (fixture.state === 'stop' ? 'secondary' : 'primary'),
+ 'state variant drifted',
+ );
+ check(actual.direction === direction, 'computed direction drifted');
+ check(actual.circular, 'target is not circular');
+ check(
+ actual.width >= 24 && actual.height >= 24,
+ 'target does not contain a 24px square',
+ );
+ check(
+ image.nonBlank && image.width > 0 && image.height > 0,
+ 'PNG is blank or has no painted dimensions',
+ );
+ check(actual.mode === mode, 'color mode did not settle');
+ check(actual.theme === 'neutral', 'neutral theme did not settle');
+ check(
+ actual.surfaceLuminanceClass === mode,
+ 'rendered surface luminance does not match color mode',
+ );
+ check(actual.colorScheme.includes(mode), 'computed color-scheme drifted');
+ check(actual.fontsReady, 'fonts did not settle');
+ check(actual.reducedMotion, 'motion was not held still');
+ check(!actual.forcedColors, 'forced-colors unexpectedly active');
+ check(
+ actual.hoverCapable === !actual.coarsePointer,
+ 'pointer and hover media disagree',
+ );
+ check(actual.coarsePointer === expectedCoarse, 'pointer modality drifted');
+ check(
+ viewport.width === expectedViewport.width &&
+ viewport.height === expectedViewport.height,
+ 'viewport drifted',
+ );
+ check(viewport.dpr === 1, 'device pixel ratio drifted');
+ check(tokenSignaturePresent, `${representation} token signature is absent`);
+ for (const pair of renderedContrastPairs) {
+ check(pair.passed, `${pair.part} contrast pair failed`);
+ }
+ check(!actual.storyError, 'Storybook rendered an error surface');
+ check(errors.length === 0, 'page emitted an error');
+ if (options.expectCoarse) {
+ check(actual.touchPoints > 0, 'coarse-pointer context has no touch points');
+ }
+ check(
+ interactionStateIsExclusive,
+ `${interaction} state is not interaction-exclusive`,
+ );
+ if (options.expectChangedPixels != null) {
+ check(
+ changedPixels === options.expectChangedPixels,
+ options.expectChangedPixels
+ ? 'interaction pixels are identical to rest'
+ : 'disabled hover changed pixels',
+ );
+ }
+ if (fixture.disabled) {
+ check(actual.cursor === 'default', 'disabled cursor is not default');
+ check(
+ actual.backgroundImage === 'none',
+ 'disabled state paints a hover image',
+ );
+ check(Number.parseFloat(actual.opacity) < 1, 'disabled state is not muted');
+ check(
+ isIdentityTransform(actual.transform),
+ 'disabled state paints a non-identity transform',
+ );
+ }
+
+ const receipt: Receipt = {
+ frame,
+ passed: failures.length === 0,
+ failures,
+ build: {expected: head, checkout: head, storybook: build},
+ story: {id: fixture.storyId, expectedName: fixture.name},
+ theme: {requested: 'neutral', observed: actual.theme},
+ mode: {
+ requested: mode,
+ observed: actual.mode,
+ colorScheme: actual.colorScheme,
+ surfaceBackground: actual.surfaceBackground,
+ surfaceLuminanceClass: actual.surfaceLuminanceClass,
+ },
+ direction: {requested: direction, observed: actual.direction},
+ viewport: {width: viewport.width, height: viewport.height},
+ devicePixelRatio: viewport.dpr,
+ media: {
+ reducedMotion: actual.reducedMotion,
+ forcedColors: actual.forcedColors,
+ coarsePointer: actual.coarsePointer,
+ hoverCapable: actual.hoverCapable,
+ touchPoints: actual.touchPoints,
+ },
+ semantics: {
+ role: actual.role,
+ accessibleName: actual.accessibleName,
+ disabled: actual.disabled,
+ size: actual.size,
+ variant: actual.variant,
+ },
+ geometry: {
+ selectorCount: actual.selectorCount,
+ visibleCount: actual.visibleCount,
+ width: actual.width,
+ height: actual.height,
+ circular: actual.circular,
+ },
+ interaction: {
+ requested: interaction,
+ matchesHover: actual.matchesHover,
+ matchesFocusVisible: actual.matchesFocusVisible,
+ matchesActive: actual.matchesActive,
+ cursor: actual.cursor,
+ color: actual.color,
+ backgroundColor: actual.backgroundColor,
+ backgroundImage: actual.backgroundImage,
+ opacity: actual.opacity,
+ transform: actual.transform,
+ outlineColor: actual.outlineColor,
+ outlineOffset: actual.outlineOffset,
+ outlineStyle: actual.outlineStyle,
+ outlineWidth: actual.outlineWidth,
+ representation,
+ tokenSignaturePresent,
+ restSha256: options.restSha256,
+ changedPixels,
+ },
+ contrastPairs: renderedContrastPairs,
+ sensors: {
+ Build: {
+ expected: {headSha: head},
+ observed: {checkoutSha: head, storybookSha: build},
+ passed: build === head,
+ },
+ Story: {
+ expected: {id: fixture.storyId, accessibleName: fixture.name},
+ observed: {id: actual.storyId, accessibleName: actual.accessibleName},
+ passed:
+ actual.storyId === fixture.storyId &&
+ actual.accessibleName === fixture.name,
+ },
+ Theme: {
+ expected: 'neutral',
+ observed: actual.theme,
+ passed: actual.theme === 'neutral',
+ },
+ 'Color mode': {
+ expected: {
+ global: mode,
+ colorScheme: mode,
+ surfaceLuminanceClass: mode,
+ },
+ observed: {
+ global: actual.mode,
+ colorScheme: actual.colorScheme,
+ surfaceBackground: actual.surfaceBackground,
+ surfaceLuminanceClass: actual.surfaceLuminanceClass,
+ },
+ passed:
+ actual.mode === mode &&
+ actual.colorScheme.includes(mode) &&
+ actual.surfaceLuminanceClass === mode,
+ },
+ Direction: {
+ expected: direction,
+ observed: actual.direction,
+ passed: actual.direction === direction,
+ },
+ 'Viewport/media': {
+ expected: {
+ viewport: expectedViewport,
+ devicePixelRatio: 1,
+ forcedColors: false,
+ reducedMotion: true,
+ coarsePointer: expectedCoarse,
+ hoverCapable: !expectedCoarse,
+ },
+ observed: {
+ viewport: {width: viewport.width, height: viewport.height},
+ devicePixelRatio: viewport.dpr,
+ forcedColors: actual.forcedColors,
+ reducedMotion: actual.reducedMotion,
+ coarsePointer: actual.coarsePointer,
+ hoverCapable: actual.hoverCapable,
+ touchPoints: actual.touchPoints,
+ },
+ passed:
+ viewport.width === expectedViewport.width &&
+ viewport.height === expectedViewport.height &&
+ viewport.dpr === 1 &&
+ !actual.forcedColors &&
+ actual.reducedMotion &&
+ actual.coarsePointer === expectedCoarse &&
+ actual.hoverCapable === !expectedCoarse &&
+ (!expectedCoarse || actual.touchPoints > 0),
+ },
+ 'Rendered state': {
+ expected: {
+ role: 'button',
+ accessibleName: fixture.name,
+ disabled: fixture.disabled,
+ size: fixture.size,
+ variant: fixture.state === 'stop' ? 'secondary' : 'primary',
+ interaction,
+ stateSignature: {
+ hover: interaction === 'hover' || interaction === 'pressed',
+ focusVisible: interaction === 'focus-visible',
+ active: interaction === 'pressed',
+ outline: interaction === 'focus-visible' ? 'visible' : 'none',
+ },
+ representation,
+ },
+ observed: {
+ role: actual.role,
+ accessibleName: actual.accessibleName,
+ disabled: actual.disabled,
+ size: actual.size,
+ variant: actual.variant,
+ interaction,
+ stateSignature: {
+ hover: actual.matchesHover,
+ focusVisible: actual.matchesFocusVisible,
+ active: actual.matchesActive,
+ outline: actual.outlineStyle,
+ },
+ representation,
+ tokenSignaturePresent,
+ contrastPairs: renderedContrastPairs,
+ changedPixels,
+ },
+ passed:
+ actual.role === 'button' &&
+ actual.accessibleName === fixture.name &&
+ actual.disabled === fixture.disabled &&
+ actual.size === fixture.size &&
+ actual.variant ===
+ (fixture.state === 'stop' ? 'secondary' : 'primary') &&
+ interactionStateIsExclusive &&
+ tokenSignaturePresent &&
+ renderedContrastPairs.every(pair => pair.passed) &&
+ (options.expectChangedPixels == null ||
+ changedPixels === options.expectChangedPixels),
+ },
+ 'Subject geometry': {
+ expected: {
+ selectorCount: 1,
+ visibleCount: 1,
+ nonZero: true,
+ circular: true,
+ contains24pxSquare: true,
+ },
+ observed: {
+ selectorCount: actual.selectorCount,
+ visibleCount: actual.visibleCount,
+ width: actual.width,
+ height: actual.height,
+ circular: actual.circular,
+ },
+ passed:
+ actual.selectorCount === 1 &&
+ actual.visibleCount === 1 &&
+ actual.width >= 24 &&
+ actual.height >= 24 &&
+ actual.circular,
+ },
+ 'Settled render': {
+ expected: {
+ fontsReady: true,
+ reducedMotion: true,
+ storyError: false,
+ pageErrors: 0,
+ },
+ observed: {
+ fontsReady: actual.fontsReady,
+ reducedMotion: actual.reducedMotion,
+ storyError: actual.storyError,
+ pageErrors: errors,
+ },
+ passed:
+ actual.fontsReady &&
+ actual.reducedMotion &&
+ !actual.storyError &&
+ errors.length === 0,
+ },
+ Image: {
+ expected: {path: frame, nonBlankHash: true, nonZeroPixels: true},
+ observed: image,
+ passed:
+ image.sha256.length === 64 &&
+ image.width > 0 &&
+ image.height > 0 &&
+ image.nonBlank,
+ },
+ },
+ settled: {
+ fontsReady: actual.fontsReady,
+ pageErrors: [...errors],
+ storyError: actual.storyError,
+ },
+ image,
+ };
+ receipts.push(receipt);
+ expect(failures, `${frame}: fail-closed sensor receipt`).toEqual([]);
+ return receipt;
+}
+
+async function tabToSubject(page: Page): Promise<void> {
+ for (let press = 0; press < 8; press += 1) {
+ await page.keyboard.press('Tab');
+ if (
+ await page
+ .locator(SUBJECT)
+ .first()
+ .evaluate(element => document.activeElement === element)
+ ) {
+ return;
+ }
+ }
+ throw new Error('Tab did not reach ChatSendButton');
+}
+
+async function driveInteraction(
+ page: Page,
+ fixture: Fixture,
+ interaction: Exclude<Interaction, 'rest'>,
+): Promise<void> {
+ const target = page.locator(SUBJECT).first();
+ if (interaction === 'hover') {
+ await target.hover();
+ return;
+ }
+ if (interaction === 'focus-visible') {
+ await tabToSubject(page);
+ return;
+ }
+ const box = await target.boundingBox();
+ if (box == null) {
+ throw new Error(`${fixture.key}: target has no layout box`);
+ }
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await page.mouse.down();
+}
+
+async function coarseContext(browser: Browser): Promise<BrowserContext> {
+ return browser.newContext({
+ viewport: {width: 320, height: 640},
+ deviceScaleFactor: 1,
+ hasTouch: true,
+ isMobile: true,
+ });
+}
+
+async function readCoarseHitPair(
+ page: Page,
+ fixture: Fixture,
+ direction: Direction,
+): Promise<CoarseHitPair> {
+ await openFixture(page, fixture, 'light', direction);
+ return page.locator(SUBJECT).evaluateAll(
+ (elements, expected) => {
+ const visible = elements.filter(element => {
+ const box = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return (
+ box.width > 0 &&
+ box.height > 0 &&
+ style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ style.opacity !== '0'
+ );
+ });
+ const target = visible[0];
+ const box = target?.getBoundingClientRect() ?? new DOMRect();
+ const cx = box.x + box.width / 2;
+ const cy = box.y + box.height / 2;
+ const hit = document.elementFromPoint(cx, cy);
+ const hitTarget =
+ target != null && (hit === target || target.contains(hit));
+ const targetCenter = target?.getBoundingClientRect();
+ const centered =
+ targetCenter != null &&
+ Math.abs(targetCenter.x + targetCenter.width / 2 - cx) < 0.5 &&
+ Math.abs(targetCenter.y + targetCenter.height / 2 - cy) < 0.5;
+ const coarsePointer = matchMedia('(pointer: coarse)').matches;
+ const touchPoints = navigator.maxTouchPoints;
+ const passed =
+ elements.length === 1 &&
+ visible.length === 1 &&
+ box.width >= 24 &&
+ box.height >= 24 &&
+ coarsePointer &&
+ touchPoints > 0 &&
+ hitTarget &&
+ centered;
+ return {
+ fixture: expected.key,
+ size: expected.size,
+ state: expected.state,
+ direction: expected.direction,
+ coarsePointer,
+ touchPoints,
+ selectorCount: elements.length,
+ visibleCount: visible.length,
+ target: {x: box.x, y: box.y, width: box.width, height: box.height},
+ hit: hitTarget,
+ centered,
+ passed,
+ };
+ },
+ {
+ key: fixture.key,
+ size: fixture.size,
+ state: fixture.state as 'send' | 'stop',
+ direction,
+ },
+ );
+}
+
+test.beforeAll(async () => {
+ head = execFileSync('git', ['rev-parse', 'HEAD'], {encoding: 'utf8'}).trim();
+ const dirtyTracked = execFileSync(
+ 'git',
+ ['status', '--porcelain', '--untracked-files=no'],
+ {encoding: 'utf8'},
+ ).trim();
+ const dirtyEvidenceFiles = execFileSync(
+ 'git',
+ [
+ 'status',
+ '--porcelain',
+ '--untracked-files=all',
+ '--',
+ 'apps/storybook/stories/ChatSendButtonAudit.stories.tsx',
+ 'packages/core/src/Chat/__tests__/ChatSendButton.a11y.chromium.spec.ts',
+ ],
+ {encoding: 'utf8'},
+ ).trim();
+ const dirty = [dirtyTracked, dirtyEvidenceFiles].filter(Boolean).join('\n');
+ if (dirty !== '') {
+ throw new Error(
+ `browser evidence requires a clean committed source set: ${dirty}`,
+ );
+ }
+ if (process.env.ASTRYX_HEAD_SHA && process.env.ASTRYX_HEAD_SHA !== head) {
+ throw new Error('PR head differs from the checked out source');
+ }
+ fs.rmSync(OUTPUT, {recursive: true, force: true});
+ fs.mkdirSync(OUTPUT, {recursive: true});
+ server = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+ const stamp = await fetch(`${server.origin}/astryx-build-sha.txt`);
+ if (!stamp.ok) {
+ throw new Error('Storybook build is missing its source stamp');
+ }
+ build = (await stamp.text()).trim();
+ if (build !== head) {
+ throw new Error('Storybook bytes differ from the PR head');
+ }
+});
+
+test.afterAll(async () => {
+ if (!head || !build) {
+ await server?.close();
+ return;
+ }
+ const manifestPath = path.join(OUTPUT, 'manifest.json');
+ const contactSheetFile = 'chat-send-button__contact-sheet.png';
+ const contactSheetPath = path.join(OUTPUT, contactSheetFile);
+ const contactSheet = fs.existsSync(contactSheetPath)
+ ? pngShot(contactSheetFile, fs.readFileSync(contactSheetPath))
+ : null;
+ const mergedFrames = [...receipts];
+ const mergedCoarseHitPairs = [...coarseHitPairs];
+ const d7ContrastPairs = mergedFrames.flatMap(frame =>
+ frame.contrastPairs.map(pair => ({frame: frame.frame, ...pair})),
+ );
+ const expectedFrames: string[] = [];
+ for (const mode of ['light', 'dark'] as const) {
+ for (const fixture of [FIXTURES.sendMd, FIXTURES.stopMd]) {
+ for (const interaction of [
+ 'rest',
+ 'hover',
+ 'focus-visible',
+ 'pressed',
+ ] as const) {
+ expectedFrames.push(`${fixture.key}__${interaction}__${mode}`);
+ }
+ }
+ expectedFrames.push(
+ `${FIXTURES.disabledMd.key}__rest__${mode}`,
+ `${FIXTURES.disabledMd.key}__hover__${mode}`,
+ `${FIXTURES.sendSm.key}__rest__${mode}`,
+ `${FIXTURES.stopSm.key}__rest__${mode}`,
+ `stop-md-narrow-coarse__rest__${mode}__320px-coarse`,
+ );
+ }
+ const expectedPairs = [
+ FIXTURES.sendSm,
+ FIXTURES.sendMd,
+ FIXTURES.stopSm,
+ FIXTURES.stopMd,
+ ].flatMap(fixture =>
+ (['ltr', 'rtl'] as const).map(direction => `${fixture.key}:${direction}`),
+ );
+ const matrixFailures = [
+ ...(contactSheet?.nonBlank ? [] : ['missing or blank contact sheet']),
+ ...expectedFrames
+ .filter(frame => !mergedFrames.some(receipt => receipt.frame === frame))
+ .map(frame => `missing frame: ${frame}`),
+ ...mergedFrames
+ .filter(receipt => !receipt.passed)
+ .map(receipt => `failed frame: ${receipt.frame}`),
+ ...expectedPairs
+ .filter(
+ pair =>
+ !mergedCoarseHitPairs.some(
+ receipt => `${receipt.fixture}:${receipt.direction}` === pair,
+ ),
+ )
+ .map(pair => `missing coarse hit pair: ${pair}`),
+ ...mergedCoarseHitPairs
+ .filter(pair => !pair.passed)
+ .map(pair => `failed coarse hit pair: ${pair.fixture}:${pair.direction}`),
+ ...d7ContrastPairs
+ .filter(pair => !pair.passed)
+ .map(pair => `failed D7 contrast pair: ${pair.frame}/${pair.part}`),
+ ...(['light', 'dark'] as const).flatMap(mode =>
+ (['send', 'stop'] as const).flatMap(state => {
+ const small = mergedFrames.find(
+ frame => frame.frame === `${state}-sm__rest__${mode}`,
+ );
+ const medium = mergedFrames.find(
+ frame => frame.frame === `${state}-md__rest__${mode}`,
+ );
+ return small != null &&
+ medium != null &&
+ medium.geometry.width > small.geometry.width &&
+ medium.geometry.height > small.geometry.height
+ ? []
+ : [`size geometry did not increase: ${state}/${mode}`];
+ }),
+ ),
+ ];
+ fs.writeFileSync(
+ manifestPath,
+ `${JSON.stringify(
+ {
+ version: 1,
+ component: 'core/ChatSendButton',
+ headSha: head,
+ storybookSha: build,
+ browser: browserVersion,
+ failClosed: true,
+ matrixComplete: matrixFailures.length === 0,
+ matrixFailures,
+ sensorCount: 10,
+ requiredSensors: [
+ 'Build',
+ 'Story',
+ 'Theme',
+ 'Color mode',
+ 'Direction',
+ 'Viewport/media',
+ 'Rendered state',
+ 'Subject geometry',
+ 'Settled render',
+ 'Image',
+ ],
+ visualEvidence: {
+ requiredPair: false,
+ reason:
+ 'The runtime fix changes event composition only and has no rendering delta, so Q12 requires exact-head state evidence rather than a before/after pixel pair.',
+ contactSheet,
+ },
+ notApplicable: {
+ loading: 'ChatSendButton exposes no loading state.',
+ status: 'ChatSendButton exposes no status-message state.',
+ selected: 'ChatSendButton is an action, not a selectable control.',
+ empty:
+ 'The icon-only action has no empty-content state; its translated name is always present.',
+ overflow:
+ 'The icon-only circular target contains no variable text content that can overflow.',
+ },
+ stateVisualConformance: {
+ enabledSendMd: ['rest', 'hover', 'focus-visible', 'pressed'],
+ disabledSendMd: ['rest', 'hover-no-paint'],
+ stopMd: ['rest', 'hover', 'focus-visible', 'pressed'],
+ sendSm: ['rest'],
+ stopSm: ['rest'],
+ colorModes: ['light', 'dark'],
+ },
+ frames: mergedFrames,
+ d7ContrastPairs,
+ coarseHitPairs: mergedCoarseHitPairs,
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ await server?.close();
+ expect(matrixFailures, 'complete exact-head evidence matrix').toEqual([]);
+});
+
+for (const mode of ['light', 'dark'] as const) {
+ test(`captures the ${mode} interaction, disabled, and size matrix`, async ({
+ page,
+ }) => {
+ for (const fixture of [FIXTURES.sendMd, FIXTURES.stopMd]) {
+ const {errors: restErrors} = await openFixture(page, fixture, mode);
+ const rest = await capture(page, fixture, mode, 'rest', restErrors);
+
+ for (const interaction of [
+ 'hover',
+ 'focus-visible',
+ 'pressed',
+ ] as const) {
+ const {errors} = await openFixture(page, fixture, mode);
+ await driveInteraction(page, fixture, interaction);
+ await capture(page, fixture, mode, interaction, errors, {
+ restSha256: rest.image.sha256,
+ expectChangedPixels: true,
+ });
+ if (interaction === 'pressed') {
+ await page.mouse.up();
+ }
+ }
+ }
+
+ const disabled = FIXTURES.disabledMd;
+ const {errors: disabledRestErrors} = await openFixture(
+ page,
+ disabled,
+ mode,
+ );
+ const disabledRest = await capture(
+ page,
+ disabled,
+ mode,
+ 'rest',
+ disabledRestErrors,
+ );
+ const {errors: disabledHoverErrors} = await openFixture(
+ page,
+ disabled,
+ mode,
+ );
+ await page.locator(SUBJECT).hover({force: true});
+ await capture(page, disabled, mode, 'hover', disabledHoverErrors, {
+ restSha256: disabledRest.image.sha256,
+ expectChangedPixels: false,
+ });
+
+ for (const fixture of [FIXTURES.sendSm, FIXTURES.stopSm]) {
+ const {errors} = await openFixture(page, fixture, mode);
+ await capture(page, fixture, mode, 'rest', errors);
+ }
+ });
+}
+
+test('captures 320px coarse-pointer evidence from DisabledStreamingNarrow', async ({
+ browser,
+}) => {
+ const context = await coarseContext(browser);
+ const page = await context.newPage();
+ const fixture: Fixture = {
+ ...FIXTURES.stopMd,
+ key: 'stop-md-narrow-coarse',
+ storyId: NARROW_STORY,
+ };
+ for (const mode of ['light', 'dark'] as const) {
+ const {errors} = await openFixture(page, fixture, mode);
+ await settleStoryPlayAndBlur(page);
+ await capture(page, fixture, mode, 'rest', errors, {
+ expectCoarse: true,
+ expectedViewport: {width: 320, height: 640},
+ frameSuffix: '__320px-coarse',
+ });
+ }
+ await context.close();
+});
+
+test('records the complete coarse hit-target matrix', async ({browser}) => {
+ const context = await coarseContext(browser);
+ const page = await context.newPage();
+ for (const fixture of [
+ FIXTURES.sendSm,
+ FIXTURES.sendMd,
+ FIXTURES.stopSm,
+ FIXTURES.stopMd,
+ ]) {
+ for (const direction of ['ltr', 'rtl'] as const) {
+ const pair = await readCoarseHitPair(page, fixture, direction);
+ coarseHitPairs.push(pair);
+ expect(pair.passed, `${fixture.key}/${direction}: coarse hit pair`).toBe(
+ true,
+ );
+ }
+ }
+ await writeContactSheet(page);
+ await context.close();
+});