Skip to content

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

TypeScript

feat(core)!: Banner content is visible by default; collapse moves to a `collapsible` prop (#5255)

freddymetadfdd778050d4
diff --git a/.changeset/banner-collapsible-content.md b/.changeset/banner-collapsible-content.md
new file mode 100644
index 0000000000..5ad6910a2e
--- /dev/null
+++ b/.changeset/banner-collapsible-content.md
@@ -0,0 +1,44 @@
+---
+'@astryxdesign/core': minor
+'@astryxdesign/cli': minor
+---
+
+[breaking] Banner: the collapse axis moves onto one `collapsible` prop, and content can opt out of collapsing (#5255)
+
+Banner inferred its disclosure from its content: any `children` got a chevron in
+the header and were hidden until it was pressed. There was no way to show
+content without a toggle — the case a banner most often wants, a list of the
+three fields that failed validation — and `defaultIsExpanded` was the only knob,
+with no controlled mode.
+
+The whole axis is now one `boolean | CollapsibleConfig` prop, following the
+boolean-or-config convention `SideNav.collapsible` set, and backed by the shared
+`useCollapsible` hook rather than Banner's own state:
+
+```tsx
+<Banner status="error" title="3 fields need attention">…</Banner> // unchanged: collapsible, starts closed
+<Banner collapsible={false}>…</Banner> // new: always visible, no toggle
+<Banner collapsible={{defaultIsOpen: true}}>…</Banner> // replaces defaultIsExpanded
+<Banner collapsible={{isOpen, onOpenChange}}>…</Banner> // new: controlled
+```
+
+**The default is unchanged** — a banner that never mentioned `defaultIsExpanded`
+behaves exactly as it did. The breaking part is the prop itself:
+`defaultIsExpanded` is removed in favour of the config, which is a type error at
+every JSX call site that names it.
+
+**Codemod:** `npx astryx upgrade --codemod banner-collapsible-content`
+
+It rewrites `defaultIsExpanded` to `collapsible={{defaultIsOpen: true}}` and
+drops `defaultIsExpanded={false}`, which is now the default. Banners that never
+set the prop are left alone.
+
+**One case the codemod and the compiler both miss: a spread.**
+`defaultIsExpanded` inside a props object is out of the transform's scope. A
+props object in a typed position still fails to compile — but an inferred one
+that is spread, `<Banner {...args} />`, does not, because TypeScript does not
+excess-property-check a spread. The prop then falls through to the DOM and the
+banner quietly starts collapsed. **Grep for `defaultIsExpanded` after running
+the codemod** and migrate any spread sites by hand.
+
+@freddymeta
diff --git a/apps/storybook/stories/Banner.stories.tsx b/apps/storybook/stories/Banner.stories.tsx
index 572b6a8967..f0b64bdf1e 100644
--- a/apps/storybook/stories/Banner.stories.tsx
+++ b/apps/storybook/stories/Banner.stories.tsx
@@ -31,10 +31,10 @@ const meta: Meta<typeof Banner> = {
description:
'Whether the banner can be dismissed (manages its own hidden state)',
},
- defaultIsExpanded: {
+ collapsible: {
control: 'boolean',
description:
- 'Whether the content area starts expanded (only relevant when children are provided)',
+ 'Whether the content area sits behind an expand/collapse toggle. On by default, starting collapsed. false keeps children always visible with no toggle; pass {defaultIsOpen: true} to start open, or {isOpen, onOpenChange} for controlled.',
},
},
};
@@ -152,7 +152,7 @@ export const CollapsibleContentExpanded: Story = {
status: 'info',
title: 'Emphasized Text',
description: 'Description text',
- defaultIsExpanded: true,
+ collapsible: {defaultIsOpen: true},
endContent: <Button label="Button" variant="secondary" size="sm" />,
isDismissable: true,
children: (
@@ -168,13 +168,13 @@ export const CollapsibleContentExpanded: Story = {
},
};
-export const WithContentArea: Story = {
- name: 'With Content Area (Card Background)',
+export const AlwaysVisibleContent: Story = {
+ name: 'Content Always Visible (collapsible={false})',
args: {
status: 'error',
title: 'Multiple errors found',
description: 'The following issues need to be resolved:',
- defaultIsExpanded: true,
+ collapsible: false,
children: (
<ul style={{margin: 0, paddingInlineStart: '20px', fontSize: '13px'}}>
<li>Email address is invalid</li>
@@ -193,7 +193,7 @@ export const ContentAreaWithAction: Story = {
description: 'Review the changes before they take effect.',
endContent: <Button label="Review" variant="secondary" size="sm" />,
isDismissable: true,
- defaultIsExpanded: true,
+ collapsible: {defaultIsOpen: true},
children: (
<div style={{fontSize: '13px'}}>
<p style={{margin: '0 0 8px'}}>Changed settings:</p>
@@ -243,10 +243,21 @@ export const AllFeatures: Story = {
title="With action button"
endContent={<Button label="Learn more" variant="secondary" size="sm" />}
/>
+ <Banner
+ status="error"
+ title="With content, always visible"
+ description="collapsible={false} drops the toggle."
+ isDismissable
+ collapsible={false}>
+ <div style={{fontSize: '13px'}}>
+ The content sits on a card-colored background, visually distinct from
+ the status header above.
+ </div>
+ </Banner>
<Banner
status="error"
title="With collapsible content"
- description="Click the chevron to expand."
+ description="Click the chevron to expand. This is the default."
isDismissable>
<div style={{fontSize: '13px'}}>
This content sits on a card-colored background, visually distinct from
@@ -257,10 +268,12 @@ export const AllFeatures: Story = {
status="success"
title="Expanded by default"
description="This content area starts open."
- defaultIsExpanded
+ collapsible={{
+ defaultIsOpen: true,
+ }}
isDismissable>
<div style={{fontSize: '13px'}}>
- Content is visible immediately because defaultIsExpanded is true.
+ Content is visible immediately because of defaultIsOpen.
</div>
</Banner>
<Banner
diff --git a/packages/cli/assets/codemods/transforms/next/__tests__/next-codemods.test.mjs b/packages/cli/assets/codemods/transforms/next/__tests__/next-codemods.test.mjs
new file mode 100644
index 0000000000..5a2751d963
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/next/__tests__/next-codemods.test.mjs
@@ -0,0 +1,127 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for the staged (next-release) codemods.
+ *
+ * Mirrors v0.4.0/__tests__/next-codemods.test.mjs, which covers the codemods
+ * after promotion. Keeping a copy here means a staged transform is tested from
+ * the day it is written rather than the day it is released.
+ */
+
+import {describe, expect, it} from 'vitest';
+import jscodeshift from 'jscodeshift';
+
+const j = jscodeshift.withParser('tsx');
+const api = {jscodeshift: j, stats: () => {}, report: () => {}};
+
+async function apply(name, source) {
+ const {default: transform} = await import(`../${name}.mjs`);
+ return transform({source, path: 'test.tsx'}, api) ?? source;
+}
+
+const TRANSFORM = 'banner-collapsible-content';
+
+const IMPORT = "import {Banner} from '@astryxdesign/core/Banner';\n";
+
+describe('banner-collapsible-content', () => {
+ it('rewrites a bare defaultIsExpanded to a starts-open config', async () => {
+ const output = await apply(
+ TRANSFORM,
+ `${IMPORT}const el = <Banner status="info" title="T" defaultIsExpanded><p>d</p></Banner>;`,
+ );
+ expect(output).toContain('defaultIsOpen: true');
+ expect(output).not.toContain('defaultIsExpanded');
+ });
+
+ it('rewrites defaultIsExpanded={true} the same way', async () => {
+ const output = await apply(
+ TRANSFORM,
+ `${IMPORT}const el = <Banner status="info" title="T" defaultIsExpanded={true}><p>d</p></Banner>;`,
+ );
+ expect(output).toContain('defaultIsOpen: true');
+ expect(output).not.toContain('defaultIsExpanded');
+ });
+
+ it('drops defaultIsExpanded={false}, which is the default', async () => {
+ const output = await apply(
+ TRANSFORM,
+ `${IMPORT}const el = <Banner status="info" title="T" defaultIsExpanded={false}><p>d</p></Banner>;`,
+ );
+ expect(output).not.toContain('defaultIsExpanded');
+ // No config needed: starting collapsed is what a Banner does by default.
+ expect(output).not.toContain('collapsible');
+ // Untouched attributes keep their original text (recast only reprints
+ // what changed), so the element is exactly the base minus the prop.
+ expect(output).toContain('<Banner status="info" title="T">');
+ });
+
+ it('keeps a dynamic default dynamic', async () => {
+ const output = await apply(
+ TRANSFORM,
+ `${IMPORT}const el = <Banner status="info" title="T" defaultIsExpanded={isOpen}><p>d</p></Banner>;`,
+ );
+ expect(output).toContain('defaultIsOpen: isOpen');
+ expect(output).not.toContain('defaultIsExpanded');
+ });
+
+ it('leaves a banner that never set the prop alone', async () => {
+ // The default is unchanged, so this banner still behaves as it did. The
+ // migration must not touch it — that is the whole point of the shape.
+ const source = `${IMPORT}const el = <Banner status="error" title="T"><ul><li>a</li></ul></Banner>;`;
+ const output = await apply(TRANSFORM, source);
+ expect(output).toBe(source);
+ });
+
+ it('leaves a childless banner alone', async () => {
+ const source = `${IMPORT}const el = <Banner status="info" title="T" />;`;
+ const output = await apply(TRANSFORM, source);
+ expect(output).toBe(source);
+ });
+
+ it('leaves a banner that already uses collapsible alone', async () => {
+ const source = `${IMPORT}const el = <Banner status="info" title="T" collapsible={false} defaultIsExpanded><p>d</p></Banner>;`;
+ const output = await apply(TRANSFORM, source);
+ expect(output).toBe(source);
+ });
+
+ it('does not guess around a spread', async () => {
+ const source = `${IMPORT}const el = <Banner status="info" title="T" defaultIsExpanded {...rest}><p>d</p></Banner>;`;
+ const output = await apply(TRANSFORM, source);
+ expect(output).toBe(source);
+ });
+
+ it("leaves another component's defaultIsExpanded alone", async () => {
+ // ChatToolCalls has a prop of the same name that this migration must not
+ // touch.
+ const source = `import {ChatToolCalls} from '@astryxdesign/core/Chat';
+const el = <ChatToolCalls calls={calls} defaultIsExpanded />;`;
+ const output = await apply(TRANSFORM, source);
+ expect(output).toBe(source);
+ });
+
+ it('leaves a Banner that is not the core Banner alone', async () => {
+ const source = `import {Banner} from './ui/Banner';
+const el = <Banner status="info" title="T" defaultIsExpanded><p>d</p></Banner>;`;
+ const output = await apply(TRANSFORM, source);
+ expect(output).toBe(source);
+ });
+
+ it('leaves the prop inside a props object alone', async () => {
+ // Out of scope by design: which component the object feeds is a guess,
+ // and the removed prop makes those sites a type error anyway.
+ const source = `${IMPORT}const args = {status: 'info', title: 'T', defaultIsExpanded: true};
+const el = <Banner {...args} />;`;
+ const output = await apply(TRANSFORM, source);
+ expect(output).toBe(source);
+ });
+
+ it('migrates a Banner imported from the package root', async () => {
+ const output = await apply(
+ TRANSFORM,
+ `import {Banner, Button} from '@astryxdesign/core';
+const el = <Banner status="info" title="T" defaultIsExpanded><p>d</p></Banner>;`,
+ );
+ expect(output).toContain('defaultIsOpen: true');
+ expect(output).not.toContain('defaultIsExpanded');
+ });
+});
diff --git a/packages/cli/assets/codemods/transforms/next/banner-collapsible-content.mjs b/packages/cli/assets/codemods/transforms/next/banner-collapsible-content.mjs
new file mode 100644
index 0000000000..c641095733
--- /dev/null
+++ b/packages/cli/assets/codemods/transforms/next/banner-collapsible-content.mjs
@@ -0,0 +1,171 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Codemod: migrate Banner's `defaultIsExpanded` onto `collapsible`
+ *
+ * Banner's collapse axis used to be a single knob, `defaultIsExpanded`, with
+ * the disclosure itself inferred from the presence of `children`. There was no
+ * way to have content without a toggle, and no controlled mode. The axis now
+ * lives on one `boolean | CollapsibleConfig` prop, per the boolean-or-config
+ * convention:
+ *
+ * <Banner>{children}</Banner> → collapsible, starts closed
+ * <Banner collapsible={{defaultIsOpen: true}}> → collapsible, starts open
+ * <Banner collapsible={{isOpen, onOpenChange}}> → controlled
+ * <Banner collapsible={false}> → always visible, no toggle
+ *
+ * The default is unchanged, so a Banner that never mentioned the old prop needs
+ * no rewrite at all — this transform is a prop rename and nothing more:
+ *
+ * defaultIsExpanded → collapsible={{defaultIsOpen: true}}
+ * defaultIsExpanded={true} → collapsible={{defaultIsOpen: true}}
+ * defaultIsExpanded={false} → (removed — it is the default)
+ * defaultIsExpanded={expr} → collapsible={{defaultIsOpen: expr}}
+ *
+ * Only elements named `Banner` are touched, and only when the file imports that
+ * name from `@astryxdesign/core`: `defaultIsExpanded` is also a ChatToolCalls
+ * prop, which this migration must leave alone.
+ *
+ * Scope: JSX attributes only. `defaultIsExpanded` inside a props object (a
+ * Storybook `args`, a spread built up in a variable) is left alone rather than
+ * rewritten on a guess about which component the object is for — removing the
+ * prop from the type makes those sites a type error, which is loud enough to
+ * find them.
+ */
+
+export const meta = {
+ title: "Rename Banner's `defaultIsExpanded` to the `collapsible` config",
+ description:
+ "Banner's collapse axis is now a single `collapsible?: boolean | " +
+ 'CollapsibleConfig` prop. Rewrites `defaultIsExpanded` to the equivalent ' +
+ 'config (`{defaultIsOpen: true}`), and drops ' +
+ '`defaultIsExpanded={false}`, which is the default. Banners that never ' +
+ 'set the prop are untouched — the default is unchanged. Pass ' +
+ '`collapsible={false}` for content that is always visible.',
+ pr: '#5255',
+};
+
+const OLD_PROP = 'defaultIsExpanded';
+const NEW_PROP = 'collapsible';
+const COMPONENT = 'Banner';
+
+/**
+ * Does this file use the core `Banner`?
+ *
+ * `defaultIsExpanded` is a ChatToolCalls prop too, and a local component may
+ * well be called Banner, so an unqualified element-name match is not enough.
+ *
+ * @param {any} j
+ * @param {any} root
+ * @returns {boolean}
+ */
+function importsCoreBanner(j, root) {
+ let found = false;
+ root.find(j.ImportDeclaration).forEach((/** @type {any} */ path) => {
+ const source = path.node.source?.value;
+ if (typeof source !== 'string' || !source.startsWith('@astryxdesign/core')) {
+ return;
+ }
+ for (const spec of path.node.specifiers ?? []) {
+ if (
+ (spec.type === 'ImportSpecifier' && spec.imported?.name === COMPONENT) ||
+ (spec.local?.name === COMPONENT &&
+ (spec.type === 'ImportDefaultSpecifier' ||
+ spec.type === 'ImportSpecifier'))
+ ) {
+ found = true;
+ }
+ }
+ });
+ return found;
+}
+
+/**
+ * @param {import('../../../../authoring/codemod/type').AstryxCodemodFile} file
+ * @param {import('../../../../authoring/codemod/type').CodemodTransformApi} api
+ * @returns {string | null | undefined}
+ */
+export default function transformer(file, api) {
+ // Cheap bail-out: nothing to rename without the old prop.
+ if (!file.source.includes(OLD_PROP)) {
+ return undefined;
+ }
+
+ const j = api.jscodeshift;
+ const root = j(file.source);
+
+ if (!importsCoreBanner(j, root)) {
+ return undefined;
+ }
+
+ let hasChanges = false;
+
+ /** `collapsible={{defaultIsOpen: <expr>}}` */
+ const collapsibleWithDefault = (/** @type {any} */ expression) =>
+ j.jsxAttribute(
+ j.jsxIdentifier(NEW_PROP),
+ j.jsxExpressionContainer(
+ j.objectExpression([
+ j.objectProperty(j.identifier('defaultIsOpen'), expression),
+ ]),
+ ),
+ );
+
+ root.find(j.JSXOpeningElement).forEach((/** @type {any} */ path) => {
+ const name = path.node.name;
+ if (name?.type !== 'JSXIdentifier' || name.name !== COMPONENT) {
+ return;
+ }
+
+ const attrs = path.node.attributes ?? [];
+ const oldIndex = attrs.findIndex(
+ (/** @type {any} */ a) =>
+ a.type === 'JSXAttribute' && a.name?.name === OLD_PROP,
+ );
+ if (oldIndex === -1) {
+ return;
+ }
+
+ // Already migrated by hand, or a spread that may carry either prop:
+ // in both cases a rewrite would be guesswork.
+ const hasNewProp = attrs.some(
+ (/** @type {any} */ a) =>
+ a.type === 'JSXAttribute' && a.name?.name === NEW_PROP,
+ );
+ const hasSpread = attrs.some(
+ (/** @type {any} */ a) => a.type === 'JSXSpreadAttribute',
+ );
+ if (hasNewProp || hasSpread) {
+ return;
+ }
+
+ const value = attrs[oldIndex].value;
+
+ if (value == null) {
+ // Bare `defaultIsExpanded` — starts open.
+ attrs[oldIndex] = collapsibleWithDefault(j.booleanLiteral(true));
+ } else if (value.type === 'JSXExpressionContainer') {
+ const expression = value.expression;
+ const isBooleanLiteral =
+ expression.type === 'BooleanLiteral' ||
+ (expression.type === 'Literal' && typeof expression.value === 'boolean');
+ if (isBooleanLiteral && expression.value === false) {
+ // Starting closed is the default now, so the prop simply goes.
+ attrs.splice(oldIndex, 1);
+ } else if (isBooleanLiteral) {
+ attrs[oldIndex] = collapsibleWithDefault(j.booleanLiteral(true));
+ } else {
+ // A dynamic default stays dynamic.
+ attrs[oldIndex] = collapsibleWithDefault(expression);
+ }
+ } else {
+ // `defaultIsExpanded="something"` is not valid for a boolean prop;
+ // leave it for a human rather than inventing a meaning.
+ return;
+ }
+
+ hasChanges = true;
+ });
+
+ return hasChanges ? root.toSource({quote: 'single'}) : undefined;
+}
diff --git a/packages/cli/assets/codemods/transforms/next/index.mjs b/packages/cli/assets/codemods/transforms/next/index.mjs
index 2af3bdfcf0..731d127b13 100644
--- a/packages/cli/assets/codemods/transforms/next/index.mjs
+++ b/packages/cli/assets/codemods/transforms/next/index.mjs
@@ -7,4 +7,14 @@
* this file into the resolved version folder.
*/
-export default [];
+import bannerCollapsibleContent, {
+ meta as bannerCollapsibleContentMeta,
+} from './banner-collapsible-content.mjs';
+
+export default [
+ {
+ name: 'banner-collapsible-content',
+ transform: bannerCollapsibleContent,
+ meta: bannerCollapsibleContentMeta,
+ },
+];
diff --git a/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.doc.mjs b/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.doc.mjs
index 5d56406264..c6b5addb24 100644
--- a/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.doc.mjs
+++ b/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.doc.mjs
@@ -6,7 +6,7 @@ export const doc = {
exampleFor: 'Banner',
name: 'Banner — Collapsible',
displayName: 'Banner — Collapsible',
- description: 'Combine an action button, dismiss control, and expandable detail area in one banner. Use for complex notifications like config changes or deployment summaries.',
+ description: 'Combine an action button, dismiss control, and a collapsible detail area in one banner. Children sit behind the toggle by default; `collapsible={{defaultIsOpen: true}}` starts it open, and `collapsible={false}` drops the toggle entirely. Use for complex notifications like config changes or deployment summaries.',
isReady: true,
aspectRatio: 16 / 9,
componentsUsed: ['Banner', 'Button', 'List', 'Layout', 'Text'],
diff --git a/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.tsx b/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.tsx
index 8d0c70e7a2..d82e90e121 100644
--- a/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.tsx
+++ b/packages/cli/assets/templates/blocks/components/Banner/BannerCollapsibleContent.tsx
@@ -16,7 +16,7 @@ export default function BannerCollapsibleContent() {
description="Review the changes before they take effect."
endContent={<Button label="Review" variant="secondary" size="sm" />}
isDismissable
- defaultIsExpanded>
+ collapsible={{defaultIsOpen: true}}>
<Stack direction="vertical" gap={2}>
<Text type="supporting" color="secondary">
Changed settings:
diff --git a/packages/core/src/Banner/Banner.doc.mjs b/packages/core/src/Banner/Banner.doc.mjs
index cc707820c7..bddd09d16f 100644
--- a/packages/core/src/Banner/Banner.doc.mjs
+++ b/packages/core/src/Banner/Banner.doc.mjs
@@ -17,6 +17,7 @@ export const docs = {
{guidance: true, description: 'Keep titles short and scannable: "Payment failed" not "There was a problem processing your most recent payment."'},
{guidance: false, description: 'Use Banner for short-lived messages that disappear on their own; use Toast instead.'},
{guidance: false, description: 'Stack multiple banners with the same status; combine related messages into one banner.'},
+ {guidance: true, description: 'Set collapsible={false} when the user needs the content to act on the message, like the list of fields that failed validation. Keep the default toggle when the detail is long enough to bury the banner\u2019s own message.'},
{guidance: true, description: 'Error and warning banners render as role="alert"; info and success render as role="status". Mount an alert banner in response to an event rather than on first paint, so assistive tech has a change to report.'},
{guidance: false, description: 'Rely on the status color or icon alone to carry meaning; say which status it is in the title text, because the icon is decorative to a screen reader.'},
],
@@ -26,7 +27,7 @@ export const docs = {
{name: 'Description', required: false, description: 'Additional detail below the title.'},
{name: 'Action button', required: false, description: 'A button for the user to act on the message, like "Review" or "Retry".'},
{name: 'Dismiss button', required: false, description: 'Lets the user close the banner. Enabled by setting isDismissable.'},
- {name: 'Collapsible content', required: false, description: 'Extra detail that expands below the banner header, like a list of errors.'},
+ {name: 'Content', required: false, description: 'Extra detail below the banner header, like a list of errors. Sits behind an expand/collapse toggle by default; set collapsible={false} to keep it visible.'},
],
},
@@ -94,14 +95,14 @@ export const docs = {
name: 'children',
type: 'ReactNode',
description:
- 'Content rendered in the card-background area below the colored header.',
+ 'Content rendered in the card-background area below the colored header. Sits behind an expand/collapse toggle unless `collapsible={false}`.',
},
{
- name: 'defaultIsExpanded',
- type: 'boolean',
+ name: 'collapsible',
+ type: 'boolean | {defaultIsOpen?: boolean; isOpen?: boolean; onOpenChange?: (isOpen: boolean) => void}',
description:
- 'Whether the content area (children) starts expanded. Only relevant when children are provided.',
- default: 'false',
+ 'Whether the content area (children) sits behind an expand/collapse toggle in the header. On by default, starting collapsed. `false` opts out: children are always visible with no toggle. `{defaultIsOpen: true}` starts open; `{isOpen, onOpenChange}` is controlled. Takes the same CollapsibleConfig as Collapsible.',
+ default: 'true',
},
{
name: 'xstyle',
@@ -154,7 +155,7 @@ export const docsZh = {
{name: 'Description', required: false, description: 'Additional detail below the title.'},
{name: 'Action button', required: false, description: 'A button for the user to act on the message, like "Review" or "Retry".'},
{name: 'Dismiss button', required: false, description: 'Lets the user close the banner. Enabled by setting isDismissable.'},
- {name: 'Collapsible content', required: false, description: 'Extra detail that expands below the banner header, like a list of errors.'},
+ {name: 'Content', required: false, description: 'Extra detail below the banner header, like a list of errors. Sits behind an expand/collapse toggle by default; set collapsible={false} to keep it visible.'},
],
},
props: [
@@ -167,8 +168,8 @@ export const docsZh = {
{name: 'endContent', type: 'ReactNode', description: '渲染在头部区域末端对齐的操作内容,通常是按钮或链接。头部过窄时会整体换行到文本下方,自成一行。'},
{name: 'container', type: "'card' | 'section'", description: '视觉变体:card 带圆角;section 无圆角全宽,适用于页面级场景。', default: "'card'"},
{name: 'elevation', type: "'none' | 'low' | 'med' | 'high'", description: '静止阴影深度。用于悬浮于内容之上的浮动横幅;none 为默认内联横幅。', default: "'none'"},
- {name: 'children', type: 'ReactNode', description: '渲染在彩色头部下方卡片背景区域的内容。'},
- {name: 'defaultIsExpanded', type: 'boolean', description: '内容区域(children)是否初始展开。仅在提供 children 时相关。', default: 'false'},
+ {name: 'children', type: 'ReactNode', description: '渲染在彩色头部下方卡片背景区域的内容。默认位于展开/折叠开关之后,除非设置 collapsible={false}。'},
+ {name: 'collapsible', type: 'boolean | {defaultIsOpen?: boolean; isOpen?: boolean; onOpenChange?: (isOpen: boolean) => void}', description: '内容区域(children)是否位于头部的展开/折叠开关之后。默认开启,且初始为折叠状态。false 表示关闭:内容始终可见且没有开关。{defaultIsOpen: true} 表示初始展开;{isOpen, onOpenChange} 为受控模式。与 Collapsible 使用同一套 CollapsibleConfig。', default: 'true'},
{
name: 'xstyle',
type: 'StyleXStyles',
@@ -230,7 +231,7 @@ export const docsDense = {
{name: 'Description', required: false, description: 'Detail below title.'},
{name: 'Action button', required: false, description: 'CTA like Review or Retry.'},
{name: 'Dismiss button', required: false, description: 'Close button via isDismissable.'},
- {name: 'Collapsible content', required: false, description: 'Expandable detail area.'},
+ {name: 'Content', required: false, description: 'Detail area; behind a toggle unless collapsible={false}.'},
],
},
propDescriptions: {
@@ -243,7 +244,8 @@ export const docsDense = {
endContent: 'end-aligned action in header, typically button/link; wraps to its own row when the header is too narrow',
container: 'card=border-radius; section=full-width no radius for page-level',
elevation: 'resting shadow depth: none|low|med|high; raise for a floating banner',
- children: 'content in card-bg area below colored header',
+ children: 'content in card-bg area below colored header; behind a toggle unless collapsible={false}',
+ collapsible: 'children behind a header toggle; default true=collapsed. false=always visible, no toggle. {defaultIsOpen:true}=starts open, {isOpen,onOpenChange}=controlled',
xstyle: 'StyleX layout customization via stylex.create()',
},
};
diff --git a/packages/core/src/Banner/Banner.test.tsx b/packages/core/src/Banner/Banner.test.tsx
index 371779d663..c092c3e5b2 100644
--- a/packages/core/src/Banner/Banner.test.tsx
+++ b/packages/core/src/Banner/Banner.test.tsx
@@ -184,33 +184,84 @@ describe('Banner', () => {
});
// =========================================================================
- // Collapsible content area
+ // Content area — collapsible by default, `collapsible={false}` opts out
// =========================================================================
- it('hides children by default (collapsed)', () => {
+ it('hides children behind a toggle by default', () => {
render(
<Banner status="info" title="Collapsible">
<div data-testid="child-content">Extra content</div>
</Banner>,
);
+ // The historical default, unchanged: chevron present, content collapsed.
expect(screen.queryByTestId('child-content')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Expand'})).toBeInTheDocument();
+ });
+
+ it('treats an explicit collapsible={true} as the default', () => {
+ render(
+ <Banner status="info" title="Explicit" collapsible>
+ <div data-testid="child-content">Extra content</div>
+ </Banner>,
+ );
+ expect(screen.queryByTestId('child-content')).not.toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Expand'})).toBeInTheDocument();
});
- it('shows children when defaultIsExpanded is true', () => {
+ it('shows children with no toggle for collapsible={false}', () => {
render(
- <Banner status="info" title="Expanded" defaultIsExpanded>
+ <Banner status="info" title="Opted out" collapsible={false}>
<div data-testid="child-content">Extra content</div>
</Banner>,
);
expect(screen.getByTestId('child-content')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Expand'}),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', {name: 'Collapse'}),
+ ).not.toBeInTheDocument();
});
- it('shows expand button when children are provided', () => {
+ it('leaves non-collapsible content out of the disclosure wiring', () => {
render(
- <Banner status="info" title="With Toggle">
- <div>Content</div>
+ <Banner
+ status="info"
+ title="Plain content"
+ isDismissable
+ collapsible={false}>
+ <div data-testid="child-content">Extra content</div>
+ </Banner>,
+ );
+ // No toggle exists, so nothing should carry disclosure state, and the
+ // region needs no id for a button to point at.
+ const dismiss = screen.getByRole('button', {name: 'Dismiss'});
+ expect(dismiss).not.toHaveAttribute('aria-expanded');
+ expect(dismiss).not.toHaveAttribute('aria-controls');
+ expect(
+ screen.getByTestId('child-content').parentElement,
+ ).not.toHaveAttribute('id');
+ });
+
+ it('starts open for collapsible={{defaultIsOpen: true}}', () => {
+ render(
+ <Banner status="info" title="Open" collapsible={{defaultIsOpen: true}}>
+ <div data-testid="child-content">Content</div>
+ </Banner>,
+ );
+ expect(screen.getByTestId('child-content')).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Collapse'})).toBeInTheDocument();
+ });
+
+ it('treats a null collapsible as the default', () => {
+ render(
+ // @ts-expect-error null is outside the prop's type, but JS callers and a
+ // value widened to `| null` still reach this.
+ <Banner status="info" title="Nullish" collapsible={null}>
+ <div data-testid="child-content">Content</div>
</Banner>,
);
+ expect(screen.queryByTestId('child-content')).not.toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Expand'})).toBeInTheDocument();
});
@@ -247,13 +298,38 @@ describe('Banner', () => {
expect(screen.getByRole('button', {name: 'Expand'})).toBeInTheDocument();
});
- it('shows collapse button when defaultIsExpanded', () => {
+ it('reports open-state changes through onOpenChange', async () => {
+ const user = userEvent.setup();
+ const onOpenChange = vi.fn();
render(
- <Banner status="info" title="Expanded" defaultIsExpanded>
- <div>Content</div>
+ <Banner status="info" title="Notify" collapsible={{onOpenChange}}>
+ <div data-testid="child-content">Extra content</div>
</Banner>,
);
- expect(screen.getByRole('button', {name: 'Collapse'})).toBeInTheDocument();
+
+ await user.click(screen.getByRole('button', {name: 'Expand'}));
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ await user.click(screen.getByRole('button', {name: 'Collapse'}));
+ expect(onOpenChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('defers to the consumer when collapsible is controlled', async () => {
+ const user = userEvent.setup();
+ const onOpenChange = vi.fn();
+ render(
+ <Banner
+ status="info"
+ title="Controlled"
+ collapsible={{isOpen: false, onOpenChange}}>
+ <div data-testid="child-content">Extra content</div>
+ </Banner>,
+ );
+
+ // A controlled banner must not move on its own: the click reports, the
+ // content stays hidden until the consumer re-renders with isOpen.
+ await user.click(screen.getByRole('button', {name: 'Expand'}));
+ expect(onOpenChange).toHaveBeenCalledWith(true);
+ expect(screen.queryByTestId('child-content')).not.toBeInTheDocument();
});
it('renders expand button to the left of dismiss button', () => {
@@ -273,7 +349,10 @@ describe('Banner', () => {
it('links the expand toggle to its content region via aria-controls', () => {
render(
- <Banner status="info" title="Controls Test" defaultIsExpanded>
+ <Banner
+ status="info"
+ title="Controls Test"
+ collapsible={{defaultIsOpen: true}}>
<div data-testid="region-content">Region content</div>
</Banner>,
);
@@ -509,9 +588,17 @@ describe('Banner', () => {
<p>Detail</p>
</Banner>,
);
- expect(
- screen.getByRole('button', {name: 'Expand'}),
- ).toBeInTheDocument();
+ expect(screen.getByRole('button', {name: 'Expand'})).toBeInTheDocument();
+ });
+
+ it('renders no content area for children that render nothing', () => {
+ const {container} = render(
+ <Banner status="info" title="Heads up" collapsible={false}>
+ {false}
+ </Banner>,
+ );
+ // Header only — an empty slot must not draw the card-background area.
+ expect(container.firstElementChild?.children).toHaveLength(1);
});
it('renders no description node for a description that renders nothing', () => {
diff --git a/packages/core/src/Banner/Banner.tsx b/packages/core/src/Banner/Banner.tsx
index 13e276b05c..95a6ea5ca8 100644
--- a/packages/core/src/Banner/Banner.tsx
+++ b/packages/core/src/Banner/Banner.tsx
@@ -4,20 +4,24 @@
/**
* @file Banner.tsx
- * @input Uses React useState/useRef/useId, Button, Icon (with registry string names), StyleX
+ * @input Uses React useState/useRef/useId, useCollapsible, Button, Icon (with registry string names), StyleX
* @output Exports Banner component, BannerProps, BannerStatus, BannerContainer types
* @position Core implementation; consumed by index.ts, tested by Banner.test.tsx
*
* Visual structure:
* - Root container: layout-only wrapper (flex column), no visual styling, no theme target
* - Header area (themeProps 'banner'): colored status background with icon, title, description, actions, dismiss
- * - Content area (themeProps 'banner-content'): collapsible card background for additional content (children)
+ * - Content area (themeProps 'banner-content'): card background for additional content (children)
* - Status icon (themeProps 'banner-icon'): the target rides on the default
* <Icon> itself — the element that paints — so 'status:X' overrides reach
* the glyph (#4166); for a custom `icon` node it stays on the layout wrapper
* - No left border accent — color is expressed through the full header background
* - Each visual area owns its own border-radius (no overflow:clip on the container)
- * - When children are provided, a collapse/expand toggle button appears in the end area
+ * - Children are collapsible by default: a toggle appears in the header end
+ * area and the content starts closed. `collapsible={false}` opts out and
+ * pins the content open with no toggle. The whole collapse axis (enabled /
+ * default / controlled) lives on that one prop and is driven by the shared
+ * `useCollapsible` hook rather than local state.
*
* A status added through `BannerStatusMap` augmentation has no entry in the
* status lookups, so it renders with no status fill, no default glyph and the
@@ -55,6 +59,8 @@ import {
easeVars,
shadowVars,
} from '../theme/tokens.stylex';
+import {useCollapsible} from '../Collapsible/useCollapsible';
+import type {CollapsibleConfig} from '../Collapsible/useCollapsible';
import {composeEventHandlers, isRenderable, mergeProps} from '../utils';
import type {Elevation} from '../utils/types';
import {edgeCompSlot} from '../Layout/edgeCompensation.stylex';
@@ -140,15 +146,29 @@ export interface BannerProps extends BaseProps<HTMLDivElement> {
*/
elevation?: Elevation;
/**
- * Whether the content area (children) starts expanded.
- * Only relevant when children are provided.
- * @default false
+ * Whether the content area (children) sits behind an expand/collapse toggle
+ * in the header. On by default, so a banner with children behaves as it
+ * always has.
+ *
+ * - omitted / `true` — collapsible, starts collapsed
+ * - `{defaultIsOpen: true}` — collapsible, starts open
+ * - `{isOpen, onOpenChange}` — controlled by the consumer
+ * - `false` — not collapsible: children are always visible, with no toggle,
+ * no `aria-expanded`, and a content region that stays mounted
+ *
+ * Takes the shared `CollapsibleConfig` so a banner's disclosure is
+ * configured exactly like `Collapsible`'s, rather than through a
+ * Banner-only vocabulary. Banner's default differs from the hook's on one
+ * point — it starts closed, not open — because a banner's message lives in
+ * its header and the content is supplementary.
+ *
+ * @default true
*/
- defaultIsExpanded?: boolean;
+ collapsible?: boolean | CollapsibleConfig;
/**
- * Extra content rendered below the header in a collapsible card-background area.
+ * Extra content rendered below the header in a card-background area.
* Use for rich content like lists, links, or detailed information.
- * When provided, a collapse/expand toggle button appears in the header.
+ * Collapsed behind a toggle unless `collapsible={false}`.
*/
children?: ReactNode;
}
@@ -367,11 +387,12 @@ const elevationStyles = stylex.create({
*
* Two-part visual structure:
* - Header: colored status background with icon, title, description, and actions
- * - Content (optional): collapsible card background area for additional rich content
+ * - Content (optional): card background area for additional rich content
*
- * When children are provided, a collapse/expand chevron button appears in the
- * header end area (to the left of the dismiss button if present). Clicking it
- * toggles the visibility of the content area.
+ * When children are provided, a chevron toggle appears in the header end area
+ * (to the left of the dismiss button if present) and the content starts
+ * collapsed. Pass `collapsible={false}` for content that is always visible,
+ * or a config object to change the initial state or control it.
*
* Manages its own dismissed state internally — the banner hides on dismiss
* even if `onDismiss` is not provided, so product teams don't need to wire
@@ -402,9 +423,14 @@ const elevationStyles = stylex.create({
* <Banner
* status="warning"
* title="Configuration changes"
- * defaultIsExpanded>
+ * collapsible={{defaultIsOpen: true}}>
* <p>Details here...</p>
* </Banner>
+ * <Banner status="error" title="3 fields need attention" collapsible={false}>
+ * <ul>
+ * <li>Email address is invalid</li>
+ * </ul>
+ * </Banner>
* ```
*/
export function Banner({
@@ -417,7 +443,7 @@ export function Banner({
endContent,
container = 'card',
elevation = 'none',
- defaultIsExpanded = false,
+ collapsible = true,
children,
xstyle,
className,
@@ -429,7 +455,26 @@ export function Banner({
}: BannerProps) {
const t = useTranslator();
const [isDismissed, setIsDismissed] = useState(false);
- const [isExpanded, setIsExpanded] = useState(defaultIsExpanded);
+ // The disclosure state machine is the shared one — Banner owns no collapse
+ // state of its own. `collapsible={false}` disables it, and that is what
+ // makes the content permanently visible.
+ //
+ // The one place Banner departs from the hook's defaults: `useCollapsible`
+ // opens by default, a banner starts closed. Its header already carries the
+ // message, so the content is supplementary — and this is the behaviour
+ // Banner has always had.
+ const collapsibleConfig =
+ collapsible != null && typeof collapsible === 'object' ? collapsible : {};
+ const {
+ isEnabled: isCollapsible,
+ isOpen: isExpanded,
+ toggle: handleToggleExpand,
+ } = useCollapsible({
+ isCollapsible: collapsible !== false && {
+ ...collapsibleConfig,
+ defaultIsOpen: collapsibleConfig.defaultIsOpen ?? false,
+ },
+ });
// The element focus came from before it entered the banner. Dismissing
// unmounts the whole banner, dismiss button included, so without a handoff
// the browser drops focus to <body> and a keyboard user loses their place.
@@ -438,7 +483,8 @@ export function Banner({
// Links the expand/collapse toggle to the content region it shows/hides so
// assistive tech can move from the button to its controlled content
// (disclosure pattern). The region is conditionally rendered, so aria-controls
- // below is set only while it's mounted to avoid a dangling reference.
+ // below is set only while it's mounted to avoid a dangling reference. A
+ // non-collapsible banner has no toggle, so neither end of the link is used.
const contentId = useId();
const defaultIconName = defaultIconNames[status];
const role = statusRole[status] ?? FALLBACK_ROLE;
@@ -482,18 +528,19 @@ export function Banner({
}
};
- const handleToggleExpand = () => {
- setIsExpanded(prev => !prev);
- };
-
+ // The toggle exists only for a collapsible banner that actually has content
+ // to disclose.
+ const hasToggle = isCollapsible && hasChildren;
// Show the end area if there are actions, dismiss, or a collapsible toggle
- const showEndArea = isRenderable(endContent) || isDismissable || hasChildren;
+ const showEndArea = isRenderable(endContent) || isDismissable || hasToggle;
// Center items vertically when there's only a title (no description)
// and the banner has action buttons
const hasActions = isRenderable(endContent) || isDismissable;
const isSingleLine = !isRenderable(description) && hasActions;
- const showContent = hasChildren && isExpanded;
+ // Non-collapsible children are always shown; collapsible ones follow the
+ // hook's open state.
+ const showContent = hasChildren && (!isCollapsible || isExpanded);
const isCard = container === 'card';
return (
@@ -575,7 +622,7 @@ export function Banner({
edgeCompSlot.inset(spacingVars['--spacing-2']),
)}>
{endContent}
- {hasChildren && (
+ {hasToggle && (
<Button
variant="ghost"
size="sm"
@@ -623,7 +670,7 @@ export function Banner({
{/* Content area: collapsible card background — theme target ('banner-content') */}
{showContent && (
<div
- id={contentId}
+ id={hasToggle ? contentId : undefined}
{...mergeProps(
themeProps('banner-content', {container, status}),
stylex.props(styles.contentArea, isCard && styles.contentAreaCard),