An open source design system that's fully customizable and agent ready
TypeScript
feat(lab): DialogHeroHeader (#10108)
Cindy Zhang848bbe7c7025
diff --git a/.changeset/astryx-discover-lists-the-lab-dialogheroheader-component.md b/.changeset/astryx-discover-lists-the-lab-dialogheroheader-component.mdnew file mode 100644index 0000000000..3db5d97f13--- /dev/null+++ b/.changeset/astryx-discover-lists-the-lab-dialogheroheader-component.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[feat] `astryx discover` lists the Lab DialogHeroHeader component from `@astryxdesign/lab`. (#4182)+@jiunshinndiff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.jsindex dec6b08451..e63bafa6ed 100644--- a/.github/scripts/story-play-guard.js+++ b/.github/scripts/story-play-guard.js@@ -369,6 +369,20 @@ const TARGETS = [guards:'the rendered RTL wrapper mirrors fixed-track item order while responsive and span geometry remain bounded',},+ {+ component: 'DialogHeroHeader',+ story: 'lab-dialogheroheader--media-bleed-geometry',+ guards:+ 'media reaches the dialog edges at theme-default, 0/2/8 padding, a ' ++ 'theme override, and RTL while the title keeps the cancelled inset',+ },+ {+ component: 'DialogHeroHeader',+ story: 'lab-dialogheroheader--custom-heading-focus-after-rerender',+ guards:+ 'a custom heading keeps focus and keeps naming the open modal while ' ++ 'the header re-renders with a new title element',+ },{component: 'TabList',story: 'core-tablist--full-bleed-geometry',diff --git a/apps/storybook/stories/DialogHeroHeader.stories.tsx b/apps/storybook/stories/DialogHeroHeader.stories.tsxnew file mode 100644index 0000000000..4c124c45aa--- /dev/null+++ b/apps/storybook/stories/DialogHeroHeader.stories.tsx@@ -0,0 +1,622 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DialogHeroHeader.stories.tsx+ * @input DialogHeroHeader and its Dialog, Layout, Heading, and media composition+ * @output Inline visual states, an interactive modal example, and a media+ * bleed geometry guard across Dialog paddings and RTL+ * @position Storybook coverage for the experimental hero header; the geometry+ * story's play function is required CI via story-play-guard.js+ */++import {+ useEffect,+ useId,+ useState,+ type ComponentProps,+ type CSSProperties,+} from 'react';+import type {Meta, StoryObj} from '@storybook/react';+import {DialogHeroHeader} from '@astryxdesign/lab';+import {Dialog} from '@astryxdesign/core/Dialog';+import {+ Layout,+ LayoutContent,+ LayoutFooter,+ HStack,+} from '@astryxdesign/core/Layout';+import {Button} from '@astryxdesign/core/Button';+import {Heading} from '@astryxdesign/core/Heading';+import {Icon} from '@astryxdesign/core/Icon';+import {Text} from '@astryxdesign/core/Text';+import * as stylex from '@stylexjs/stylex';++const styles = stylex.create({+ heroSvg: {+ display: 'block',+ },+});++// Self-contained stand-in for a hero image / illustration. A real app would+// pass an <img>, <video>, or illustration component sized to fill the slot.+function HeroMedia({mode = 'dark'}: {mode?: 'dark' | 'light'}) {+ const gradientId = useId();+ const [from, to, accent] =+ mode === 'dark'+ ? ['#1c2340', '#3b2d5e', '#8ba7ff']+ : ['#e8ecfb', '#f6e9f2', '#5b74d6'];+ return (+ <svg+ viewBox="0 0 400 160"+ width="100%"+ height="160"+ preserveAspectRatio="xMidYMid slice"+ aria-hidden="true"+ {...stylex.props(styles.heroSvg)}>+ <defs>+ <linearGradient id={gradientId} x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stopColor={from} />+ <stop offset="100%" stopColor={to} />+ </linearGradient>+ </defs>+ <rect width="400" height="160" fill={`url(#${gradientId})`} />+ <circle cx="330" cy="40" r="52" fill={accent} opacity="0.35" />+ <circle cx="70" cy="140" r="70" fill={accent} opacity="0.25" />+ <circle cx="200" cy="80" r="34" fill={accent} opacity="0.55" />+ </svg>+ );+}++const meta: Meta<typeof DialogHeroHeader> = {+ title: 'Lab/DialogHeroHeader',+ component: DialogHeroHeader,+ tags: ['autodocs'],+};++export default meta;+type Story = StoryObj<typeof DialogHeroHeader>;++/**+ * The hero header drops into Layout's header slot exactly like DialogHeader.+ * The media bleeds to the dialog's edges; the close button overlays its+ * top-trailing corner. `mediaMode="dark"` composes MediaTheme so the close+ * button stays legible over the dark artwork.+ */+export const Basic: Story = {+ render: () => (+ <Dialog isOpen isInline onOpenChange={() => {}}>+ <Layout+ header={+ <DialogHeroHeader+ title="Welcome aboard"+ media={<HeroMedia mode="dark" />}+ mediaMode="dark"+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ Set up your workspace in three quick steps. You can change any of+ this later in Settings.+ </Text>+ </LayoutContent>+ }+ footer={+ <LayoutFooter>+ <HStack gap={2} hAlign="end">+ <Button label="Skip" variant="secondary" />+ <Button label="Get started" variant="primary" />+ </HStack>+ </LayoutFooter>+ }+ />+ </Dialog>+ ),+};++/**+ * Light media inverts the overlay treatment: `mediaMode="light"` gives the+ * close button dark, contrast-safe tokens.+ */+export const LightMedia: Story = {+ render: () => (+ <Dialog isOpen isInline onOpenChange={() => {}}>+ <Layout+ header={+ <DialogHeroHeader+ title="New in this release"+ media={<HeroMedia mode="light" />}+ mediaMode="light"+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ Charts now support streaming data, and the command palette learned+ fuzzy matching.+ </Text>+ </LayoutContent>+ }+ />+ </Dialog>+ ),+};++/**+ * `startContent` renders inline before the title; `maxLines` truncates long+ * auto-wrapped titles with an ellipsis.+ */+export const StartContentAndTruncation: Story = {+ render: () => (+ <Dialog isOpen isInline onOpenChange={() => {}}>+ <Layout+ header={+ <DialogHeroHeader+ title="A launch announcement with a title long enough to need truncation in a narrow dialog"+ media={<HeroMedia mode="dark" />}+ mediaMode="dark"+ startContent={<Icon icon="info" size="sm" />}+ maxLines={1}+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ The full title stays available to screen readers and in the+ truncation tooltip.+ </Text>+ </LayoutContent>+ }+ />+ </Dialog>+ ),+};++/**+ * When the artwork carries the message, hide the title row visually with+ * `isTitleHidden`. The title still names the dialog for screen readers.+ * Passing a Heading element instead of a string customizes the treatment.+ */+export const HiddenTitleAndCustomHeading: Story = {+ render: () => (+ <HStack gap={4} wrap="wrap">+ <Dialog isOpen isInline onOpenChange={() => {}} width={320}>+ <Layout+ header={+ <DialogHeroHeader+ title="Spring theme refresh"+ media={<HeroMedia mode="light" />}+ mediaMode="light"+ isTitleHidden+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ The media speaks for itself; the hidden title still names the+ dialog.+ </Text>+ </LayoutContent>+ }+ />+ </Dialog>+ <Dialog isOpen isInline onOpenChange={() => {}} width={320}>+ <Layout+ header={+ <DialogHeroHeader+ title={+ <Heading level={2} type="display-3">+ Big moment+ </Heading>+ }+ media={<HeroMedia mode="dark" />}+ mediaMode="dark"+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ A caller-provided Heading element renders as-is for custom+ treatments.+ </Text>+ </LayoutContent>+ }+ />+ </Dialog>+ </HStack>+ ),+};++/**+ * Full modal behavior: the title receives focus on open and names the dialog+ * via aria-labelledby; Escape and the overlaid close button both close.+ */+export const Modal: Story = {+ render: function ModalExample() {+ const [isOpen, setIsOpen] = useState(false);+ return (+ <>+ <Button+ label="Open hero dialog"+ variant="secondary"+ onClick={() => setIsOpen(true)}+ />+ <Dialog isOpen={isOpen} onOpenChange={setIsOpen}>+ <Layout+ header={+ <DialogHeroHeader+ title="Welcome aboard"+ media={<HeroMedia mode="dark" />}+ mediaMode="dark"+ onOpenChange={setIsOpen}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ Set up your workspace in three quick steps.+ </Text>+ </LayoutContent>+ }+ footer={+ <LayoutFooter>+ <HStack gap={2} hAlign="end">+ <Button+ label="Get started"+ variant="primary"+ onClick={() => setIsOpen(false)}+ />+ </HStack>+ </LayoutFooter>+ }+ />+ </Dialog>+ </>+ );+ },+};++/** Optional close controls and divider follow the surrounding Layout. */+export const WithoutCloseButton: Story = {+ render: () => (+ <Dialog isOpen isInline onOpenChange={() => {}}>+ <Layout+ defaultHasDividers+ header={+ <DialogHeroHeader+ title="A new view of your workspace"+ media={<HeroMedia />}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ Close controls are supplied only when needed.+ </Text>+ </LayoutContent>+ }+ />+ </Dialog>+ ),+};++/** Logical positioning keeps the overlay on the trailing edge in RTL. */+export const RightToLeft: Story = {+ render: () => (+ <div dir="rtl">+ <Dialog isOpen isInline onOpenChange={() => {}} padding={8}>+ <Layout+ header={+ <DialogHeroHeader+ title="مرحبًا بك"+ media={<HeroMedia mode="light" />}+ mediaMode="light"+ startContent={<Icon icon="info" size="sm" />}+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">جهّز مساحة عملك في ثلاث خطوات بسيطة.</Text>+ </LayoutContent>+ }+ />+ </Dialog>+ </div>+ ),+};++type MediaBleedFixture = {+ id: string;+ dir: 'ltr' | 'rtl';+ padding?: ComponentProps<typeof Dialog>['padding'];+ /** Public theme property set on an ancestor instead of the `padding` prop. */+ themePadding?: number;+};++/**+ * Representative Dialog paddings: the theme default, the zero and small/large+ * `padding` steps, a public theme override that is not a spacing step, and the+ * same large and theme paths under RTL.+ */+const MEDIA_BLEED_FIXTURES: MediaBleedFixture[] = [+ {id: 'theme-default', dir: 'ltr'},+ {id: 'padding-0', dir: 'ltr', padding: 0},+ {id: 'padding-2', dir: 'ltr', padding: 2},+ {id: 'padding-8', dir: 'ltr', padding: 8},+ {id: 'theme-override', dir: 'ltr', themePadding: 20},+ {id: 'rtl-padding-8', dir: 'rtl', padding: 8},+ {id: 'rtl-theme-override', dir: 'rtl', themePadding: 20},+];++/** Sets Dialog's public theme padding the way a theme would. */+function themePaddingStyle(+ padding: number | undefined,+): (CSSProperties & {'--astryx-dialog-padding': string}) | undefined {+ if (padding == null) {+ return undefined;+ }+ return {'--astryx-dialog-padding': `${padding}px`};+}++function assertBleedGeometry(label: string, actual: number, expected: number) {+ if (Math.abs(actual - expected) > 0.5) {+ throw new Error(+ `${label}: expected ${expected.toFixed(2)}px, received ${actual.toFixed(2)}px`,+ );+ }+}++/**+ * Browser geometry guard for the media's edge compensation, run in CI by+ * `.github/scripts/story-play-guard.js`. In every fixture the media area must+ * reach the dialog surface's inline-start, inline-end, and block-start edges+ * while the title stays inset by the header padding the media cancels. Edges+ * are measured logically, so the RTL fixtures prove the same contract with+ * inline-start on the right. Expected insets are read back from the rendered+ * DOM; only the theme override's declared value is restated.+ */+export const MediaBleedGeometry: Story = {+ render: () => (+ <div style={{display: 'flex', flexWrap: 'wrap', gap: 24}}>+ {MEDIA_BLEED_FIXTURES.map(({id, dir, padding, themePadding}) => (+ <div+ key={id}+ dir={dir}+ data-media-bleed-fixture={id}+ style={themePaddingStyle(themePadding)}>+ <Dialog+ isOpen+ isInline+ onOpenChange={() => {}}+ padding={padding}+ width={320}+ data-media-bleed-surface="">+ <Layout+ header={+ <DialogHeroHeader+ title={id}+ media={<HeroMedia mode="dark" />}+ mediaMode="dark"+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">Media bleed fixture</Text>+ </LayoutContent>+ }+ />+ </Dialog>+ </div>+ ))}+ </div>+ ),+ play: async ({canvasElement}) => {+ await document.fonts.ready;+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );++ const insets = new Map<string, number>();+ for (const {id, dir, themePadding} of MEDIA_BLEED_FIXTURES) {+ const fixture = canvasElement.querySelector<HTMLElement>(+ `[data-media-bleed-fixture="${id}"]`,+ );+ const surface = fixture?.querySelector<HTMLElement>(+ '[data-media-bleed-surface]',+ );+ const mediaArea = fixture?.querySelector('svg')?.parentElement;+ const headerBox = mediaArea?.parentElement;+ const title = fixture?.querySelector<HTMLElement>('h2');+ if (!surface || !mediaArea || !headerBox || !title) {+ throw new Error(`${id}: media bleed fixture did not render`);+ }++ const surfaceRect = surface.getBoundingClientRect();+ const fromStart = (x: number) =>+ dir === 'rtl' ? surfaceRect.right - x : x - surfaceRect.left;+ const fromEnd = (x: number) =>+ dir === 'rtl' ? x - surfaceRect.left : surfaceRect.right - x;+ const startEdge = (rect: DOMRect) =>+ dir === 'rtl' ? rect.right : rect.left;+ const endEdge = (rect: DOMRect) =>+ dir === 'rtl' ? rect.left : rect.right;++ const mediaRect = mediaArea.getBoundingClientRect();+ const headerRect = headerBox.getBoundingClientRect();+ const titleRect = title.getBoundingClientRect();+ const headerStyle = getComputedStyle(headerBox);+ const inset =+ fromStart(startEdge(headerRect)) ++ Number.parseFloat(headerStyle.paddingInlineStart);+ const endInset =+ fromEnd(endEdge(headerRect)) ++ Number.parseFloat(headerStyle.paddingInlineEnd);+ const blockInset =+ headerRect.top -+ surfaceRect.top ++ Number.parseFloat(headerStyle.paddingBlockStart);++ // The media cancels exactly the padding around it on its three edges.+ assertBleedGeometry(+ `${id} media inline-start`,+ fromStart(startEdge(mediaRect)),+ 0,+ );+ assertBleedGeometry(+ `${id} media inline-end`,+ fromEnd(endEdge(mediaRect)),+ 0,+ );+ assertBleedGeometry(+ `${id} media block-start`,+ mediaRect.top - surfaceRect.top,+ 0,+ );+ // ...while the title keeps that padding, so the fixture is not vacuous.+ assertBleedGeometry(+ `${id} title inline-start`,+ fromStart(startEdge(titleRect)),+ inset,+ );+ if (+ id !== 'padding-0' &&+ (inset <= 0 || endInset <= 0 || blockInset <= 0)+ ) {+ throw new Error(+ `${id}: expected nonzero header padding to cancel, received ${inset}/${endInset}/${blockInset}px`,+ );+ }+ if (themePadding != null) {+ assertBleedGeometry(`${id} theme inset`, inset, themePadding);+ }+ insets.set(id, inset);+ }++ // Padding steps must actually move the inset the media cancels.+ const zero = insets.get('padding-0') ?? Number.NaN;+ const small = insets.get('padding-2') ?? Number.NaN;+ const large = insets.get('padding-8') ?? Number.NaN;+ assertBleedGeometry('padding-0 inset', zero, 0);+ if (!(small > zero && large > small)) {+ throw new Error(+ `padding steps did not order the insets: 0=${zero}, 2=${small}, 8=${large}`,+ );+ }+ assertBleedGeometry(+ 'rtl padding-8 mirrors ltr',+ insets.get('rtl-padding-8') ?? Number.NaN,+ large,+ );+ },+};++const CUSTOM_HEADING_RERENDERS = 3;++async function waitForCondition(+ isMet: () => boolean,+ description: string,+): Promise<void> {+ const deadline = performance.now() + 5000;+ while (!isMet()) {+ if (performance.now() > deadline) {+ throw new Error(`timed out waiting until ${description}`);+ }+ await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));+ }+}++function describeElement(element: Element | null): string {+ if (element == null) {+ return 'null';+ }+ const id = element.id === '' ? '' : `#${element.id}`;+ return `<${element.tagName.toLowerCase()}${id}>`;+}++/**+ * Regression fixture for a caller-provided heading in an open modal. The+ * story re-renders the header after the modal opens, and every render passes+ * a new `title` element. Focus must stay on the heading: Chromium blurs a+ * focused element whose tabindex is removed, so a handshake that removes and+ * adds its attributes on each render moves focus to the page body. The+ * heading must also keep naming the dialog. Kept off the docs page because+ * the modal opens on load.+ */+export const CustomHeadingFocusAfterRerender: Story = {+ tags: ['!autodocs'],+ render: function CustomHeadingFocusAfterRerenderExample() {+ const [renderCount, setRenderCount] = useState(0);+ useEffect(() => {+ if (renderCount >= CUSTOM_HEADING_RERENDERS) {+ return;+ }+ const timer = setTimeout(() => setRenderCount(count => count + 1), 50);+ return () => clearTimeout(timer);+ }, [renderCount]);+ return (+ <Dialog isOpen onOpenChange={() => {}}>+ <Layout+ header={+ <DialogHeroHeader+ title={+ <Heading level={1} type="display-3">+ Big moment+ </Heading>+ }+ media={<HeroMedia mode="dark" />}+ mediaMode="dark"+ onOpenChange={() => {}}+ />+ }+ content={+ <LayoutContent>+ <Text type="body">+ <span data-rerender-count={renderCount}>+ Re-renders after opening: {renderCount}+ </span>+ </Text>+ </LayoutContent>+ }+ />+ </Dialog>+ );+ },+ play: async ({canvasElement}) => {+ const doc = canvasElement.ownerDocument;+ await waitForCondition(+ () =>+ doc.querySelector(+ `[data-rerender-count="${CUSTOM_HEADING_RERENDERS}"]`,+ ) != null,+ `the header re-rendered ${CUSTOM_HEADING_RERENDERS} times after opening`,+ );+ await new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ );+ const heading = doc.querySelector<HTMLElement>('dialog[open] h1');+ if (heading == null) {+ throw new Error('the open modal did not render the custom h1 heading');+ }+ if (doc.activeElement !== heading) {+ throw new Error(+ `focus left the custom heading after a re-render: ${describeElement(doc.activeElement)}`,+ );+ }+ const dialog = heading.closest('dialog');+ if (+ heading.id === '' ||+ dialog?.getAttribute('aria-labelledby') !== heading.id+ ) {+ throw new Error(+ `the custom heading no longer names the dialog: heading id "${heading.id}", aria-labelledby "${dialog?.getAttribute('aria-labelledby')}"`,+ );+ }+ },+};diff --git a/internal/shadcn-registry/routes.lock.json b/internal/shadcn-registry/routes.lock.jsonindex 7fea2c9e01..8dfbfac7f7 100644--- a/internal/shadcn-registry/routes.lock.json+++ b/internal/shadcn-registry/routes.lock.json@@ -602,6 +602,11 @@"path": "components/lab/comments","aliases": []},+ {+ "name": "component-lab-dialog-hero-header",+ "path": "components/lab/dialog-hero-header",+ "aliases": []+ },{"name": "component-lab-diff-viewer","path": "components/lab/diff-viewer",diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.jsonindex 7344878198..939c6cd8d0 100644--- a/packages/cli/assets/discover/official-packages.json+++ b/packages/cli/assets/discover/official-packages.json@@ -128,6 +128,10 @@"kind": "component","name": "CommentThread"},+ {+ "kind": "component",+ "name": "DialogHeroHeader"+ },{"kind": "component","name": "DiffViewer"diff --git a/packages/lab/src/DialogHeroHeader/DialogHeroHeader.doc.mjs b/packages/lab/src/DialogHeroHeader/DialogHeroHeader.doc.mjsnew file mode 100644index 0000000000..6be1939d0a--- /dev/null+++ b/packages/lab/src/DialogHeroHeader/DialogHeroHeader.doc.mjs@@ -0,0 +1,229 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file DialogHeroHeader.doc.mjs+ * @input DialogHeroHeader props and Dialog composition+ * @output Consumer documentation for the canary-only hero header+ * @position Lab component documentation consumed by the CLI and docsite+ */++/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */++export const docs = {+ name: 'DialogHeroHeader',+ displayName: 'Dialog Hero Header',+ import: '@astryxdesign/lab',+ group: 'DialogHeroHeader',+ category: 'Overlay',+ keywords: [+ 'dialog',+ 'modal',+ 'header',+ 'hero',+ 'media',+ 'image',+ 'illustration',+ 'onboarding',+ 'marketing',+ 'featured',+ 'close button',+ 'title',+ ],+ description:+ 'Experimental hero-style header for Dialog, available from @astryxdesign/lab@canary: a full-bleed media slot above the title with the close button overlaid on the media. The high-emphasis sibling of DialogHeader for featured, marketing, or onboarding dialogs.',+ props: [+ {+ name: 'title',+ type: 'string | ReactElement',+ description:+ 'Dialog title. A string is wrapped in a level 2 Heading (matching DialogHeader); pass a pre-styled Heading element to customize the treatment. Provides the accessible label for the parent Dialog via aria-labelledby unless the Dialog has an explicit label. The visible title is the default initial focus target; another eligible descendant autofocus request takes priority. A custom Heading receives the label and focus on its own element; if it sets its own id, name the Dialog with aria-labelledby.',+ required: true,+ },+ {+ name: 'media',+ type: 'ReactNode',+ description:+ "Full-bleed visual rendered above the title (image, illustration, or icon). Stretches to the dialog's padded edges; the close button overlays its top-trailing corner. Size the media itself (e.g. width 100%) to fill the slot.",+ required: true,+ },+ {+ name: 'mediaMode',+ type: "'light' | 'dark'",+ description:+ "Luminance of the media surface. Composes MediaTheme under the hood so content overlaid on the media (the close button) picks up contrast-safe inverted tokens: 'dark' media gets light overlay content, 'light' media gets dark. Omit to keep ambient theme tokens.",+ },+ {+ name: 'isTitleHidden',+ type: 'boolean',+ description:+ 'Visually hides the title row while keeping it available to screen readers, so the dialog stays named by the title.',+ default: 'false',+ },+ {+ name: 'startContent',+ type: 'ReactNode',+ description:+ 'Content placed before the title (e.g. an icon), inline with the heading.',+ },+ {+ name: 'maxLines',+ type: 'number',+ description:+ 'Max lines before the title truncates with an ellipsis. Only applies when title is a string (auto-wrapped in a Heading).',+ },+ {+ name: 'onOpenChange',+ type: '(isOpen: boolean) => unknown',+ description:+ 'Close button callback, called with false when the close button is clicked. If not provided, no close button is rendered. Same contract as DialogHeader.',+ },+ {+ name: 'hasDivider',+ type: 'boolean',+ description:+ "Adds a themed border at the bottom edge. Defaults to the parent Layout's defaultHasDividers context value.",+ },+ ],+ usage: {+ description:+ "Drop into Layout's header slot inside a Dialog, exactly like DialogHeader. Use when the dialog opens onto a featured, marketing, or onboarding moment where the compact DialogHeader is too understated. The media bleeds to the dialog's edges automatically and the close button floats over its top-trailing corner. The visible title is the default initial focus target; inline previews do not move focus. Install @astryxdesign/lab@canary with @astryxdesign/core@canary and import both packages’ CSS. Lab APIs can change between canary versions.",+ bestPractices: [+ {+ guidance: true,+ description:+ 'Set mediaMode to match the media\'s luminance so the overlaid close button stays legible: dark imagery needs mediaMode="dark".',+ },+ {+ guidance: true,+ description:+ 'Size the media content to fill the slot (width 100% for images); the slot itself only positions and bleeds.',+ },+ {+ guidance: true,+ description:+ 'Keep actions (CTAs) in LayoutFooter; the hero header takes no actions slot.',+ },+ {+ guidance: true,+ description:+ 'Use isTitleHidden when the media already communicates the message visually; the title still names the dialog for screen readers.',+ },+ {+ guidance: false,+ description:+ 'Use for routine confirmations or forms; use the compact DialogHeader instead.',+ },+ {+ guidance: false,+ description:+ 'Pass decorative media without an empty alt: use alt="" on purely decorative images so screen readers skip them.',+ },+ ],+ },+ examples: [+ {+ label: 'Onboarding dialog',+ code: `import {DialogHeroHeader} from '@astryxdesign/lab';+import '@astryxdesign/core/astryx.css';+import '@astryxdesign/lab/lab.css';++const [isOpen, setIsOpen] = useState(true);+<Dialog isOpen={isOpen} onOpenChange={setIsOpen}>+ <Layout+ header={+ <DialogHeroHeader+ title="Welcome aboard"+ media={<img src={heroImage} alt="" width="100%" />}+ mediaMode="dark"+ onOpenChange={setIsOpen}+ />+ }+ content={<LayoutContent>Get started in three steps.</LayoutContent>}+ footer={+ <LayoutFooter hasDivider>+ <Button label="Get started" variant="primary" />+ </LayoutFooter>+ }+ />+</Dialog>`,+ },+ {+ label: 'Hidden title (media carries the message)',+ code: `<DialogHeroHeader+ title="Product tour"+ media={<AnnouncementIllustration />}+ isTitleHidden+ onOpenChange={setIsOpen}+/>`,+ },+ ],+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsZh = {+ usage: {+ description:+ '像 DialogHeader 一样放入 Dialog 内 Layout 的 header 插槽。当对话框呈现精选、营销或引导场景,紧凑的 DialogHeader 不够醒目时使用。媒体自动延伸到对话框边缘,关闭按钮浮动在媒体的尾部上角。可见标题是默认的初始焦点目标;内联预览不会移动焦点。安装 @astryxdesign/lab@canary 和 @astryxdesign/core@canary,并导入两个包的 CSS。Lab API 可能在 canary 版本之间变化。',+ bestPractices: [+ {+ guidance: true,+ description:+ '让 mediaMode 与媒体的明暗匹配,保证浮动关闭按钮清晰可读:深色图片需要 mediaMode="dark"。',+ },+ {+ guidance: true,+ description:+ '让媒体内容填满插槽(图片用 width 100%);插槽本身只负责定位和延伸。',+ },+ {+ guidance: true,+ description:+ '操作按钮(CTA)放在 LayoutFooter;hero 头部不提供操作插槽。',+ },+ {+ guidance: true,+ description:+ '当媒体已经在视觉上传达信息时使用 isTitleHidden;标题仍会为屏幕阅读器命名对话框。',+ },+ {+ guidance: false,+ description: '用于常规确认或表单;请改用紧凑的 DialogHeader。',+ },+ {+ guidance: false,+ description:+ '装饰性媒体缺少空 alt;纯装饰图片请使用 alt="" 让屏幕阅读器跳过。',+ },+ ],+ },+};++/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */+export const docsDense = {+ description:+ 'canary-only lab hero Dialog header: full-bleed media slot + title, close button overlaid on media (MediaTheme via mediaMode)',+ usage: {+ description:+ 'High-emphasis sibling of DialogHeader for featured/marketing/onboarding dialogs. Drops into Layout header slot; media bleeds to dialog edges; title names the dialog; visible title is the default initial focus target. Import from @astryxdesign/lab and load core + lab CSS; install both packages at @canary.',+ bestPractices: [+ {+ guidance: true,+ description:+ 'Match mediaMode to the media luminance for close-button contrast.',+ },+ {+ guidance: true,+ description: 'Size media to fill the slot (width 100%).',+ },+ {guidance: true, description: 'Keep CTAs in LayoutFooter.'},+ {+ guidance: true,+ description:+ 'Use isTitleHidden when the media carries the message; SR name is kept.',+ },+ {+ guidance: false,+ description: 'Use for routine confirmations/forms; use DialogHeader.',+ },+ ],+ },+};diff --git a/packages/lab/src/DialogHeroHeader/DialogHeroHeader.test.tsx b/packages/lab/src/DialogHeroHeader/DialogHeroHeader.test.tsxnew file mode 100644index 0000000000..de540915bc--- /dev/null+++ b/packages/lab/src/DialogHeroHeader/DialogHeroHeader.test.tsx@@ -0,0 +1,575 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DialogHeroHeader.test.tsx+ * @input Uses vitest, @testing-library/react, DialogHeroHeader, core Dialog+ * @output Tests for header rendering, modal focus ownership, accessible naming,+ * and close-button identity across media changes+ * @position Lab testing; validates DialogHeroHeader.tsx implementation+ *+ * SYNC: When DialogHeroHeader.tsx changes, update tests to match new behavior+ */++import {useEffect, useState} from 'react';+import {describe, it, expect, vi, beforeEach} from 'vitest';+import {render, screen, waitFor} from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import {Dialog} from '@astryxdesign/core/Dialog';+import {Heading} from '@astryxdesign/core/Heading';+import {LayoutDividerContext} from '@astryxdesign/core/Layout';+import {DialogHeroHeader} from './DialogHeroHeader';++// Mock dialog methods since they're not fully implemented in jsdom+beforeEach(() => {+ HTMLDialogElement.prototype.showModal = vi.fn(function (+ this: HTMLDialogElement,+ ) {+ this.setAttribute('open', '');+ });+ HTMLDialogElement.prototype.close = vi.fn(function (this: HTMLDialogElement) {+ this.removeAttribute('open');+ });+});++describe('DialogHeroHeader', () => {+ it('renders a string title as an h2 heading', () => {+ render(+ <DialogHeroHeader title="Welcome aboard" media={<div>media</div>} />,+ );+ const heading = screen.getByRole('heading', {+ level: 2,+ name: 'Welcome aboard',+ });+ expect(heading.tagName).toBe('H2');+ });++ it('renders a caller-provided Heading element as-is', () => {+ render(+ <DialogHeroHeader+ title={<Heading level={3}>Custom heading</Heading>}+ media={<div>media</div>}+ />,+ );+ expect(+ screen.getByRole('heading', {level: 3, name: 'Custom heading'}),+ ).toBeInTheDocument();+ expect(screen.queryByRole('heading', {level: 2})).not.toBeInTheDocument();+ });++ it('renders the media slot', () => {+ render(+ <DialogHeroHeader+ title="Title"+ media={<img alt="Illustration" src="hero.png" />}+ />,+ );+ expect(screen.getByRole('img', {name: 'Illustration'})).toBeInTheDocument();+ });++ it('renders startContent before the title', () => {+ render(+ <DialogHeroHeader+ title="Title"+ media={<div>media</div>}+ startContent={<span>start</span>}+ />,+ );+ expect(screen.getByText('start')).toBeInTheDocument();+ });++ it('does not move page focus when rendered outside a Dialog', () => {+ render(<DialogHeroHeader title="Title" media={<div>media</div>} />);+ expect(document.activeElement).toBe(document.body);+ });++ describe('close button', () => {+ it('renders when onOpenChange is provided', () => {+ render(+ <DialogHeroHeader+ title="Title"+ media={<div>media</div>}+ onOpenChange={() => {}}+ />,+ );+ expect(screen.getByRole('button', {name: /close/i})).toBeInTheDocument();+ });++ it('does not render when onOpenChange is not provided', () => {+ render(<DialogHeroHeader title="Title" media={<div>media</div>} />);+ expect(+ screen.queryByRole('button', {name: /close/i}),+ ).not.toBeInTheDocument();+ });++ it('calls onOpenChange(false) when clicked', async () => {+ const user = userEvent.setup();+ const handleOpenChange = vi.fn();+ render(+ <DialogHeroHeader+ title="Title"+ media={<div>media</div>}+ onOpenChange={handleOpenChange}+ />,+ );+ await user.click(screen.getByRole('button', {name: /close/i}));+ expect(handleOpenChange).toHaveBeenCalledTimes(1);+ expect(handleOpenChange).toHaveBeenCalledWith(false);+ });+ });++ describe('mediaMode', () => {+ it('preserves the focused close button across media-mode changes', () => {+ const props = {+ title: 'Title',+ media: <div>media</div>,+ onOpenChange: vi.fn(),+ };+ const {rerender} = render(<DialogHeroHeader {...props} />);+ const button = screen.getByRole('button', {name: /close/i});+ button.focus();+ for (const mediaMode of ['dark', 'light', undefined] as const) {+ rerender(<DialogHeroHeader {...props} mediaMode={mediaMode} />);+ expect(screen.getByRole('button', {name: /close/i})).toBe(button);+ expect(button).toHaveFocus();+ }+ });++ it('wraps the close button in a MediaTheme surface', () => {+ const {container} = render(+ <DialogHeroHeader+ title="Title"+ media={<div>media</div>}+ mediaMode="dark"+ onOpenChange={() => {}}+ />,+ );+ const surface = container.querySelector('[data-astryx-media="dark"]');+ expect(surface).not.toBeNull();+ expect(surface).toContainElement(+ screen.getByRole('button', {name: /close/i}),+ );+ });++ it('applies no MediaTheme surface when omitted', () => {+ const {container} = render(+ <DialogHeroHeader+ title="Title"+ media={<div>media</div>}+ onOpenChange={() => {}}+ />,+ );+ expect(container.querySelector('[data-astryx-media]')).toBeNull();+ });+ });++ describe('isTitleHidden', () => {+ it('keeps the title in the accessibility tree', () => {+ render(+ <DialogHeroHeader+ title="Title"+ media={<div>media</div>}+ isTitleHidden+ />,+ );+ expect(+ screen.getByRole('heading', {level: 2, name: 'Title'}),+ ).toBeInTheDocument();+ });++ it('changes the title row presentation', () => {+ const {container: hidden} = render(+ <DialogHeroHeader+ title="Same title"+ media={<div>media</div>}+ isTitleHidden+ />,+ );+ const {container: visible} = render(+ <DialogHeroHeader title="Same title" media={<div>media</div>} />,+ );+ const hiddenRow = hidden.querySelector('h2')?.parentElement;+ const visibleRow = visible.querySelector('h2')?.parentElement;+ // The hidden variant nests the row inside a VisuallyHidden container.+ expect(hiddenRow?.parentElement?.className).not.toBe(+ visibleRow?.parentElement?.className,+ );+ });+ });++ describe('inside Dialog', () => {+ it('focuses the visible title only after opening and restores the invoker on close', () => {+ const trigger = document.createElement('button');+ document.body.append(trigger);+ trigger.focus();+ const focusStates: boolean[] = [];+ const recordFocus = (event: FocusEvent) => {+ const target = event.target as HTMLElement;+ const dialog = target.closest('dialog');+ if (dialog) {+ focusStates.push(dialog.open);+ }+ };+ document.addEventListener('focusin', recordFocus);+ try {+ const {rerender} = render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader title="Welcome" media={<div>media</div>} />+ </Dialog>,+ );+ expect(screen.getByRole('heading', {name: 'Welcome'})).toHaveFocus();+ expect(focusStates.length).toBeGreaterThan(0);+ expect(focusStates.every(Boolean)).toBe(true);+ rerender(+ <Dialog isOpen={false} onOpenChange={() => {}}>+ {null}+ </Dialog>,+ );+ expect(trigger).toHaveFocus();+ } finally {+ document.removeEventListener('focusin', recordFocus);+ trigger.remove();+ }+ });++ it('uses the title alone as the accessible name, including custom headings', () => {+ const {rerender} = render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title="Welcome"+ startContent={<span>New</span>}+ media={<div>media</div>}+ />+ </Dialog>,+ );+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Welcome');+ rerender(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title={<Heading level={3}>Custom</Heading>}+ startContent={<span>New</span>}+ media={<div>media</div>}+ />+ </Dialog>,+ );+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Custom');+ expect(screen.getByRole('heading', {level: 3})).toHaveTextContent(+ 'Custom',+ );+ });++ it('focuses and labels a custom heading element itself after opening', () => {+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title={<Heading level={1}>Custom</Heading>}+ startContent={<span>New</span>}+ media={<div>media</div>}+ />+ </Dialog>,+ );+ const heading = screen.getByRole('heading', {level: 1, name: 'Custom'});+ // Post-open focus lands on the heading, so it keeps its role and name.+ expect(document.activeElement).toBe(heading);+ expect(screen.getByRole('dialog')).toHaveAttribute(+ 'aria-labelledby',+ heading.id,+ );+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Custom');+ // The layout slot around the heading takes no part in the handshake.+ const slot = heading.parentElement as HTMLElement;+ expect(slot).not.toHaveAttribute('id');+ expect(slot).not.toHaveAttribute('tabindex');+ expect(slot).not.toHaveAttribute('data-autofocus');+ });++ it("keeps a custom heading's own id and tabIndex", () => {+ render(+ <Dialog isOpen onOpenChange={() => {}} aria-labelledby="own-title">+ <DialogHeroHeader+ title={+ <Heading level={2} id="own-title" tabIndex={0}>+ Own+ </Heading>+ }+ media={<div>media</div>}+ />+ </Dialog>,+ );+ const heading = screen.getByRole('heading', {name: 'Own'});+ expect(heading).toHaveAttribute('id', 'own-title');+ expect(heading).toHaveAttribute('tabindex', '0');+ expect(heading).toHaveFocus();+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Own');+ });++ it.each([+ ['inline', {isInline: true}, {}],+ ['hidden', {}, {isTitleHidden: true}],+ ] as const)(+ 'does not request focus for a custom heading when %s',+ (_, dialogProps, headerProps) => {+ render(+ <Dialog isOpen onOpenChange={() => {}} {...dialogProps}>+ <DialogHeroHeader+ title={<Heading level={3}>Custom</Heading>}+ media={<div>media</div>}+ {...headerProps}+ />+ </Dialog>,+ );+ const heading = screen.getByRole('heading', {level: 3});+ expect(heading).not.toHaveFocus();+ expect(heading).not.toHaveAttribute('tabindex');+ expect(heading).not.toHaveAttribute('data-autofocus');+ expect(heading).toHaveAttribute('id');+ },+ );++ it('moves the handshake to a replacement custom heading', () => {+ const {rerender} = render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title={<Heading level={3}>First</Heading>}+ media={<div>media</div>}+ />+ </Dialog>,+ );+ const first = screen.getByRole('heading', {name: 'First'});+ rerender(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title={<Heading level={2}>Second</Heading>}+ media={<div>media</div>}+ />+ </Dialog>,+ );+ const second = screen.getByRole('heading', {name: 'Second'});+ expect(second).not.toBe(first);+ expect(second).toHaveAttribute('tabindex', '-1');+ expect(second).toHaveAttribute('data-autofocus', 'dialog-title');+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Second');+ });++ it('leaves the custom heading handshake in place when the header re-renders', () => {+ const renderHeader = (caption: string) => (+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title={<Heading level={1}>Custom</Heading>}+ media={<div>{caption}</div>}+ />+ </Dialog>+ );+ const {rerender} = render(renderHeader('first'));+ const heading = screen.getByRole('heading', {level: 1, name: 'Custom'});+ expect(heading).toHaveFocus();+ // Chromium blurs a focused element whose tabindex is removed, so a+ // re-render with a new title element must not remove and add the+ // handshake attributes again.+ const observer = new MutationObserver(() => {});+ observer.observe(heading, {attributes: true});+ rerender(renderHeader('second'));+ const changed = observer+ .takeRecords()+ .map(record => record.attributeName);+ observer.disconnect();+ expect(changed).toEqual([]);+ expect(heading).toHaveFocus();+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Custom');+ });++ it('names the dialog by a custom heading that renders after the header mounts', async () => {+ function LateHeading() {+ const [isReady, setIsReady] = useState(false);+ useEffect(() => {+ setIsReady(true);+ }, []);+ return isReady ? <Heading level={2}>Late</Heading> : null;+ }+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader title={<LateHeading />} media={<div>media</div>} />+ </Dialog>,+ );+ const dialog = screen.getByRole('dialog');+ await waitFor(() => expect(dialog).toHaveAccessibleName('Late'));+ const heading = screen.getByRole('heading', {name: 'Late'});+ expect(dialog).toHaveAttribute('aria-labelledby', heading.id);+ expect(heading.parentElement).not.toHaveAttribute('id');+ });++ it('moves the handshake when a custom heading replaces its own element', async () => {+ function SwappingHeading() {+ const [level, setLevel] = useState<2 | 3>(2);+ useEffect(() => {+ setLevel(3);+ }, []);+ return <Heading level={level}>Swapped</Heading>;+ }+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title={<SwappingHeading />}+ media={<div>media</div>}+ />+ </Dialog>,+ );+ const dialog = screen.getByRole('dialog');+ await waitFor(() =>+ expect(screen.getByRole('heading', {level: 3})).toHaveAttribute('id'),+ );+ const heading = screen.getByRole('heading', {level: 3, name: 'Swapped'});+ expect(dialog).toHaveAttribute('aria-labelledby', heading.id);+ expect(dialog).toHaveAccessibleName('Swapped');+ });++ it('honors an explicit descendant focus request before the default title', () => {+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader title="Welcome" media={<div>media</div>} />+ <button data-autofocus>Continue</button>+ </Dialog>,+ );+ expect(screen.getByRole('button', {name: 'Continue'})).toHaveFocus();+ });++ it.each(['disabled', 'hidden', 'inert'] as const)(+ 'falls back to the title when the explicit request is %s',+ unavailable => {+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader title="Welcome" media={<div>media</div>} />+ <div+ hidden={unavailable === 'hidden'}+ inert={unavailable === 'inert'}>+ <button data-autofocus disabled={unavailable === 'disabled'}>+ Continue+ </button>+ </div>+ </Dialog>,+ );+ expect(screen.getByRole('heading', {name: 'Welcome'})).toHaveFocus();+ },+ );++ it('does not request focus for a visually hidden title', () => {+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title="Hidden"+ media={<div>media</div>}+ isTitleHidden+ onOpenChange={() => {}}+ />+ </Dialog>,+ );+ const heading = screen.getByRole('heading', {name: 'Hidden'});+ expect(heading).not.toHaveFocus();+ expect(heading.parentElement).not.toHaveFocus();+ expect(screen.getByRole('dialog')).toHaveAccessibleName('Hidden');+ });++ it('names the open dialog via aria-labelledby', () => {+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader title="Welcome aboard" media={<div>media</div>} />+ </Dialog>,+ );+ const dialog = screen.getByRole('dialog');+ const labelledBy = dialog.getAttribute('aria-labelledby');+ expect(labelledBy).toBeTruthy();+ expect(document.getElementById(labelledBy as string)).toHaveTextContent(+ 'Welcome aboard',+ );+ });++ it('still names the dialog when the title is hidden', () => {+ render(+ <Dialog isOpen onOpenChange={() => {}}>+ <DialogHeroHeader+ title="Hidden name"+ media={<div>media</div>}+ isTitleHidden+ />+ </Dialog>,+ );+ const dialog = screen.getByRole('dialog');+ const labelledBy = dialog.getAttribute('aria-labelledby');+ expect(labelledBy).toBeTruthy();+ expect(document.getElementById(labelledBy as string)).toHaveTextContent(+ 'Hidden name',+ );+ });++ it('does not auto-focus the title in inline dialogs', () => {+ render(+ <Dialog isOpen isInline onOpenChange={() => {}}>+ <DialogHeroHeader title="Inline title" media={<div>media</div>} />+ </Dialog>,+ );+ expect(document.activeElement).toBe(document.body);+ });+ });++ describe('divider', () => {+ it('renders without divider by default (no context)', () => {+ const {container: noCtx} = render(+ <DialogHeroHeader title="No ctx" media={<div>media</div>} />,+ );+ const {container: explicitFalse} = render(+ <DialogHeroHeader+ title="Explicit false"+ media={<div>media</div>}+ hasDivider={false}+ />,+ );+ expect((noCtx.firstChild as HTMLElement).className).toBe(+ (explicitFalse.firstChild as HTMLElement).className,+ );+ });++ it('inherits divider from Layout context and allows explicit override', () => {+ const {container: ctxTrue} = render(+ <LayoutDividerContext value={{defaultHasDividers: true}}>+ <DialogHeroHeader title="Ctx true" media={<div>media</div>} />+ </LayoutDividerContext>,+ );+ const {container: explicitTrue} = render(+ <DialogHeroHeader+ title="Explicit true"+ media={<div>media</div>}+ hasDivider+ />,+ );+ const {container: overridden} = render(+ <LayoutDividerContext value={{defaultHasDividers: true}}>+ <DialogHeroHeader+ title="Overridden"+ media={<div>media</div>}+ hasDivider={false}+ />+ </LayoutDividerContext>,+ );+ const ctxClass = (ctxTrue.firstChild as HTMLElement).className;+ const explicitClass = (explicitTrue.firstChild as HTMLElement).className;+ const overriddenClass = (overridden.firstChild as HTMLElement).className;+ expect(ctxClass).toBe(explicitClass);+ expect(overriddenClass).not.toBe(ctxClass);+ });+ });++ it('forwards ref, data-testid, and className to the root element', () => {+ const ref = vi.fn();+ render(+ <DialogHeroHeader+ ref={ref}+ title="Title"+ media={<div>media</div>}+ data-testid="hero-header"+ className="custom-class"+ />,+ );+ const root = screen.getByTestId('hero-header');+ expect(root.className).toContain('custom-class');+ expect(ref).toHaveBeenCalledWith(root);+ });+});diff --git a/packages/lab/src/DialogHeroHeader/DialogHeroHeader.tsx b/packages/lab/src/DialogHeroHeader/DialogHeroHeader.tsxnew file mode 100644index 0000000000..d347acfd98--- /dev/null+++ b/packages/lab/src/DialogHeroHeader/DialogHeroHeader.tsx@@ -0,0 +1,406 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file DialogHeroHeader.tsx+ * @input Uses React, StyleX, theme tokens, LayoutHeader, Button, Icon,+ * Heading, MediaTheme, VisuallyHidden, useDialogContext, useTranslator+ * @output Exports DialogHeroHeader component, DialogHeroHeaderProps, and+ * DialogHeroHeaderMediaMode+ * @position Lab implementation; consumed by index.ts, tested by+ * DialogHeroHeader.test.tsx, demonstrated in Storybook+ *+ * Hero-style header for Dialog. The high-emphasis sibling of DialogHeader: a+ * full-bleed media slot sits above the title, and the close button overlays+ * the media's top-trailing corner.+ *+ * The media bleeds to the dialog's edges by cancelling the surrounding+ * LayoutHeader padding with negative margins driven by the+ * `--container-padding-*` custom properties (the same container-compensation+ * contract Section uses), so it tracks theme and per-dialog padding+ * automatically. Corner rounding comes free from the Dialog inner wrapper's+ * `overflow: hidden` + inherited radius.+ *+ * Content overlaid on the media (the close button) can't rely on ambient+ * theme tokens for contrast; `mediaMode` describes the media's luminance and+ * composes MediaTheme under the hood so the overlay picks up inverted tokens+ * (including its focus ring) when the media is dark.+ *+ * The title alone carries Dialog's title id. A visible title declares default+ * focus intent; Dialog applies it after opening, with explicit descendant+ * focus requests taking priority. Hidden, inline, and standalone headers do+ * not request focus. A caller-provided heading receives the same handshake on+ * its own rendered element (never on a wrapper, so the focus target keeps its+ * heading role); attributes the caller already set are left untouched. The+ * handshake follows the rendered heading node, so a re-render keeps focus on+ * it, and a heading that renders later or is replaced still names the dialog.+ * MediaTheme stays mounted across media-mode changes so the close button+ * retains DOM identity and keyboard focus.+ *+ * SYNC: When modified, update these files to stay in sync:+ * - /packages/lab/src/DialogHeroHeader/DialogHeroHeader.doc.mjs (props, usage)+ * - /packages/lab/src/DialogHeroHeader/DialogHeroHeader.test.tsx (behavior)+ * - /packages/lab/src/DialogHeroHeader/index.ts (exports if types change)+ * - /apps/storybook/stories/DialogHeroHeader.stories.tsx (examples)+ */++import {+ useCallback,+ useLayoutEffect,+ useRef,+ type ReactElement,+ type ReactNode,+} from 'react';+import * as stylex from '@stylexjs/stylex';+import type {BaseProps} from '@astryxdesign/core';+import {spacingVars} from '@astryxdesign/core/theme/tokens.stylex';+import {LayoutHeader} from '@astryxdesign/core/Layout';+import {Button} from '@astryxdesign/core/Button';+import {Icon} from '@astryxdesign/core/Icon';+import {Heading} from '@astryxdesign/core/Heading';+import {MediaTheme} from '@astryxdesign/core/theme';+import {VisuallyHidden} from '@astryxdesign/core/VisuallyHidden';+import {useDialogContext} from '@astryxdesign/core/internal/dialog-context';+import {useTranslator} from '@astryxdesign/core/i18n';++const styles = stylex.create({+ // Media container: full width of the header, media centered. Negative+ // margins cancel the LayoutHeader padding (published as+ // --container-padding-* custom properties) so the media bleeds to the+ // dialog's edges — the same compensation contract Section uses. Layout-only+ // wrapper: all paint lives on the caller's media and the Button.+ mediaArea: {+ position: 'relative',+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ marginInlineStart: 'calc(-1 * var(--container-padding-inline-start, 0px))',+ marginInlineEnd: 'calc(-1 * var(--container-padding-inline-end, 0px))',+ marginBlockStart: 'calc(-1 * var(--container-padding-block-start, 0px))',+ },+ // Close button floats over the media's top-trailing corner (logical+ // properties keep it trailing under RTL, matching Drawer's controls).+ closeButton: {+ position: 'absolute',+ insetBlockStart: spacingVars['--spacing-2'],+ insetInlineEnd: spacingVars['--spacing-2'],+ zIndex: 1,+ },+ // Title row below the media; startContent is outside the accessible label.+ titleRow: {+ display: 'flex',+ alignItems: 'center',+ gap: spacingVars['--spacing-3'],+ marginBlockStart: spacingVars['--spacing-4'],+ },+ startContent: {+ display: 'flex',+ alignItems: 'center',+ flexShrink: 0,+ },+ // Allow the heading to shrink and truncate inside the flex row.+ titleHeading: {+ minWidth: 0,+ outline: 'none',+ },+ // Layout-only slot around a caller-provided heading. It never takes the+ // title id or focus; those land on the heading itself.+ customTitleSlot: {+ minWidth: 0,+ },+});++const HEADING_SELECTOR = 'h1, h2, h3, h4, h5, h6, [role="heading"]';++/**+ * Applies Dialog's title handshake to the rendered element of a+ * caller-provided heading without cloning or inspecting it. Only attributes+ * the element does not already carry are added, and cleanup removes only+ * values that are still ours, so a caller-owned id or tabIndex always wins.+ *+ * The handshake follows the heading node, not the `title` prop. A re-render+ * that keeps the same heading changes nothing: removing tabindex from the+ * focused heading would blur it. A heading that renders later, or that the+ * caller's component replaces with another element, receives the handshake+ * when it appears, and Dialog then checks its default name again.+ *+ * Returns the callback ref for the slot around the heading. The ref attaches+ * in the same commit as the slot, so the id and focus marker exist before+ * Dialog resolves its default name and initial focus.+ */+function useCustomTitleHandshake(+ titleId: string | undefined,+ shouldAutoFocus: boolean,+ syncDefaultName: (() => void) | undefined,+) {+ const syncRef = useRef<(() => boolean) | null>(null);++ const attachSlot = useCallback(+ (slot: HTMLDivElement | null) => {+ if (slot == null) {+ return;+ }+ let heading: HTMLElement | null = null;+ let added: Array<[name: string, value: string]> = [];+ const release = () => {+ for (const [name, value] of added) {+ if (heading?.getAttribute(name) === value) {+ heading.removeAttribute(name);+ }+ }+ added = [];+ };+ // Returns whether the slot now holds a different heading element.+ const sync = () => {+ const next =+ slot.querySelector<HTMLElement>(HEADING_SELECTOR) ??+ (slot.firstElementChild as HTMLElement | null);+ if (next === heading) {+ return false;+ }+ release();+ heading = next;+ if (next != null) {+ const addIfAbsent = (name: string, value: string) => {+ if (!next.hasAttribute(name)) {+ next.setAttribute(name, value);+ added.push([name, value]);+ }+ };+ if (titleId != null) {+ addIfAbsent('id', titleId);+ }+ if (shouldAutoFocus) {+ addIfAbsent('tabindex', '-1');+ // Private coordination with Dialog, which owns modal focus timing.+ addIfAbsent('data-autofocus', 'dialog-title');+ }+ }+ return true;+ };+ sync();+ syncRef.current = sync;+ // The caller's own component can render its heading later or replace+ // it without re-rendering this header.+ const observer = new MutationObserver(() => {+ if (sync()) {+ syncDefaultName?.();+ }+ });+ observer.observe(slot, {childList: true, subtree: true});+ return () => {+ observer.disconnect();+ syncRef.current = null;+ release();+ heading = null;+ };+ },+ [titleId, shouldAutoFocus, syncDefaultName],+ );++ // A re-render of this header can replace the heading in the same commit;+ // check again before Dialog reads its title. The same heading is a no-op.+ useLayoutEffect(() => {+ if (syncRef.current?.()) {+ syncDefaultName?.();+ }+ });++ return attachSlot;+}++/**+ * Luminance of the media surface, forwarded to MediaTheme for content+ * rendered over the media (the close button).+ */+export type DialogHeroHeaderMediaMode = 'light' | 'dark';++export interface DialogHeroHeaderProps extends BaseProps<HTMLDivElement> {+ /** Ref forwarded to the root element */+ ref?: React.Ref<HTMLDivElement>;++ /**+ * The title of the dialog. A string is wrapped in a level 2 Heading+ * (matching DialogHeader); pass a pre-styled Heading element to customize+ * the heading treatment. Provides the accessible label for the parent+ * Dialog via aria-labelledby (unless the Dialog receives an explicit+ * aria-label/aria-labelledby). The visible title is the default initial+ * focus target after the modal opens; an explicit descendant request wins.+ * A custom heading receives the label and focus on its own element; if it+ * sets its own `id`, name the Dialog with `aria-labelledby` instead.+ */+ title: string | ReactElement;++ /**+ * The full-bleed visual rendered above the title (image, illustration, or+ * icon). Stretches to the dialog's padded edges; the close button overlays+ * its top-trailing corner. Size the media itself (e.g. width 100%) to fill+ * the slot.+ */+ media: ReactNode;++ /**+ * Luminance of the media surface. Composes MediaTheme under the hood so+ * content overlaid on the media (the close button) picks up contrast-safe+ * inverted tokens: 'dark' media gets light overlay content, 'light' media+ * gets dark overlay content. Omit to keep the ambient theme tokens.+ */+ mediaMode?: DialogHeroHeaderMediaMode;++ /**+ * Visually hides the title row while keeping it available to screen+ * readers, so the dialog stays named by the title.+ * @default false+ */+ isTitleHidden?: boolean;++ /**+ * Content placed before the title (e.g. an icon), inline with the heading.+ */+ startContent?: ReactNode;++ /**+ * Max lines before the title truncates with an ellipsis. Only applies when+ * `title` is a string (auto-wrapped in a Heading).+ */+ maxLines?: number;++ /**+ * Callback fired when the dialog visibility changes.+ * Called with `false` when the close button is clicked.+ * If not provided, no close button will be rendered.+ */+ onOpenChange?: (isOpen: boolean) => unknown;++ /**+ * Adds a themed border at the bottom edge.+ * Defaults to the parent Layout's `defaultHasDividers` context value.+ */+ hasDivider?: boolean;+}++/**+ * Hero-style header designed specifically for Dialog — the high-emphasis+ * sibling of DialogHeader.+ *+ * Renders a full-bleed media slot above the title for dialogs that open onto+ * a featured, marketing, or onboarding moment. The close button overlays the+ * media's top-trailing corner; set `mediaMode` so it composes MediaTheme and+ * stays legible over dark or light media. The title names the parent Dialog+ * via aria-labelledby. The visible title supplies the default initial focus+ * target after the modal opens; hidden titles and inline previews skip it.+ *+ * Uses LayoutHeader internally, so it drops into Layout's `header` slot the+ * same way DialogHeader does.+ *+ * @example+ * ```+ * <Dialog isOpen={isOpen} onOpenChange={open => setIsOpen(open)}>+ * <Layout+ * header={+ * <DialogHeroHeader+ * title="Welcome aboard"+ * media={<img src={hero} alt="" width="100%" />}+ * mediaMode="dark"+ * onOpenChange={open => setIsOpen(open)}+ * />+ * }+ * content={<LayoutContent>Content</LayoutContent>}+ * footer={<LayoutFooter hasDivider>Actions</LayoutFooter>}+ * />+ * </Dialog>+ * ```+ */+export function DialogHeroHeader({+ title,+ media,+ mediaMode,+ isTitleHidden = false,+ startContent,+ maxLines,+ onOpenChange,+ hasDivider,+ xstyle,+ className,+ style,+ ref,+ ...rest+}: DialogHeroHeaderProps) {+ const t = useTranslator();+ const dialogContext = useDialogContext();+ const shouldAutoFocus = dialogContext?.isInline === false && !isTitleHidden;+ const titleId = dialogContext?.titleId;+ const attachCustomTitleSlot = useCustomTitleHandshake(+ titleId,+ shouldAutoFocus,+ dialogContext?.syncDefaultName,+ );++ const closeButton = onOpenChange != null && (+ <Button+ variant="ghost"+ label={t('@astryx.dialog.close')}+ tooltip={t('@astryx.dialog.close')}+ icon={<Icon icon="close" color="inherit" />}+ onClick={() => {+ onOpenChange(false);+ }}+ isIconOnly+ xstyle={styles.closeButton}+ />+ );++ // Custom headings keep their own props; useCustomTitleHandshake wires the+ // title id and focus request onto the rendered heading, never the slot and+ // never the start-content, so neither leaks into the dialog's name.+ const titleRow = (+ <div {...stylex.props(styles.titleRow)}>+ {startContent != null && (+ <div {...stylex.props(styles.startContent)}>{startContent}</div>+ )}+ {typeof title === 'string' ? (+ <Heading+ id={titleId}+ tabIndex={shouldAutoFocus ? -1 : undefined}+ // Private coordination with Dialog, which owns modal focus timing.+ data-autofocus={shouldAutoFocus ? 'dialog-title' : undefined}+ level={2}+ maxLines={maxLines}+ xstyle={styles.titleHeading}>+ {title}+ </Heading>+ ) : (+ <div+ ref={attachCustomTitleSlot}+ {...stylex.props(styles.customTitleSlot)}>+ {title}+ </div>+ )}+ </div>+ );++ return (+ <LayoutHeader+ ref={ref}+ hasDivider={hasDivider}+ xstyle={xstyle}+ className={className}+ style={style}+ {...rest}>+ <div {...stylex.props(styles.mediaArea)}>+ {media}+ {closeButton && (+ <MediaTheme mode={mediaMode ?? 'off'}>{closeButton}</MediaTheme>+ )}+ </div>+ {isTitleHidden ? (+ <VisuallyHidden as="div">{titleRow}</VisuallyHidden>+ ) : (+ titleRow+ )}+ </LayoutHeader>+ );+}++DialogHeroHeader.displayName = 'DialogHeroHeader';diff --git a/packages/lab/src/DialogHeroHeader/index.ts b/packages/lab/src/DialogHeroHeader/index.tsnew file mode 100644index 0000000000..64cfac3d89--- /dev/null+++ b/packages/lab/src/DialogHeroHeader/index.ts@@ -0,0 +1,14 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file index.ts+ * @input DialogHeroHeader.tsx+ * @output Re-exports DialogHeroHeader component and its prop types+ * @position Canary-only Lab entry point for the DialogHeroHeader directory+ */++export {DialogHeroHeader} from './DialogHeroHeader';+export type {+ DialogHeroHeaderProps,+ DialogHeroHeaderMediaMode,+} from './DialogHeroHeader';diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.tsindex 4515104d41..2047b02024 100644--- a/packages/lab/src/index.ts+++ b/packages/lab/src/index.ts@@ -104,6 +104,13 @@ export {} from './ChatReasoning/ChatReasoning';export * from './Chat';+// DialogHeroHeader — hero-style Dialog header (meta/astryx#4182)+export {+ DialogHeroHeader,+ type DialogHeroHeaderProps,+ type DialogHeroHeaderMediaMode,+} from './DialogHeroHeader';+// Tour — guided product-tour / NUX walkthrough (meta/astryx#4239)export {Tour,