An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] ChatMessage: avoid empty message chrome (#6597)
Cindy Zhang550b88e3d395
diff --git a/.changeset/chatmessage-empty-slots.md b/.changeset/chatmessage-empty-slots.mdnew file mode 100644index 0000000000..fa34f75697--- /dev/null+++ b/.changeset/chatmessage-empty-slots.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] `ChatMessage` no longer leaves empty space for an avatar, name, or metadata that renders nothing. Booleans and empty strings create no slot, and any other slot content that renders nothing, such as an empty Fragment or a component that returns `null`, collapses its wrapper. A name that renders no text falls back to the translated sender label, while numeric values such as `0` still render.++@cixzhangdiff --git a/apps/storybook/rtl-audit/targets.json b/apps/storybook/rtl-audit/targets.jsonindex 444a70eae8..8e9166c5e6 100644--- a/apps/storybook/rtl-audit/targets.json+++ b/apps/storybook/rtl-audit/targets.json@@ -197,6 +197,15 @@"next": ".astryx-chat-message-bubble[data-sender=\"user\"]"}},+ {+ "component": "ChatMessage",+ "storyId": "core-chatmessage--default",+ "dims": ["D2"],+ "selectors": {+ "prev": "section[aria-label=\"Density precedence\"] article[data-sender=\"assistant\"] .astryx-chat-message-bubble",+ "next": "section[aria-label=\"Density precedence\"] article[data-sender=\"user\"] .astryx-chat-message-bubble"+ }+ },{"component": "ChatSendButton","storyId": "core-chatcomposer--with-streaming",diff --git a/apps/storybook/stories/ChatMessage.stories.tsx b/apps/storybook/stories/ChatMessage.stories.tsxnew file mode 100644index 0000000000..ec031d9293--- /dev/null+++ b/apps/storybook/stories/ChatMessage.stories.tsx@@ -0,0 +1,126 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import type {Meta, StoryObj} from '@storybook/react';+import {+ ChatMessage,+ ChatMessageBubble,+ ChatMessageList,+} from '@astryxdesign/core/Chat';+import {Avatar} from '@astryxdesign/core/Avatar';+import {Text} from '@astryxdesign/core/Text';++const meta: Meta<typeof ChatMessage> = {+ title: 'Core/ChatMessage',+ component: ChatMessage,+ tags: ['autodocs', 'visual-theme-matrix'],+ parameters: {+ layout: 'centered',+ },+};+export default meta;++type Story = StoryObj<typeof meta>;++function RendersNothing() {+ return null;+}++export const Default: Story = {+ render: () => (+ <div+ style={{+ display: 'flex',+ flexDirection: 'column',+ gap: 24,+ width: 'min(720px, 90vw)',+ }}>+ <section+ aria-label="Sender roles"+ style={{display: 'flex', flexDirection: 'column', gap: 20}}>+ <ChatMessage+ sender="assistant"+ avatar={<Avatar name="Astra" size="md" />}+ name="Astra"+ metadata={+ <Text type="supporting" color="secondary">+ Updated just now+ </Text>+ }>+ <Text type="body">+ Here is the summary you asked for, with the sender identity and+ message metadata attached to the message wrapper.+ </Text>+ </ChatMessage>++ <ChatMessage sender="user">+ <ChatMessageBubble>+ Thanks. Keep the follow-up concise and include the next action.+ </ChatMessageBubble>+ </ChatMessage>++ <ChatMessage+ sender="system"+ avatar={<Avatar name="System" size="md" />}+ name="System"+ metadata={<span>Suppressed metadata</span>}>+ <Text type="supporting" color="secondary">+ Conversation archived+ </Text>+ </ChatMessage>+ </section>++ <section aria-label="Density precedence">+ <ChatMessageList+ density="compact"+ style={{+ border: '1px solid var(--color-border-primary)',+ borderRadius: 'var(--radius-container)',+ }}>+ <ChatMessage+ sender="assistant"+ avatar={<Avatar name="Astra" size="sm" />}>+ <ChatMessageBubble>Inherited compact density</ChatMessageBubble>+ <ChatMessageBubble>Second grouped response</ChatMessageBubble>+ </ChatMessage>+ <ChatMessage sender="user" density="spacious">+ <ChatMessageBubble>+ Explicit spacious density overrides the compact list.+ </ChatMessageBubble>+ </ChatMessage>+ </ChatMessageList>+ </section>++ <section+ aria-label="Slots that render nothing"+ style={{display: 'flex', flexDirection: 'column', gap: 20}}>+ <ChatMessage+ sender="assistant"+ avatar={<RendersNothing />}+ name={<></>}+ metadata={[]}>+ <ChatMessageBubble>+ Empty avatar, name, and metadata slots collapse; the message keeps+ its fallback label.+ </ChatMessageBubble>+ </ChatMessage>+ <ChatMessage sender="user" avatar={false} name="" metadata={false}>+ <ChatMessageBubble>+ Booleans and empty strings render no slot.+ </ChatMessageBubble>+ </ChatMessage>+ </section>++ <section+ aria-label="Narrow long content"+ style={{width: 320, maxWidth: '100%'}}>+ <ChatMessage sender="assistant" name="Astra">+ <ChatMessageBubble>+ Long messages wrap inside a narrow conversation without changing the+ sender alignment or forcing the message beyond its container. This+ sentence intentionally expands the content across several lines.+ </ChatMessageBubble>+ </ChatMessage>+ </section>+ </div>+ ),+};diff --git a/packages/core/src/Chat/ChatMessage.doc.mjs b/packages/core/src/Chat/ChatMessage.doc.mjsindex 7c3da8833d..3236c0b039 100644--- a/packages/core/src/Chat/ChatMessage.doc.mjs+++ b/packages/core/src/Chat/ChatMessage.doc.mjs@@ -6,7 +6,8 @@ export const docs = {name: 'ChatMessage',subComponentOf: 'Chat',displayName: 'Chat Message',- description: 'Sender context wrapper: handles avatar, name, metadata, and alignment based on sender role.',+ description:+ 'Sender context wrapper: handles avatar, name, metadata, and alignment based on sender role.',playground: {defaults: {sender: 'assistant',@@ -28,7 +29,8 @@ export const docs = {{name: 'children',type: 'ReactNode',- description: 'Free-form content: bubbles, asset lists, tool calls, images. Custom (non-bubble) children render flush with the message edge; wrap them in a ghost ChatMessageBubble to align them with the bubble text column.',+ description:+ 'Free-form content: bubbles, asset lists, tool calls, images. Custom (non-bubble) children render flush with the message edge; wrap them in a ghost ChatMessageBubble to align them with the bubble text column.',required: true,slotElements: [{@@ -40,7 +42,8 @@ export const docs = {{name: 'avatar',type: 'ReactNode',- description: 'Avatar element rendered beside the message. Typically Avatar.',+ description:+ 'Avatar element rendered beside the message. Typically Avatar. `null`, booleans, and empty strings create no slot; any other content that renders nothing collapses its slot.',slotElements: [{__element: 'Avatar',@@ -54,12 +57,14 @@ export const docs = {{name: 'name',type: 'ReactNode',- description: "Sender name rendered above the message body. Use when the first child is raw content (not a bubble). If the first child is a bubble, put the name on the bubble's `name` prop instead.",+ description:+ "Sender name rendered above the message body; it labels the message. `null`, booleans, and empty strings create no slot, and any other content that renders nothing collapses its slot; either way the message is labelled by the translated sender fallback. Use when the first child is raw content (not a bubble). If the first child is a bubble, put the name on the bubble's `name` prop instead.",},{name: 'metadata',type: 'ReactNode',- description: "Metadata rendered below the message body. Use when the last child is raw content (not a bubble). If the last child is a bubble, put metadata on the bubble's `metadata` prop instead.",+ description:+ "Metadata rendered below the message body. `null`, booleans, and empty strings create no slot; any other content that renders nothing collapses its slot. Use when the last child is raw content (not a bubble). If the last child is a bubble, put metadata on the bubble's `metadata` prop instead.",slotElements: [{__element: 'Text',@@ -74,6 +79,7 @@ export const docs = {name: 'density',type: "'compact' | 'balanced' | 'spacious'",description: 'Visual density. Inherited from list context if not set.',+ default: "'balanced'",},],};@@ -81,13 +87,17 @@ export const docs = {export const docsZh = {name: 'ChatMessage',displayName: 'Chat Message',- description: '发送者上下文包装器,根据发送者角色处理头像、名称、元数据和对齐方式。',+ description:+ '发送者上下文包装器,根据发送者角色处理头像、名称、元数据和对齐方式。',propDescriptions: {sender: '消息发送者,控制对齐和布局。',- children: '自由内容:气泡、资源列表、工具调用、图片。非气泡的自定义子内容默认与消息边缘齐平,可用 ghost 变体的 ChatMessageBubble 包裹使其与气泡文本列对齐。',- avatar: '消息旁边渲染的头像元素。通常是 Avatar。',- name: '消息正文上方渲染的发送者名称。当第一个子元素不是气泡时使用。',- metadata: '消息正文下方渲染的元数据。当最后一个子元素不是气泡时使用。',+ children:+ '自由内容:气泡、资源列表、工具调用、图片。非气泡的自定义子内容默认与消息边缘齐平,可用 ghost 变体的 ChatMessageBubble 包裹使其与气泡文本列对齐。',+ avatar:+ '消息旁边渲染的头像元素。通常是 Avatar。`null`、布尔值和空字符串不会创建槽位;其他不渲染任何内容的值会让槽位折叠。',+ name: '消息正文上方渲染的发送者名称,并作为消息的标签。`null`、布尔值和空字符串不会创建槽位,其他不渲染任何内容的值会让槽位折叠;两种情况都改用本地化发送者标签。当第一个子元素不是气泡时使用。',+ metadata:+ '消息正文下方渲染的元数据。`null`、布尔值和空字符串不会创建槽位;其他不渲染任何内容的值会让槽位折叠。当最后一个子元素不是气泡时使用。',density: '视觉密度。未设置时从列表上下文继承。',},};@@ -95,14 +105,19 @@ export const docsZh = {export const docsDense = {name: 'ChatMessage',displayName: 'Chat Message',- description: 'sender context wrapper; handles avatar+name+metadata+alignment by sender role',+ description:+ 'sender context wrapper; handles avatar+name+metadata+alignment by sender role',propDescriptions: {sender: 'who sent; controls alignment+layout',- children: 'free-form: bubbles, assets, tool calls, images; wrap non-bubble content in a ghost bubble to align with bubble text column',- avatar: 'avatar element beside msg; typically Avatar',- name: 'sender name above body; use when first child is raw (not bubble)',- displayName: 'sender name above body; use when first child is raw (not bubble)',- metadata: 'metadata below body; use when last child is raw (not bubble)',+ children:+ 'free-form: bubbles, assets, tool calls, images; wrap non-bubble content in a ghost bubble to align with bubble text column',+ avatar:+ 'avatar beside msg; null/boolean/"" omit slot; content rendering nothing collapses slot',+ name: 'sender name above body; labels msg; null/boolean/"" omit slot, content rendering nothing collapses it; both fall back to translated sender label; use when first child is raw',+ displayName:+ 'sender name above body; use when first child is raw (not bubble)',+ metadata:+ 'metadata below body; null/boolean/"" omit slot; content rendering nothing collapses slot; use when last child is raw',density: 'visual density; inherited from list context if unset',},};diff --git a/packages/core/src/Chat/ChatMessage.spec.md b/packages/core/src/Chat/ChatMessage.spec.mdnew file mode 100644index 0000000000..7d4bea5394--- /dev/null+++ b/packages/core/src/Chat/ChatMessage.spec.md@@ -0,0 +1,265 @@+---+schema_version: 3+template_version: 6+kind: component+id: component:ChatMessage+authority: draft+archive_reason: null+superseded_by: null+approved_by: null+approved_at: null+owners: [cixzhang]+review_triggers: [public-api, behavior, layout, theming, accessibility, testing]+verified_by:+ [+ packages/core/src/Chat/ChatMessage.test.tsx,+ packages/core/src/theme/themingTargets.test.ts,+ apps/storybook/stories/ChatMessage.stories.tsx,+ ]+modules: []+families: []+design_specs: []+architecture:+ [+ architecture:public-component-api,+ architecture:component-style-authoring,+ architecture:component-theming-surface,+ architecture:theme-tokens,+ architecture:react-component-runtime,+ architecture:component-test-sufficiency,+ architecture:knowledge-contracts,+ ]+contributing: []+system_specs: [spec:AST-020, spec:AST-029]+---++# ChatMessage component contract++This record is an **observational backfill** written during the 2026-09-24+component audit under `spec:AST-029/FR3–FR4`. Rows marked `verify` describe the+audit base's released contract. Rows marked `proposed` describe the empty-slot+behavior (FR3, FR6, ORD2, AR1–AR2, DEC-1) and await owner approval: `null`,+booleans, and empty strings create no slot; any other slot content that renders+nothing collapses its wrapper through CSS; and a name that renders no text falls+back to the translated sender label. Slot content is never inspected to decide+any of this. Unresolved questions remain open rather than becoming policy.++## Contract at a glance++| Area | Contract |+| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `sender`, `children`, `avatar`, `name`, `metadata`, `density`, plus `BaseProps<HTMLElement>` and `ref` on the message article. |+| Behavior | Sender controls logical alignment and system-message suppression; density resolves explicit prop → message-list context → `balanced`; descendants receive the resolved context. |+| End-user impact | People reading a conversation can distinguish user, assistant, and system messages while names and translated fallback labels preserve each article's sender identity. |+| Builder impact | No new caller choice. Slot content that renders nothing leaves no empty space and no unnamed article. |+| Compatibility/readiness | Draft. No public API, default, or theming target changes; the empty-slot rows are a patch fix. Authority remains `draft` until exact-head owner approval. |+| Review checks | Reject a row that states unshipped behavior, changes sender or density meaning, treats caller content as component-owned, or turns the unresolved theming question into new API. |+| Governing rules | `architecture:public-component-api/INV1, INV3, INV5–INV6, INV8–INV9`; `architecture:component-theming-surface/INV3–INV6`; `spec:AST-029/FR3–FR6`. |++This table is a review projection; the body below is authoritative.++## Intent++ChatMessage is the sender-aware article wrapper for one message in a+conversation. It owns logical alignment, optional sender identity slots, the+resolved density context supplied to message descendants, and the article's+accessible name. Message content and its own interactions remain caller-owned.++Consumer syntax and examples belong in `ChatMessage.doc.mjs` and the Chat family+document.++## Compatibility and migration++- Released default preserved: yes — the published `./Chat` subpath exports+ `ChatMessage`, `ChatMessageProps`, `ChatMessageSender`, and `ChatDensity`.+- Compatibility class: patch fix. Slot content that renders nothing creates no+ visible slot, and a name that renders no text leaves the translated fallback+ label; a name that renders text labels the article.+- Controlled/uncontrolled behavior: not applicable; the component owns no+ controllable value.+- Migration decision: none.++Consumer migration instructions belong in consumer docs and release notes.++## Ownership boundary++**Owns**++- One semantic `<article>` root and its public ref, DOM, data, ARIA, class, and+ style passthrough.+- Logical start, end, or centered alignment selected by `sender`.+- Optional avatar, name, and metadata placement for non-system messages,+ including collapsing a slot whose content renders nothing (DEC-1).+- Density resolution and the `ChatMessageContext` value supplied to descendants.+- The `chat-message` target with its `sender` and resolved `density` axes.+- The article's visible-name or translated fallback accessible label.++**Does not own / non-goals**++- Bubble presentation, grouping, width, name, or metadata — owned by+ `component:ChatMessageBubble` when a bubble supplies them.+- Avatar appearance — owned by the caller's supplied node, commonly+ `component:Avatar`.+- Metadata content, timestamp formatting, status, or footer actions — owned by+ the supplied node and its components.+- Message-list ordering, spacing between messages, streaming announcements, or+ scroll behavior — owned by `component:ChatMessageList` and+ `component:ChatLayout`.+- Interactions inside `children`; descendants retain their own semantic and+ accessibility contracts.++## Public concepts++| Concept | Closed values or states | Meaning | Availability by variant/orientation/state | Default | Owner | Stability | Invalid-value behavior |+| ------------ | --------------------------------------------------------- | --------------------------------------------------------------------------------------- | ----------------------------------------- | --------- | ---------------------- | --------- | ------------------------------- |+| `sender` | `assistant`; `user`; `system` | Selects logical alignment, article identity, and whether auxiliary identity slots show. | required in every message | required | component | stable | closed union; rejected by types |+| `children` | any `ReactNode` | Message body passed through inside the aligned content column. | every sender | required | caller | stable | n/a — required |+| `avatar` | renders content; renders nothing; skipped scalar; omitted | Optional identity node beside a non-system message. | assistant and user; suppressed for system | omitted | caller | stable | renders nothing: slot collapses |+| `name` | renders text; renders nothing; skipped scalar; omitted | Optional visible sender name and article label source. | assistant and user; suppressed for system | omitted | caller/component | stable | renders no text: fallback label |+| `metadata` | renders content; renders nothing; skipped scalar; omitted | Optional content below the message body. | assistant and user; suppressed for system | omitted | caller | stable | renders nothing: slot collapses |+| `density` | `compact`; `balanced`; `spacious`; omitted | Selects gaps and becomes descendant message context. | every sender | inherited | component/list context | stable | closed union; rejected by types |+| root surface | `ref`; DOM/data/ARIA props; `className`/`style`/`xstyle` | Extends the message article. | every sender | omitted | public component API | stable | n/a |++## Behavioral and layout contract++Draft requirements identify their basis so observed code is not mistaken for an+intentional decision.++| ID | Candidate invariant | Basis | Draft review state |+| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | ------------------ |+| FR1 | `assistant` MUST align to inline start, `user` to inline end, and `system` to the centre; the root MUST reflect the sender on the `chat-message` target. | shipped implementation; consumer docs; focused tests | verify |+| FR2 | `system` MUST suppress the supplied avatar, name, and metadata while continuing to render `children`. | shipped implementation; Chat family anatomy; focused tests | verify |+| FR3 | A non-system message MUST render supplied avatar, name, children, and metadata in that visual order. `null`, boolean, and empty-string auxiliary values MUST NOT create wrappers; a wrapper whose content renders nothing MUST collapse (DEC-1). | owner direction; focused tests | proposed |+| FR4 | Density MUST resolve explicit `density` → nearest `ChatMessageList` density → `balanced`, and the resolved value MUST reflect on the root target. | shipped implementation; consumer docs; focused tests; theming metadata | verify |+| FR5 | Descendants MUST receive the resolved `{sender, density}` value through `ChatMessageContext`. | shipped implementation; descendant composition | verify |+| FR6 | The article MUST carry the translated sender fallback as `aria-label`, and a non-system `name` that is not a skipped scalar MUST also label it through `aria-labelledby`. A name that renders text names the article; one that renders none leaves the fallback (accessible name computation 1.2, step 2B). | owner direction; accessible name computation 1.2; focused tests | proposed |+| FR7 | Accepted `ref`, DOM/data/ARIA props, `className`, `style`, and `xstyle` MUST reach and compose on the same article that carries the `chat-message` target. | `architecture:public-component-api/INV5–INV6, INV8`; focused tests | settled |++### Allowed variation++- **AV1 — Message content.** `children` may be bubbles, rich content, tool output,+ media, or any other caller-owned React node.+- **AV2 — Identity content.** Avatar, name, and metadata are caller-owned nodes+ passed to React unchanged; the wrapper controls placement, system suppression,+ and collapse of a slot whose content renders nothing.+- **AV3 — Density geometry.** Resolved gaps follow the active theme's spacing+ scale; the compact → balanced → spacious ordering is fixed.++### Representative states++| State | Required invariant | Allowed variation |+| ------------------------------------------- | ----------------------------------------------------------------- | --------------------------------------------------- |+| Assistant with avatar, name, and metadata | Inline-start layout; visible name labels the article | Any caller-owned node may fill the slots |+| Skipped scalar auxiliary values | No slot or naming reference is created | `null`, booleans, empty strings |+| Auxiliary content that renders nothing | The slot collapses; a name of this kind leaves the fallback label | Empty array or Fragment, component returning `null` |+| Numeric auxiliary values | `0` remains visible and a numeric name labels the article | Any non-system sender |+| User without a name | Inline-end layout; translated sender fallback labels the article | Avatar and metadata may be present or omitted |+| System with auxiliary props supplied | Centre layout; avatar, name, and metadata remain suppressed | Any children continue to render |+| Standalone message | Resolved density is `balanced` | Any sender and content |+| Message inside a density-providing list | Inherits the list density | Any sender and content |+| Message with explicit density inside a list | Explicit density wins | Any supported density |+| Narrow container with long content | Root stays within the container and content remains available | Descendant content chooses its own wrap policy |+| RTL container | Logical user/assistant alignment mirrors with document direction | System remains centred |++### Transformation and precedence order++- **ORD1 — Density.** Resolve the explicit message prop first, then the nearest+ message-list context, then `balanced`; use that single result for layout,+ target reflection, and descendant context.+- **ORD2 — Accessible name.** A system `name` or a skipped scalar creates no+ name wrapper. Otherwise the article references the name wrapper's generated+ id; the rendered text there names the article, and empty text yields to the+ translated fallback carried as `aria-label`.++### Performance and resources++- **PR1 — No external resources.** ChatMessage installs no listener, timer,+ observer, request, or Effect.+- **PR2 — Stable broadcast.** The descendant context value changes only when the+ resolved sender or density changes.++## Accessibility contract++- **AR1 — Article naming mechanism.** Every article carries the translated+ sender fallback as `aria-label`. A name wrapper, when present, is referenced+ through `aria-labelledby`; its rendered text names the article, and when it+ renders no text the accessible name falls back to `aria-label`.+- **AR2 — No inspection.** Slot content is never inspected, cloned, or+ executed to decide whether it renders; collapse and the naming fallback follow+ the rendered DOM.+- **AR3 — Descendant ownership.** ChatMessage is non-interactive and introduces no+ keyboard model. Interactive descendants remain responsible for their own roles,+ names, states, focus, and activation.++## Design relationships++| Anatomy or state | Design requirement | Representation authority | Hierarchy role | Component contract |+| ---------------- | ------------------------------------------------------- | ------------------------ | -------------- | ------------------ |+| Assistant | Align the message column to logical start | observed | content | FR1 |+| User | Align the message column to logical end | observed | content | FR1 |+| System | Centre the content column and suppress identity slots | observed | supporting | FR1–FR2 |+| Name | Use supporting type and secondary text colour tokens | observed | supporting | FR3 |+| Density | Increase root and child gaps across the three-step axis | observed | structure | FR4 |++No component-local design decision is settled by this draft.++### Theming reachability (observed)++| Anatomy part | Disposition |+| ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Message root | `target` — the `chat-message` target sits on the article and reflects `sender` and resolved `density`; the Chat family document owns its consumer metadata. |+| Avatar | `delegatesTo` the supplied node, commonly the `avatar` target owned by `component:Avatar`. |+| Name | `none` — reachability-gap: the built-in name paints explicit supporting type and secondary colour on an untargeted descendant; see OQ1. |+| Content | `delegatesTo` caller-owned children and their targets; custom content has no component-owned target. |+| Metadata | `none` — intentional current boundary: the caller supplies the complete rendered node, while the wrapper contributes placement only. |++## Family and system relationships++- There is no current `family:chat` record. `Chat.doc.mjs` is the consumer-facing+ family document and owns the shared target inventory; it is not product authority.+- `component:ChatMessageList` supplies optional density context and owns list+ spacing, log semantics, streaming state, and message ordering.+- `component:ChatMessageBubble` consumes sender and density context when present+ and owns bubble presentation.+- There is no current direct owner for ChatMessage's+ `compact | balanced | spacious` density vocabulary or ordering. FR4–FR5 record+ the shipped axis and precedence observationally; routed global layout claims do+ not settle that component-specific vocabulary.+- `spec:AST-029` permits this observational draft and keeps the closed audit+ inventory outside the component contract.++## Verification map++| Contract | Verification | Representative states | Mutation or failure expectation | Audit section |+| ------------ | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------- | ---------------------- |+| FR1–FR3 | `ChatMessage.test.tsx`; `ChatMessage.stories.tsx` | all senders; skipped scalar, renders-nothing, numeric, content, and suppressed slot states | Removing the scalar skip or the CSS collapse leaves an empty slot or a gap | `audit:ChatMessage/§4` |+| FR4–FR5 | `ChatMessage.test.tsx`; `themingTargets.test.ts` | standalone; inherited density; explicit override | Changing precedence or reflection gives descendants and themes a different density | `audit:ChatMessage/§2` |+| FR6, AR1–AR2 | `ChatMessage.test.tsx`; Chromium accessibility tree | visible, omitted, skipped-scalar, renders-nothing, and system names | Dropping the fallback `aria-label` or the name reference leaves an article unnamed | `audit:ChatMessage/§1` |+| FR7 | `ChatMessage.test.tsx`; public export and theming-target checks | ref; data prop; class; style | Moving passthrough or ref off the target article breaks the public root contract | `audit:ChatMessage/§3` |+| AR3 | Source review plus component-scoped accessibility audit | rich and interactive descendants | The wrapper introduces an interactive role or takes ownership away from descendants | `audit:ChatMessage/§1` |+| RTL | `ChatMessage.stories.tsx`; component-scoped RTL audit | all senders; narrow long content | Physical direction keeps user or assistant on the same side in both directions | `audit:ChatMessage/§9` |++## Decision log++- **DEC-1 — Slot emptiness follows the rendered DOM.** (`proposed`, awaiting+ owner approval) ChatMessage skips only `null`, boolean, and empty-string+ slot values. Any other content is passed to React unchanged; its wrapper+ collapses with `:empty` when it renders nothing, and the article's naming+ falls back to `aria-label` when the referenced name renders no text.+ Rejected: inspecting arrays, Fragments, or iterables, which cannot see+ component output and consumes one-shot iterators.++## Open questions++- **OQ1 — Should the built-in name become a separately themeable anatomy part?**+ (`human-api`) The released family inventory exposes only the aggregate+ `chat-message` target, while the name's explicit type and colour prevent a root+ override from reaching it by inheritance. Adding or splitting a target changes+ public theming API, so this draft records the reachability gap without choosing a+ remedy.++## Content boundary++This file does not duplicate consumer prop tables or examples, current audit+scores, screenshot matrices, or shared-system rules. The audit PR owns the closed+run evidence required by `spec:AST-029/FR5`.diff --git a/packages/core/src/Chat/ChatMessage.test.tsx b/packages/core/src/Chat/ChatMessage.test.tsxindex 87348dbd6e..393585a696 100644--- a/packages/core/src/Chat/ChatMessage.test.tsx+++ b/packages/core/src/Chat/ChatMessage.test.tsx@@ -1,9 +1,34 @@// Copyright (c) Meta Platforms, Inc. and affiliates.+import {createElement, createRef, Fragment, type ReactNode} from 'react';import {describe, it, expect} from 'vitest';import {render, screen} from '@testing-library/react';import {ChatMessage} from './ChatMessage';import {ChatMessageBubble} from './ChatMessageBubble';+import {ChatMessageList} from './ChatMessageList';++// Content that renders nothing but is not a skipped scalar: its wrapper+// renders and collapses through CSS instead of the content being inspected.+const contentThatRendersNothing: [string, () => ReactNode][] = [+ ['an empty array', () => []],+ ['an array of non-rendering values', () => [null, false, '']],+ ['an empty Fragment', () => createElement(Fragment)],+ ['a component that returns null', () => <RendersNothing />],+];++function RendersNothing() {+ return null;+}++function OpaqueName() {+ return <span>Navi</span>;+}++/** The name wrapper the article's aria-labelledby points at. */+function labelTarget(article: HTMLElement): HTMLElement | null {+ const id = article.getAttribute('aria-labelledby');+ return id == null ? null : article.ownerDocument.getElementById(id);+}describe('ChatMessage', () => {it('renders children', () => {@@ -33,6 +58,60 @@ describe('ChatMessage', () => {expect(screen.queryByText('System')).toBeNull();});+ it.each([false, true, ''])('does not render a name wrapper for %j', name => {+ render(+ <ChatMessage sender="assistant" name={name}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const article = screen.getByRole('article');+ expect(article).toHaveAccessibleName('Message from assistant');+ expect(article).not.toHaveAttribute('aria-labelledby');+ expect(article.querySelector('div:empty')).toBeNull();+ });++ it('preserves a numeric name', () => {+ render(+ <ChatMessage sender="assistant" name={0}>+ <span>Summary</span>+ </ChatMessage>,+ );+ expect(screen.getByRole('article')).toHaveAccessibleName('0');+ expect(screen.getByText('0')).toBeInTheDocument();+ });++ it.each(contentThatRendersNothing)(+ 'collapses the name wrapper and keeps the fallback label for %s',+ (_label, createName) => {+ render(+ <ChatMessage sender="assistant" name={createName()}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const article = screen.getByRole('article');+ const target = labelTarget(article);+ // The label reference resolves to no text, so the accessible name falls+ // back to aria-label; real Chromium computes "Message from assistant".+ expect(target).not.toBeNull();+ expect(target).toBeEmptyDOMElement();+ expect(getComputedStyle(target as HTMLElement).display).toBe('none');+ expect(article).toHaveAttribute('aria-label', 'Message from assistant');+ },+ );++ it('labels the article by a name that renders text', () => {+ render(+ <ChatMessage sender="assistant" name={<OpaqueName />}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const article = screen.getByRole('article');+ expect(article).toHaveAccessibleName('Navi');+ expect(+ getComputedStyle(labelTarget(article) as HTMLElement).display,+ ).not.toBe('none');+ });+it('renders avatar for assistant', () => {render(<ChatMessage@@ -53,6 +132,53 @@ describe('ChatMessage', () => {expect(screen.queryByTestId('avatar')).toBeNull();});+ it.each([false, true, ''])(+ 'does not render an avatar wrapper for %j',+ avatar => {+ render(+ <ChatMessage sender="assistant" avatar={avatar}>+ <span>Summary</span>+ </ChatMessage>,+ );+ expect(screen.getByRole('article').querySelector('div:empty')).toBeNull();+ },+ );++ it('preserves a numeric avatar', () => {+ render(+ <ChatMessage sender="assistant" avatar={0}>+ <span>Summary</span>+ </ChatMessage>,+ );+ expect(screen.getByText('0')).toBeInTheDocument();+ });++ it.each(contentThatRendersNothing)(+ 'collapses the avatar wrapper for %s',+ (_label, createAvatar) => {+ render(+ <ChatMessage sender="assistant" avatar={createAvatar()}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const wrapper = screen.getByRole('article').firstElementChild;+ expect(wrapper).toBeEmptyDOMElement();+ expect(getComputedStyle(wrapper as HTMLElement).display).toBe('none');+ },+ );++ it('keeps an avatar wrapper that renders content visible', () => {+ render(+ <ChatMessage+ sender="assistant"+ avatar={<span data-testid="avatar">N</span>}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const wrapper = screen.getByTestId('avatar').parentElement;+ expect(getComputedStyle(wrapper as HTMLElement).display).not.toBe('none');+ });+it('applies sender class', () => {render(<ChatMessage sender="user" data-testid="msg">@@ -95,4 +221,124 @@ describe('ChatMessage', () => {);expect(screen.getByTestId('custom-content')).toBeTruthy();});++ it('renders metadata for a non-system sender', () => {+ render(+ <ChatMessage sender="assistant" metadata={<span>Updated just now</span>}>+ <span>Summary</span>+ </ChatMessage>,+ );+ expect(screen.getByText('Updated just now')).toBeInTheDocument();+ });++ it('hides metadata for a system sender', () => {+ render(+ <ChatMessage sender="system" metadata={<span>Hidden metadata</span>}>+ <span>Maintenance complete</span>+ </ChatMessage>,+ );+ expect(screen.queryByText('Hidden metadata')).not.toBeInTheDocument();+ });++ it.each([false, true, ''])(+ 'does not render an empty metadata wrapper for %j',+ metadata => {+ render(+ <ChatMessage sender="assistant" metadata={metadata}>+ <span>Summary</span>+ </ChatMessage>,+ );+ expect(screen.getByRole('article').querySelector('div:empty')).toBeNull();+ },+ );++ it('preserves numeric metadata', () => {+ render(+ <ChatMessage sender="assistant" metadata={0}>+ <span>Summary</span>+ </ChatMessage>,+ );+ expect(screen.getByText('0')).toBeInTheDocument();+ });++ it.each(contentThatRendersNothing)(+ 'collapses the metadata wrapper for %s',+ (_label, createMetadata) => {+ render(+ <ChatMessage sender="assistant" metadata={createMetadata()}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const column = screen.getByText('Summary').parentElement?.parentElement;+ const wrapper = column?.lastElementChild;+ expect(wrapper).toBeEmptyDOMElement();+ expect(getComputedStyle(wrapper as HTMLElement).display).toBe('none');+ },+ );++ it('keeps metadata that renders content visible', () => {+ render(+ <ChatMessage sender="assistant" metadata={<span>Updated</span>}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const wrapper = screen.getByText('Updated').parentElement;+ expect(getComputedStyle(wrapper as HTMLElement).display).not.toBe('none');+ });++ it('uses balanced density without list context', () => {+ render(+ <ChatMessage sender="assistant" data-testid="message">+ <span>Summary</span>+ </ChatMessage>,+ );+ expect(screen.getByTestId('message')).toHaveAttribute(+ 'data-density',+ 'balanced',+ );+ });++ it('inherits list density and lets an explicit prop override it', () => {+ render(+ <ChatMessageList density="spacious">+ <ChatMessage sender="assistant" data-testid="inherited">+ <span>Inherited</span>+ </ChatMessage>+ <ChatMessage+ sender="assistant"+ density="compact"+ data-testid="explicit">+ <span>Explicit</span>+ </ChatMessage>+ </ChatMessageList>,+ );+ expect(screen.getByTestId('inherited')).toHaveAttribute(+ 'data-density',+ 'spacious',+ );+ expect(screen.getByTestId('explicit')).toHaveAttribute(+ 'data-density',+ 'compact',+ );+ });++ it('forwards root props and ref while preserving the theme target', () => {+ const ref = createRef<HTMLElement>();+ render(+ <ChatMessage+ ref={ref}+ sender="assistant"+ data-testid="message"+ data-purpose="summary"+ className="consumer-message"+ style={{order: 2}}>+ <span>Summary</span>+ </ChatMessage>,+ );+ const message = screen.getByTestId('message');+ expect(ref.current).toBe(message);+ expect(message).toHaveAttribute('data-purpose', 'summary');+ expect(message).toHaveClass('astryx-chat-message', 'consumer-message');+ expect(message.style.order).toBe('2');+ });});diff --git a/packages/core/src/Chat/ChatMessage.tsx b/packages/core/src/Chat/ChatMessage.tsxindex 474d26a0e1..35dea7d4aa 100644--- a/packages/core/src/Chat/ChatMessage.tsx+++ b/packages/core/src/Chat/ChatMessage.tsx@@ -16,6 +16,7 @@* SYNC: When modified, update these files to stay in sync:* - /packages/core/src/Chat/index.ts (exports)* - /apps/storybook/stories/Chat.stories.tsx+ * - /apps/storybook/stories/ChatMessage.stories.tsx* - /packages/cli/assets/templates/blocks/components/ChatMessage/ (block examples)*/@@ -33,7 +34,7 @@ import {type ChatMessageSender,type ChatDensity,} from './ChatContext';-import {mergeProps} from '../utils';+import {isRenderable, mergeProps} from '../utils';import type {BaseProps} from '../BaseProps';import {themeProps} from '../utils/themeProps';import {useTranslator} from '../i18n';@@ -49,9 +50,17 @@ export interface ChatMessageProps extends BaseProps<HTMLElement> {* should span the full message column.*/children: ReactNode;+ /**+ * Avatar content rendered beside a non-system message.+ * `null`, booleans, and empty strings create no slot; any other content that+ * renders nothing collapses its slot.+ */avatar?: ReactNode;/*** Sender name rendered above the message body.+ * `null`, booleans, and empty strings create no slot, and the message is+ * labelled by the translated sender fallback; any other content that renders+ * nothing collapses its slot and falls back to the same label.* Use when the first child is raw content (not a bubble).* If the first child is a ChatMessageBubble, put the name on the* bubble's `name` prop instead — it aligns with the bubble's padding.@@ -59,6 +68,8 @@ export interface ChatMessageProps extends BaseProps<HTMLElement> {name?: ReactNode;/*** Metadata rendered below the message body.+ * `null`, booleans, and empty strings create no slot; any other content that+ * renders nothing collapses its slot.* Use when the last child is raw content (not a bubble).* If the last child is a ChatMessageBubble, put metadata on the* bubble's `metadata` prop instead — it aligns with the bubble's padding.@@ -94,7 +105,11 @@ const styles = stylex.create({flexDirection: 'row',justifyContent: 'center',},+ // Slot wrappers collapse when the caller's content renders nothing, so an+ // empty Fragment or a component that returns null leaves no gap. Content is+ // never inspected to decide this.avatarWrap: {+ display: {default: null, ':empty': 'none'},flexShrink: 0,':has(~ * [data-chat-name])': {marginBlockStart: spacingVars['--spacing-5'],@@ -117,12 +132,16 @@ const styles = stylex.create({alignItems: 'flex-end',},name: {+ display: {default: null, ':empty': 'none'},fontSize: typeScaleVars['--text-supporting-size'],fontWeight: fontWeightVars['--font-weight-semibold'],color: colorVars['--color-text-secondary'],lineHeight: typeScaleVars['--text-supporting-leading'],marginBlockEnd: spacingVars['--spacing-1'],},+ metadata: {+ display: {default: null, ':empty': 'none'},+ },childrenWrap: {display: 'flex',flexDirection: 'column',@@ -219,8 +238,9 @@ export function ChatMessage({: styles.childrenAssistant;const isSystem = sender === 'system';- const hasAvatar = avatar != null && !isSystem;- const hasName = name != null && !isSystem;+ const hasAvatar = !isSystem && isRenderable(avatar);+ const hasName = !isSystem && isRenderable(name);+ const hasMetadata = !isSystem && isRenderable(metadata);const nameId = useId();return (@@ -229,9 +249,10 @@ export function ChatMessage({{...rest}ref={ref}data-testid={testId}- aria-label={- !hasName ? t('@astryx.chatMessage.messageFrom', {sender}) : undefined- }+ // The visible name labels the article. When it renders no text, the+ // label reference resolves to nothing and the accessible name falls+ // back to aria-label (accessible name computation 1.2, step 2B).+ aria-label={t('@astryx.chatMessage.messageFrom', {sender})}aria-labelledby={hasName ? nameId : undefined}{...mergeProps(themeProps('chat-message', {sender, density}),@@ -262,7 +283,9 @@ export function ChatMessage({{children}</div>- {metadata != null && !isSystem && <div>{metadata}</div>}+ {hasMetadata && (+ <div {...stylex.props(styles.metadata)}>{metadata}</div>+ )}</div></article></ChatMessageContext>