Skip to content

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

TypeScript

[Component Audit] ChatMessageMetadata: remove empty metadata separators (#6637)

Cindy Zhang9dbb6c1271e8
diff --git a/.changeset/chat-metadata-empty-slots.md b/.changeset/chat-metadata-empty-slots.md
new file mode 100644
index 0000000000..18d1d14679
--- /dev/null
+++ b/.changeset/chat-metadata-empty-slots.md
@@ -0,0 +1,11 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Omit empty ChatMessageMetadata slots and their separators.
+
+Boolean and empty-string timestamp or footer values no longer leave a blank row
+or a stray dot. Numeric zero remains visible, and all delivery statuses keep
+their existing labels and icons.
+
+@cixzhang
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 35edbf8859..a8d5759499 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1016,6 +1016,34 @@ jobs:
retention-days: 30
if-no-files-found: ignore
+ # 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 evidence
+ if: github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatMessageMetadata:')
+ env:
+ ASTRYX_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ node .github/scripts/accessibility-audit.js \
+ --storybook-dir apps/storybook/dist \
+ --output chat-message-metadata-a11y-report.json \
+ --components ChatMessageMetadata \
+ --baseline .github/a11y-baseline.json \
+ --fail-on-new
+ pnpm exec playwright test \
+ packages/core/src/Chat/__tests__/ChatMessageMetadata.a11y.chromium.spec.ts \
+ --project chromium
+
+ - name: Upload ChatMessageMetadata audit evidence
+ if: always() && github.event_name == 'pull_request' && startsWith(github.event.pull_request.title, '[Component Audit] ChatMessageMetadata:')
+ uses: actions/upload-artifact@v7
+ with:
+ name: chat-message-metadata-audit-evidence-${{ needs.build-storybook.outputs.short_hash }}
+ path: |
+ chat-message-metadata-a11y-report.json
+ test-results/chat-message-metadata-audit-evidence/
+ retention-days: 30
+ if-no-files-found: ignore
+
# 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/verified-not-applicable.json b/apps/storybook/rtl-audit/verified-not-applicable.json
index b0449e9103..c85e486ba6 100644
--- a/apps/storybook/rtl-audit/verified-not-applicable.json
+++ b/apps/storybook/rtl-audit/verified-not-applicable.json
@@ -266,5 +266,9 @@
"packages/core/src/Chat/ChatMessageList.tsx": "sha256:9d7dc59f2fa33cc13175f1093b509aea4ff54a76b9ef83d576d55f6c4d0bc541",
"packages/core/src/Chat/index.ts": "sha256:0f4a9d3ee08b4fcd43698ad017460aad109c500d2411913f509506d2a27387bb"
}
+ },
+ {
+ "component": "core/ChatMessageMetadata",
+ "reason": "The metadata row owns no directional glyph, contextual directional separator, physical inline positioning, prev/next control order, horizontal scrolling, dragging, overlay, or arrow-key behavior. Sender-dependent row reversal uses CSS flex direction relative to the surrounding writing direction and is verified separately by matched LTR/RTL Chromium receipts. The RTL audit's D1, D2, D3, D5, and D6 detectors therefore have no applicable target for this component."
}
]
diff --git a/apps/storybook/stories/ChatMessageMetadata.stories.tsx b/apps/storybook/stories/ChatMessageMetadata.stories.tsx
new file mode 100644
index 0000000000..f2d341e8de
--- /dev/null
+++ b/apps/storybook/stories/ChatMessageMetadata.stories.tsx
@@ -0,0 +1,94 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatMessageMetadata.stories.tsx
+ * @input ChatMessageMetadata in message context with status and caller-owned slots
+ * @output Reusable status, empty-slot, composition, and overflow browser fixtures
+ * @position Component-owned Storybook evidence for ChatMessageMetadata
+ */
+
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ ChatMessage,
+ ChatMessageBubble,
+ ChatMessageMetadata,
+} from '@astryxdesign/core/Chat';
+import {Button} from '@astryxdesign/core/Button';
+
+const meta = {
+ title: 'Core/ChatMessageMetadata',
+ component: ChatMessageMetadata,
+ tags: ['autodocs'],
+} satisfies Meta<typeof ChatMessageMetadata>;
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+// Every case is a reusable composition, not a story per scalar or screenshot.
+export const States: Story = {
+ render: () => (
+ <div style={{display: 'grid', gap: 16, maxWidth: 640}}>
+ {(['sending', 'sent', 'delivered', 'read', 'error'] as const).map(
+ status => (
+ <section key={status} data-metadata-case={`status-${status}`}>
+ <ChatMessage sender="user">
+ <ChatMessageBubble
+ metadata={
+ <ChatMessageMetadata timestamp="10:30" status={status} />
+ }>
+ {status} message
+ </ChatMessageBubble>
+ </ChatMessage>
+ </section>
+ ),
+ )}
+ <section data-metadata-case="assistant-footer">
+ <ChatMessage sender="assistant">
+ <ChatMessageBubble>Reply</ChatMessageBubble>
+ <ChatMessageMetadata
+ timestamp="10:31"
+ footer={<Button label="Copy reply" onClick={() => {}} size="sm" />}
+ />
+ </ChatMessage>
+ </section>
+ <section data-metadata-case="empty-footer">
+ <ChatMessage sender="assistant">
+ <ChatMessageMetadata timestamp="10:32" footer={false} />
+ </ChatMessage>
+ </section>
+ <section data-metadata-case="empty-timestamp">
+ <ChatMessage sender="assistant">
+ <ChatMessageMetadata timestamp={false} footer="Model info" />
+ </ChatMessage>
+ </section>
+ <section data-metadata-case="empty-row" style={{minHeight: 24}}>
+ <ChatMessage sender="assistant">
+ <ChatMessageMetadata timestamp="" footer={false} />
+ </ChatMessage>
+ </section>
+ <section data-metadata-case="numeric-slots">
+ <ChatMessage sender="user">
+ <ChatMessageMetadata timestamp={0} footer={0} />
+ </ChatMessage>
+ </section>
+ <section data-metadata-case="standalone">
+ <ChatMessageMetadata timestamp="11:00" status="read" />
+ </section>
+ </div>
+ ),
+};
+
+export const NarrowOverflow: Story = {
+ render: () => (
+ <div
+ data-metadata-case="narrow-overflow"
+ style={{width: 320, maxWidth: '100%'}}>
+ <ChatMessage sender="assistant">
+ <ChatMessageMetadata
+ timestamp="10:32"
+ footer="A longer metadata description that can grow when translated into a different language"
+ status="delivered"
+ />
+ </ChatMessage>
+ </div>
+ ),
+};
diff --git a/packages/core/src/Chat/ChatMessageMetadata.doc.mjs b/packages/core/src/Chat/ChatMessageMetadata.doc.mjs
index 1ad0727f21..d19d8d436e 100644
--- a/packages/core/src/Chat/ChatMessageMetadata.doc.mjs
+++ b/packages/core/src/Chat/ChatMessageMetadata.doc.mjs
@@ -6,7 +6,8 @@ export const docs = {
name: 'ChatMessageMetadata',
subComponentOf: 'Chat',
displayName: 'Chat Message Metadata',
- description: 'Composable metadata row for chat messages. Renders timestamp, footer content, and delivery status in a single row. Direction reverses for user sender. Renders nothing if all props are empty.',
+ description:
+ 'Composable metadata row for chat messages. Renders timestamp, footer content, and delivery status in a single row. Direction reverses for user sender. Omits the row when both slots are omitted or non-rendering scalars and status is omitted.',
props: [
{
name: 'timestamp',
@@ -42,12 +43,64 @@ export const docs = {
description: 'Message delivery status. Shows icon + label.',
},
],
+ usage: {
+ description:
+ 'Place ChatMessageMetadata below a message or in the last ChatMessageBubble metadata slot to show a timestamp, footer content, and optional delivery status. Non-rendering scalar slots (booleans and empty strings) create no separator; numeric zero remains visible. Composite React content remains caller-owned.',
+ bestPractices: [
+ {
+ guidance: true,
+ description:
+ 'Put metadata in the last bubble metadata slot when the message uses bubbles, so it follows the bubble content.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Pass timestamp and footer content independently; separators are omitted for non-rendering scalar slots. Composite React nodes are used as supplied.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Do not supply footer actions without their own accessible names and interaction behavior; the metadata row does not own those controls.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Do not put the same metadata on both a bubble and its enclosing message.',
+ },
+ ],
+ anatomy: [
+ {
+ name: 'Metadata row',
+ required: true,
+ description: 'Sender-aware line containing the visible metadata items.',
+ },
+ {
+ name: 'Timestamp',
+ required: false,
+ description:
+ 'Caller-supplied time content at the start of the logical sequence.',
+ },
+ {
+ name: 'Footer',
+ required: false,
+ description:
+ 'Caller-supplied information or actions between time and status.',
+ },
+ {
+ name: 'Status',
+ required: false,
+ description:
+ 'Localized delivery icon and text when a status is supplied.',
+ },
+ ],
+ },
};
export const docsZh = {
name: 'ChatMessageMetadata',
displayName: 'Chat Message Metadata',
- description: '可组合的消息元数据行。渲染时间戳、页脚内容和发送状态。用户消息方向反转。',
+ description:
+ '可组合的消息元数据行。渲染时间戳、页脚内容和发送状态。用户消息方向反转。',
propDescriptions: {
timestamp: '时间戳内容,字符串或 Timestamp 组件。',
footer: '页脚内容:模型信息、反应按钮、复制按钮。',
@@ -58,7 +111,8 @@ export const docsZh = {
export const docsDense = {
name: 'ChatMessageMetadata',
displayName: 'Chat Message Metadata',
- description: 'composable metadata row; renders timestamp · footer · status; reverses for user sender',
+ description:
+ 'composable metadata row; renders timestamp · footer · status; reverses for user sender',
propDescriptions: {
timestamp: 'timestamp content; string or Timestamp',
footer: 'footer content; model info, reaction btns, copy btn',
diff --git a/packages/core/src/Chat/ChatMessageMetadata.spec.md b/packages/core/src/Chat/ChatMessageMetadata.spec.md
new file mode 100644
index 0000000000..497ee42a40
--- /dev/null
+++ b/packages/core/src/Chat/ChatMessageMetadata.spec.md
@@ -0,0 +1,220 @@
+---
+schema_version: 3
+template_version: 6
+kind: component
+id: component:ChatMessageMetadata
+authority: draft
+archive_reason: null
+superseded_by: null
+approved_by: null
+approved_at: null
+owners: [cixzhang]
+review_triggers: [public-api, behavior, layout, accessibility, theming, testing]
+verified_by:
+ [
+ packages/core/src/Chat/ChatMessageMetadata.test.tsx,
+ packages/core/src/Chat/__tests__/ChatMessageMetadata.a11y.chromium.spec.ts,
+ apps/storybook/stories/ChatMessageMetadata.stories.tsx,
+ packages/core/src/theme/themingTargets.test.ts,
+ ]
+modules: []
+families: []
+design_specs: []
+architecture:
+ [
+ architecture:public-component-api,
+ architecture:component-test-sufficiency,
+ architecture:component-theming-surface,
+ architecture:component-style-authoring,
+ architecture:react-component-runtime,
+ architecture:knowledge-contracts,
+ ]
+contributing: []
+system_specs: [spec:AST-029]
+---
+
+# ChatMessageMetadata component contract
+
+This is an observational draft of the existing Core chat metadata surface and
+its tested empty-scalar correction. It creates no new prop, status meaning,
+announcement guarantee, or visual policy. Current shared records govern their
+own scopes independently of this draft.
+
+## Contract at a glance
+
+| Area | Contract |
+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| Public contract | Optional `timestamp` and `footer` ReactNode slots, optional closed `status` union, root `BaseProps<HTMLDivElement>` and `ref`, exported through `./Chat`. |
+| Behavior | The row renders its present slots in timestamp, footer, status order, with a separator only between present slots; user sender reverses the flex row. Five delivery statuses have localized icon-and-text displays. |
+| End-user impact | Non-rendering scalar slot values no longer leave a standalone dot, a blank metadata row, or a separator without adjacent content. Visible numeric zero remains. |
+| Builder impact | No new inputs, defaults, or migration. Caller-supplied footer controls remain caller-owned. |
+| Compatibility/readiness | Patch-compatible scalar correction to a released `./Chat` subpath; draft pending exact-head observational verification and owner review. |
+| Review checks | Reject a lost visible zero, stranded separator, omitted translated status label, dropped root passthrough, or claim that a static DOM attribute proves an AT announcement. |
+| Governing rules | `architecture:public-component-api/INV1, INV3, INV5–INV9`; `architecture:component-test-sufficiency/INV1–INV7`; `spec:AST-029/FR2–FR5`. |
+
+The table is a review projection. Consumer syntax belongs in
+`ChatMessageMetadata.doc.mjs` and the Chat family consumer documentation.
+
+## Intent
+
+ChatMessageMetadata is the optional compact line below a chat message. It
+projects caller-owned timestamp/footer content and an optional delivery status
+inside the sender-aware Chat composition. It is not the message article, the
+bubble surface, the transcript, or the footer control owner.
+
+## Compatibility and migration
+
+- Released default preserved: yes. Core `0.6.3` exports `./Chat` with this
+ component, props, and status type.
+- Compatibility class: patch correction for non-rendering scalar ReactNode
+ values, preserving numeric `0` and the published props.
+- Controlled/uncontrolled behavior: not applicable; the component stores no
+ delivery state.
+- Migration decision: none. Existing callers need no new option.
+
+Consumer migration instructions, when needed, belong in release notes rather
+than this record.
+
+## Ownership boundary
+
+**Owns**
+
+- The optional metadata root, its `chat-message-metadata` painting target,
+ ref, neutral DOM passthrough, and composed styling inputs.
+- Presence checks and separators among timestamp, footer, and status.
+- Sender-relative row order from the nearest Chat message context, with an
+ assistant fallback outside that context.
+- Status-to-glyph and translated-caption selection and the local sending/error
+ paint path.
+
+**Does not own / non-goals**
+
+- Sender identity, article semantics, avatar, name, and body alignment:
+ `ChatMessage` owns these.
+- Bubble inset and placement: `ChatMessageBubble` owns these.
+- Footer action semantics, button focus, and callback behavior: the caller's
+ supplied content owns them.
+- Transcript scrolling, loading, or delivery-state transitions: the surrounding
+ composition owns these.
+- A new public rule for inspecting composite, lazy, or asynchronous ReactNode
+ values, or a screen-reader announcement-timing guarantee.
+
+## Public concepts
+
+| Concept | Closed values or states | Observed meaning | Availability | Default | Owner | Stability | Invalid-value behavior |
+| -------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------- | --------------------------------------------------- | ------------------------------------------- | ----------------------------------- | ------------- | ---------------------------------------------------------------------------------------------------- |
+| `timestamp` | Omitted or caller ReactNode | Optional first item, normally a time | Any composition | Omitted | Caller | Released | Null, booleans, and empty string do not render a scalar slot; `0` renders; non-scalars remain opaque |
+| `footer` | Omitted or caller ReactNode | Optional middle item such as model information or caller controls | Any composition | Omitted | Caller | Released | Same scalar treatment as timestamp |
+| `status` | `sending`, `sent`, `delivered`, `read`, `error`, omitted | Optional delivery caption and glyph | Any composition | Omitted | Component/caller input | Released | Closed type union; omitted contributes no item |
+| Sender context | `user`, `assistant`, `system`, absent | Selects user-reversed or other forward row order | Within `ChatMessage` or standalone | Assistant when absent | `ChatMessage` / local fallback | Observational | Non-user values share the forward path |
+| Root surface | `BaseProps<HTMLDivElement>`, `ref`, `xstyle`, `className`, `style` | Extends the metadata row when it exists | Slot passes scalar-presence check or status present | Absent for empty scalar slots and no status | `architecture:public-component-api` | Released | Non-scalar values remain opaque; target and consumer styles combine |
+
+## Behavioral and layout contract
+
+The following candidate invariants name their evidence. They are observations
+for review, not current product policy created by this draft.
+
+| ID | Candidate invariant | Basis | Draft review state |
+| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | ------------------ |
+| FR1 | The root appears when at least one slot passes the shared scalar-presence predicate or `status` is present. Non-scalar values are treated as present without inspecting their inner content. | Public ReactNode seam, shared `isRenderable` scalar utility, focused red/green and browser evidence | Verify correction |
+| FR2 | Accepted slot values render in timestamp, footer, status order with dots between values considered present; numeric `0` is visible in either slot, and non-scalar nodes remain opaque. | Shipped ordering, shared scalar utility, focused tests, light/dark browser cases | Verify correction |
+| FR3 | A `user` message reverses row direction; `assistant`, `system`, and absent context use the forward path. | Source, Chat context, sender and RTL browser fixtures | Verify observation |
+| FR4 | Status selects one of five registry icons and localized labels; failure uses the error text token, and sending has a CSS pulse suppressed under reduced motion. | Source, locale catalog, owned browser status matrix | Verify observation |
+| FR5 | The root merges the target, default StyleX output, and consumer `xstyle`, `className`, and `style`; accepted neutral DOM/ARIA inputs and `ref` reach that root. | Source, public API authority, existing passthrough test | Verify observation |
+| FR6 | A status item has a translated title and author-supplied `aria-label`, an icon and visible localized text. The row declares no live-region role or imperative announcement. | Source, DOM tests and axe fixtures; no real-AT timing claim | Verify observation |
+
+### Allowed variation
+
+- **AV1 - Slot content.** The caller decides the structure and semantics inside
+ timestamp and footer slots. This component does not inspect non-scalar nodes.
+- **AV2 - Theme.** Semantic colors, typography, and spacing resolve through the
+ active Theme; the root remains the public metadata painting target.
+- **AV3 - Context.** Standalone use takes the assistant ordering fallback.
+
+### Representative states
+
+| State | Observed result | Allowed variation |
+| --------------------------- | --------------------------------------------------------------------------- | -------------------------------------- |
+| Standalone timestamp | One root and one visible item | Caller content |
+| User or assistant message | Sender-relative row order | Text direction inherited from the page |
+| Timestamp + footer + status | Items separated according to scalar presence; composite nodes remain opaque | Caller footer content |
+| Each delivery status | Distinct localized caption and mapped icon | Active translation and theme tokens |
+| Non-rendering scalar slots | No stranded dot; no row when all items are empty | Composite nodes remain opaque |
+| Numeric `0` | Visible content, not an empty marker | Either slot |
+| Long footer at narrow width | Content reflows within its container | Caller text may wrap |
+
+### Transformation and precedence order
+
+- **ORD1 - Presence before separators.** Decide scalar presence with the shared
+ predicate while treating non-scalar caller nodes as opaque, then place
+ punctuation between values considered present. The status check remains
+ independent of the slot checks.
+- **ORD2 - Composition.** Resolve sender context, select flex order, and compose
+ component StyleX and theme target with consumer styling inputs on one root.
+
+### Performance and resources
+
+- **PR1 - Render derivation.** The component creates no local React state,
+ Effects, timers, observer, or event listeners. Its local animation is CSS and
+ suppressed for reduced motion.
+
+## Accessibility contract
+
+- **AR1 - Display semantics.** The metadata line does not add a button, focus
+ target, list role, or live region of its own. Interactive footer content retains
+ its own semantics and keyboard behavior.
+- **AR2 - Visible delivery state.** The status caption accompanies the glyph so
+ state identification does not rely on color or the icon alone.
+- **AR3 - Evidence boundary.** Browser-exposed markup and axe coverage do not
+ establish spoken output or announcement timing; any such future claim follows
+ `spec:AST-009` and its named AT evidence rule.
+
+## Design relationships
+
+| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |
+| ---------------- | ---------------------------------------------------------------- | -------------------------------------------- | -------------- | ------------------ |
+| Metadata row | Semantic supporting typography and sender-relative reading order | Local representation unsettled | Supporting | FR2–FR3 |
+| Delivery status | Registry glyph, caption, and semantic error token | Local prominence and motion choice unsettled | Supporting | FR4, AR2 |
+
+No current component-local ChatMessageMetadata design decision is introduced.
+The draft `design:motion` and `design:system-states` records are not adopted as
+current authority by this record.
+
+## Family and system relationships
+
+- There is no current `family:chat` product-authority record. `Chat.doc.mjs` is
+ consumer composition guidance, not a family contract.
+- `architecture:public-component-api` owns root export and passthrough;
+ `architecture:component-theming-surface` owns the public painting target;
+ `architecture:component-test-sufficiency` owns bounded evidence coverage.
+- `spec:AST-029` keeps the closed audit inventory and score outside this
+ component draft.
+
+## Verification map
+
+| Contract | Evidence | Representative states | Mutation or failure expectation | Audit section |
+| ------------ | ------------------------------------------------------ | ------------------------------------------- | ----------------------------------------------------------------- | ----------------------------------------- |
+| FR1–FR2 | `ChatMessageMetadata.test.tsx`; Chromium receipts | empty scalar, zero, timestamp/footer/status | A nullish-only guard reintroduces a stray separator or blank row | `audit:ChatMessageMetadata/behavior` |
+| FR3 | Storybook sender fixtures and Chromium RTL frames | user, assistant, standalone in LTR/RTL | Wrong relative ordering becomes visible | `audit:ChatMessageMetadata/rtl` |
+| FR4, AR2 | Status fixtures, locale catalog, Chromium/axe receipts | five statuses, light/dark, reduced motion | A dropped status label or failed theme paint is visible | `audit:ChatMessageMetadata/accessibility` |
+| FR5 | Existing passthrough test and theming-target guard | DOM/data/ARIA and styling | Root drops accepted caller inputs or target | `audit:ChatMessageMetadata/public-api` |
+| FR6, AR1–AR3 | Axe and browser semantic receipts | static status and caller button | Missing text/icon or falsely claimed AT timing remains detectable | `audit:ChatMessageMetadata/testing` |
+
+## Decision log
+
+None. This draft makes no new component-local product decision.
+
+## Open questions
+
+- **OQ1 - Should non-scalar ReactNode slots ever be normalized for emptiness?**
+ (`human-api`) Arrays, Fragments, lazy content, and promises remain opaque under
+ the existing scalar predicate; this audit does not consume or inspect them.
+- **OQ2 - Should standalone delivery-status changes be announced, and if so by
+ which owner?** (`human-api`) The current row is display-only. No spoken-timing
+ claim is made without a current owner and applicable AT evidence.
+
+## Content boundary
+
+This record does not store an audit score, screenshot manifest, CI transcript,
+consumer prop example, new public API, or shared visual policy. Those remain in
+the audit PR evidence, consumer docs, and their canonical owners.
diff --git a/packages/core/src/Chat/ChatMessageMetadata.test.tsx b/packages/core/src/Chat/ChatMessageMetadata.test.tsx
index 65f7fbad04..1874bde710 100644
--- a/packages/core/src/Chat/ChatMessageMetadata.test.tsx
+++ b/packages/core/src/Chat/ChatMessageMetadata.test.tsx
@@ -29,4 +29,38 @@ describe('ChatMessageMetadata', () => {
expect(root).toHaveAttribute('data-custom', 'x');
expect(root).toHaveAttribute('id', 'meta-1');
});
+
+ it('omits separators when a footer slot has no rendered content', () => {
+ render(
+ <ChatMessageMetadata
+ timestamp="10:32"
+ footer={false}
+ data-testid="meta"
+ />,
+ );
+ expect(screen.getByTestId('meta')).toHaveTextContent('10:32');
+ expect(screen.getByTestId('meta')).not.toHaveTextContent('·');
+ });
+
+ it('omits an empty timestamp and the row when both slots are empty', () => {
+ const {rerender} = render(
+ <ChatMessageMetadata
+ timestamp={false}
+ footer="Model info"
+ data-testid="meta"
+ />,
+ );
+ expect(screen.getByTestId('meta')).toHaveTextContent('Model info');
+ expect(screen.getByTestId('meta')).not.toHaveTextContent('·');
+
+ rerender(
+ <ChatMessageMetadata timestamp="" footer={false} data-testid="meta" />,
+ );
+ expect(screen.queryByTestId('meta')).not.toBeInTheDocument();
+ });
+
+ it('keeps numeric zero in both visible slots', () => {
+ render(<ChatMessageMetadata timestamp={0} footer={0} data-testid="meta" />);
+ expect(screen.getByTestId('meta')).toHaveTextContent('0·0');
+ });
});
diff --git a/packages/core/src/Chat/ChatMessageMetadata.tsx b/packages/core/src/Chat/ChatMessageMetadata.tsx
index 5f82d1f573..9531dd1add 100644
--- a/packages/core/src/Chat/ChatMessageMetadata.tsx
+++ b/packages/core/src/Chat/ChatMessageMetadata.tsx
@@ -4,12 +4,12 @@
/**
* @file ChatMessageMetadata.tsx
- * @input Uses React, StyleX, ChatContext, Icon, theme tokens
+ * @input Uses React, StyleX, ChatContext, Icon, theme tokens, and isRenderable
* @output Exports ChatMessageMetadata component
* @position Shared metadata row used by composing inside ChatMessage
*
- * Renders: <timestamp> · <footer> · <status>
- * Direction reverses for user sender.
+ * Renders timestamp, footer, and status values with separators determined by
+ * scalar presence. Direction reverses for user sender.
*/
import React, {type ReactNode} from 'react';
@@ -23,7 +23,7 @@ import {
import {useChatMessageContext} from './ChatContext';
import {Icon} from '../Icon';
import type {IconName} from '../Icon/globalIconRegistry';
-import {mergeProps} from '../utils';
+import {isRenderable, mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
@@ -97,7 +97,8 @@ export interface ChatMessageMetadataProps extends BaseProps<HTMLDivElement> {
* Composable metadata row for chat messages.
*
* Renders: timestamp · footer · status
- * Renders nothing if all props are null/undefined.
+ * Renders nothing when neither slot passes the scalar-presence check and no
+ * status is set. Composite React nodes remain caller-owned.
*
* @example
* ```
@@ -124,8 +125,9 @@ export function ChatMessageMetadata({
const statusConfig = status != null ? STATUS_CONFIG[status] : null;
const statusLabel = statusConfig != null ? t(statusConfig.i18nKey) : '';
- const hasContent =
- timestamp != null || footer != null || statusConfig != null;
+ const hasTimestamp = isRenderable(timestamp);
+ const hasFooter = isRenderable(footer);
+ const hasContent = hasTimestamp || hasFooter || statusConfig != null;
if (!hasContent) {
return null;
}
@@ -144,12 +146,10 @@ export function ChatMessageMetadata({
style,
)}
{...rest}>
- {timestamp != null && <span>{timestamp}</span>}
- {timestamp != null && (footer != null || statusConfig != null) && (
- <span>·</span>
- )}
- {footer != null && footer}
- {footer != null && statusConfig != null && <span>·</span>}
+ {hasTimestamp && <span>{timestamp}</span>}
+ {hasTimestamp && (hasFooter || statusConfig != null) && <span>·</span>}
+ {hasFooter && footer}
+ {hasFooter && statusConfig != null && <span>·</span>}
{statusConfig != null && (
<span
title={statusLabel}
diff --git a/packages/core/src/Chat/__tests__/ChatMessageMetadata.a11y.chromium.spec.ts b/packages/core/src/Chat/__tests__/ChatMessageMetadata.a11y.chromium.spec.ts
new file mode 100644
index 0000000000..0261ddcf20
--- /dev/null
+++ b/packages/core/src/Chat/__tests__/ChatMessageMetadata.a11y.chromium.spec.ts
@@ -0,0 +1,413 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file ChatMessageMetadata.a11y.chromium.spec.ts
+ * @input Exact-head Storybook build and component-owned metadata fixtures
+ * @output Chromium PNGs, semantic/paint sensor receipts, and a fail-closed manifest
+ * @position Browser evidence for the ChatMessageMetadata 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 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/chat-message-metadata-audit-evidence',
+);
+const STATES = 'core-chatmessagemetadata--states';
+const NARROW = 'core-chatmessagemetadata--narrow-overflow';
+const LABELS = {
+ sending: 'Sending',
+ sent: 'Sent',
+ delivered: 'Delivered',
+ read: 'Read',
+ error: 'Failed',
+} as const;
+
+interface Case {
+ name: string;
+ storyId: string;
+ rootCount: number;
+ text: string;
+ status?: keyof typeof LABELS;
+ button?: boolean;
+ sender?: 'user' | 'assistant';
+}
+
+// These expectations are fixture/source facts, never values copied from a page.
+const CASES: Case[] = [
+ ...Object.entries(LABELS).map(([status, label]) => ({
+ name: `status-${status}`,
+ storyId: STATES,
+ rootCount: 1,
+ text: `10:30·${label}`,
+ status: status as keyof typeof LABELS,
+ sender: 'user' as const,
+ })),
+ {
+ name: 'assistant-footer',
+ storyId: STATES,
+ rootCount: 1,
+ text: '10:31·Copy reply',
+ button: true,
+ sender: 'assistant',
+ },
+ {
+ name: 'empty-footer',
+ storyId: STATES,
+ rootCount: 1,
+ text: '10:32',
+ sender: 'assistant',
+ },
+ {
+ name: 'empty-timestamp',
+ storyId: STATES,
+ rootCount: 1,
+ text: 'Model info',
+ sender: 'assistant',
+ },
+ {
+ name: 'empty-row',
+ storyId: STATES,
+ rootCount: 0,
+ text: '',
+ sender: 'assistant',
+ },
+ {
+ name: 'numeric-slots',
+ storyId: STATES,
+ rootCount: 1,
+ text: '0·0',
+ sender: 'user',
+ },
+ {
+ name: 'standalone',
+ storyId: STATES,
+ rootCount: 1,
+ text: '11:00·Read',
+ status: 'read',
+ },
+ {
+ name: 'narrow-overflow',
+ storyId: NARROW,
+ rootCount: 1,
+ text: '10:32·A longer metadata description that can grow when translated into a different language·Delivered',
+ status: 'delivered',
+ sender: 'assistant',
+ },
+];
+
+let server: StaticServer;
+let head: string;
+let build: string;
+const frames: Record<string, unknown>[] = [];
+
+test.beforeAll(async () => {
+ head = execFileSync('git', ['rev-parse', 'HEAD'], {encoding: 'utf8'}).trim();
+ if (process.env.ASTRYX_HEAD_SHA && process.env.ASTRYX_HEAD_SHA !== head) {
+ throw new Error('PR head differs from the checked out source');
+ }
+ 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');
+ }
+ fs.mkdirSync(OUTPUT, {recursive: true});
+});
+
+test.afterAll(async () => {
+ const previous = fs.existsSync(path.join(OUTPUT, 'manifest.json'))
+ ? (JSON.parse(fs.readFileSync(path.join(OUTPUT, 'manifest.json'), 'utf8'))
+ .frames ?? [])
+ : [];
+ if (head && build) {
+ fs.writeFileSync(
+ path.join(OUTPUT, 'manifest.json'),
+ `${JSON.stringify(
+ {
+ version: 1,
+ component: 'core/ChatMessageMetadata',
+ headSha: head,
+ storybookSha: build,
+ frames: [...previous, ...frames].filter(
+ (frame, index, all) =>
+ all.findIndex(
+ other =>
+ other.state === frame.state &&
+ other.mode === frame.mode &&
+ other.direction === frame.direction,
+ ) === index,
+ ),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ }
+ await server?.close();
+});
+
+async function capture(
+ page: Page,
+ scenario: Case,
+ mode: 'light' | 'dark',
+ direction: 'ltr' | 'rtl',
+ options: {
+ viewport?: {width: number; height: number};
+ coarsePointer?: boolean;
+ state?: string;
+ } = {},
+) {
+ const viewport = options.viewport ?? {width: 1024, height: 768};
+ const state = options.state ?? scenario.name;
+ const errors: string[] = [];
+ const onError = (error: Error) => errors.push(String(error));
+ page.on('pageerror', onError);
+ await page.setViewportSize(viewport);
+ await page.goto(
+ `${server.origin}/iframe.html?id=${scenario.storyId}&viewMode=story&globals=colorMode:${mode};astryxTheme:neutral;direction:${direction}`,
+ );
+ const panel = page.locator(`[data-metadata-case="${scenario.name}"]`);
+ await panel.waitFor();
+ await page.waitForFunction(
+ expected =>
+ document.documentElement.getAttribute('data-theme') === expected,
+ mode,
+ );
+ await holdMotionStill(page);
+ await page.evaluate(async () => document.fonts.ready);
+ const roots = panel.locator('.astryx-chat-message-metadata');
+ const actual = await panel.evaluate((element, expected) => {
+ const root = element.querySelector('.astryx-chat-message-metadata');
+ const status = root?.querySelector('[title]');
+ const rect = element.getBoundingClientRect();
+ const rootStyle = root ? getComputedStyle(root) : null;
+ return {
+ rootCount: element.querySelectorAll('.astryx-chat-message-metadata')
+ .length,
+ text: (root?.textContent ?? '').replace(/\s+/g, ' ').trim(),
+ direction: rootStyle?.direction ?? getComputedStyle(element).direction,
+ color: rootStyle?.color ?? null,
+ fontSize: rootStyle?.fontSize ?? null,
+ statusColor: status ? getComputedStyle(status).color : null,
+ statusTitle: status?.getAttribute('title') ?? null,
+ statusLabel: status?.getAttribute('aria-label') ?? null,
+ buttonCount: element.querySelectorAll('button').length,
+ sender:
+ element.querySelector('article')?.getAttribute('data-sender') ?? null,
+ overflowFree: element.scrollWidth <= element.clientWidth + 1,
+ rootWidth: root?.getBoundingClientRect().width ?? null,
+ childX: root
+ ? [...root.children].map(child => child.getBoundingClientRect().x)
+ : [],
+ geometry: {x: rect.x, y: rect.y, width: rect.width, height: rect.height},
+ rootVisible: root
+ ? root.getBoundingClientRect().width > 0 &&
+ root.getBoundingClientRect().height > 0
+ : false,
+ storyError: [
+ ...document.querySelectorAll(
+ '.sb-errordisplay, [data-testid="story-error"]',
+ ),
+ ].some(node => {
+ const box = node.getBoundingClientRect();
+ const style = getComputedStyle(node);
+ return (
+ box.width > 0 &&
+ box.height > 0 &&
+ box.bottom > 0 &&
+ box.right > 0 &&
+ box.top < innerHeight &&
+ box.left < innerWidth &&
+ style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ style.opacity !== '0'
+ );
+ }),
+ mode: document.documentElement.getAttribute('data-theme'),
+ theme: document
+ .querySelector('[data-astryx-theme]')
+ ?.getAttribute('data-astryx-theme'),
+ colorScheme: getComputedStyle(document.documentElement).colorScheme,
+ fonts: document.fonts.status,
+ viewport: {width: innerWidth, height: innerHeight},
+ dpr: devicePixelRatio,
+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,
+ coarsePointer: matchMedia('(pointer: coarse)').matches,
+ horizontalOverflow: document.documentElement.scrollWidth > innerWidth + 1,
+ expectedSubject: expected,
+ };
+ }, scenario.name);
+ const expected = {
+ build: head,
+ storyId: scenario.storyId,
+ theme: 'neutral',
+ mode,
+ direction,
+ viewport,
+ coarsePointer: options.coarsePointer ?? false,
+ reducedMotion: true,
+ rootCount: scenario.rootCount,
+ text: scenario.text,
+ statusTitle: scenario.status ? LABELS[scenario.status] : null,
+ buttonCount: scenario.button ? 1 : 0,
+ sender: scenario.sender ?? null,
+ };
+ const failures: string[] = [];
+ const check = (ok: boolean, detail: string) => {
+ if (!ok) {
+ failures.push(detail);
+ }
+ };
+ check(actual.rootCount === expected.rootCount, 'metadata root count');
+ check(actual.text === expected.text, 'visible content and separators');
+ check(actual.direction === direction, 'computed direction');
+ if (scenario.name === 'status-read' || scenario.name === 'assistant-footer') {
+ const first = actual.childX[0];
+ const last = actual.childX[actual.childX.length - 1];
+ const goesRight =
+ scenario.sender === 'user' ? direction === 'rtl' : direction === 'ltr';
+ check(
+ first != null &&
+ last != null &&
+ (goesRight ? first < last : first > last),
+ 'sender-relative visual order',
+ );
+ }
+ check(actual.statusTitle === expected.statusTitle, 'translated status title');
+ check(actual.buttonCount === expected.buttonCount, 'footer button');
+ check(actual.sender === expected.sender, 'message sender');
+ check(
+ actual.theme === 'neutral' &&
+ actual.mode === mode &&
+ actual.colorScheme === mode,
+ 'resolved theme',
+ );
+ check(
+ actual.fonts === 'loaded' && actual.reducedMotion,
+ 'settled fonts and reduced motion',
+ );
+ check(
+ actual.viewport.width === viewport.width &&
+ actual.viewport.height === viewport.height &&
+ actual.coarsePointer === expected.coarsePointer,
+ 'viewport and pointer',
+ );
+ check(
+ actual.geometry.width > 0 &&
+ actual.geometry.height > 0 &&
+ !actual.storyError,
+ 'visible fixture with no Storybook error',
+ );
+ check(
+ actual.rootCount === 0 || actual.rootVisible,
+ 'visible metadata subject',
+ );
+ check(
+ actual.overflowFree && !actual.horizontalOverflow,
+ 'no horizontal overflow',
+ );
+ check(errors.length === 0, 'no page errors');
+ const file = `ChatMessageMetadata__${state}__neutral-${mode}__${direction}.png`;
+ const png = await panel.screenshot({animations: 'disabled'});
+ const image = {
+ file,
+ sha256: createHash('sha256').update(png).digest('hex'),
+ width: png.readUInt32BE(16),
+ height: png.readUInt32BE(20),
+ };
+ fs.writeFileSync(path.join(OUTPUT, file), png);
+ const receipt = {
+ expected,
+ observed: {...actual, build, storyId: scenario.storyId, pageErrors: errors},
+ browser: page.context().browser()?.version() ?? 'unknown',
+ image,
+ passed: failures.length === 0,
+ failures,
+ };
+ fs.writeFileSync(
+ path.join(OUTPUT, `${file}.sensors.json`),
+ `${JSON.stringify(receipt, null, 2)}\n`,
+ );
+ frames.push({
+ state,
+ mode,
+ direction,
+ receipt: `${file}.sensors.json`,
+ image,
+ passed: receipt.passed,
+ failures,
+ });
+ expect(await roots.count()).toBe(actual.rootCount);
+ page.off('pageerror', onError);
+ return failures.map(detail => `${state}/${mode}/${direction}: ${detail}`);
+}
+
+test('captures light and dark status, composition, empty, and overflow states', async ({
+ page,
+}) => {
+ const failures: string[] = [];
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ for (const mode of ['light', 'dark'] as const) {
+ for (const scenario of CASES) {
+ failures.push(...(await capture(page, scenario, mode, 'ltr')));
+ }
+ }
+ expect(failures).toEqual([]);
+});
+
+test('captures sender ordering in RTL', async ({page}) => {
+ const failures: string[] = [];
+ await page.emulateMedia({reducedMotion: 'reduce'});
+ for (const mode of ['light', 'dark'] as const) {
+ for (const scenario of CASES.filter(
+ item => item.name === 'status-read' || item.name === 'assistant-footer',
+ )) {
+ failures.push(...(await capture(page, scenario, mode, 'rtl')));
+ }
+ }
+ expect(failures).toEqual([]);
+});
+
+test('captures narrow touch reflow in both modes', async ({browser}) => {
+ const viewport = {width: 320, height: 640};
+ const context = await browser.newContext({
+ viewport,
+ deviceScaleFactor: 1,
+ hasTouch: true,
+ isMobile: true,
+ reducedMotion: 'reduce',
+ });
+ try {
+ const page = await context.newPage();
+ const scenario = CASES.find(item => item.name === 'narrow-overflow');
+ if (!scenario) {throw new Error('Narrow metadata fixture is missing');}
+ const failures: string[] = [];
+ for (const mode of ['light', 'dark'] as const) {
+ failures.push(
+ ...(await capture(page, scenario, mode, 'ltr', {
+ viewport,
+ coarsePointer: true,
+ state: 'narrow-touch',
+ })),
+ );
+ }
+ expect(failures).toEqual([]);
+ } finally {
+ await context.close();
+ }
+});