diff --git a/.changeset/astryx-discover-lists-the-lab-dialogheroheader-c-dhhr.md b/.changeset/astryx-discover-lists-the-lab-dialogheroheader-c-dhhr.md new file mode 100644 index 0000000000000..493bfcbe22a9e --- /dev/null +++ b/.changeset/astryx-discover-lists-the-lab-dialogheroheader-c-dhhr.md @@ -0,0 +1,6 @@ +--- +'@astryxdesign/cli': patch +--- + +[feat] `astryx discover` lists the Lab DialogHeroHeader component and its DialogHeroHeaderShowcase template from `@astryxdesign/lab`. (#4182) +@jiunshinn diff --git a/.changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.md b/.changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.md new file mode 100644 index 0000000000000..115b0fc049f3e --- /dev/null +++ b/.changeset/dialog-when-the-opening-dialog-s-first-data-auto-wr66.md @@ -0,0 +1,6 @@ +--- +'@astryxdesign/core': patch +--- + +[fix] Dialog: when the opening Dialog's first data-autofocus request is hidden, inert, or cannot take focus, the next request takes it; a header's default title request comes after every explicit request (#4182) +@jiunshinn diff --git a/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md b/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md new file mode 100644 index 0000000000000..cb437fc0b86e5 --- /dev/null +++ b/.changeset/internal-lab-s-dialogheroheader-reads-the-dialog-ctse.md @@ -0,0 +1,6 @@ +--- +'@astryxdesign/core': patch +--- + +[chore] Internal: Lab's DialogHeroHeader reads the Dialog's title id and inline state through an internal entry reserved for Astryx's own packages; nothing a consumer sees changes (#4182) +@jiunshinn diff --git a/.github/scripts/story-play-guard.js b/.github/scripts/story-play-guard.js index db34b39b9cfb8..8172d0cb9ab67 100644 --- a/.github/scripts/story-play-guard.js +++ b/.github/scripts/story-play-guard.js @@ -347,6 +347,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.tsx new file mode 100644 index 0000000000000..59c3f89f93e01 --- /dev/null +++ b/apps/storybook/stories/DialogHeroHeader.stories.tsx @@ -0,0 +1,628 @@ +// 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 DialogHeroHeaderShowcase from '../../../packages/lab/blocks/DialogHeroHeaderShowcase'; +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 , , 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 ( + + + + + + + + + + + + + ); +} + +const meta: Meta = { + title: 'Lab/DialogHeroHeader', + component: DialogHeroHeader, + tags: ['autodocs'], +}; + +export default meta; +type Story = StoryObj; + +/** The same block is discoverable through the Lab integration and canary docsite. */ +export const Showcase: Story = { + render: () => , +}; + +/** + * 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: () => ( + {}}> + } + mediaMode="dark" + onOpenChange={() => {}} + /> + } + content={ + + + Set up your workspace in three quick steps. You can change any of + this later in Settings. + + + } + footer={ + + + + + + + } + /> + + ), +}; + +/** + * Light media inverts the overlay treatment: `mediaMode="light"` gives the + * close button dark, contrast-safe tokens. + */ +export const LightMedia: Story = { + render: () => ( + {}}> + } + mediaMode="light" + onOpenChange={() => {}} + /> + } + content={ + + + Charts now support streaming data, and the command palette learned + fuzzy matching. + + + } + /> + + ), +}; + +/** + * `startContent` renders inline before the title; `maxLines` truncates long + * auto-wrapped titles with an ellipsis. + */ +export const StartContentAndTruncation: Story = { + render: () => ( + {}}> + } + mediaMode="dark" + startContent={} + maxLines={1} + onOpenChange={() => {}} + /> + } + content={ + + + The full title stays available to screen readers and in the + truncation tooltip. + + + } + /> + + ), +}; + +/** + * 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: () => ( + + {}} width={320}> + } + mediaMode="light" + isTitleHidden + onOpenChange={() => {}} + /> + } + content={ + + + The media speaks for itself; the hidden title still names the + dialog. + + + } + /> + + {}} width={320}> + + Big moment + + } + media={} + mediaMode="dark" + onOpenChange={() => {}} + /> + } + content={ + + + A caller-provided Heading element renders as-is for custom + treatments. + + + } + /> + + + ), +}; + +/** + * 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 ( + <> + setIsOpen(true)} + /> + + } + mediaMode="dark" + onOpenChange={setIsOpen} + /> + } + content={ + + + Set up your workspace in three quick steps. + + + } + footer={ + + + setIsOpen(false)} + /> + + + } + /> + + > + ); + }, +}; + +/** Optional close controls and divider follow the surrounding Layout. */ +export const WithoutCloseButton: Story = { + render: () => ( + {}}> + } + /> + } + content={ + + + Close controls are supplied only when needed. + + + } + /> + + ), +}; + +/** Logical positioning keeps the overlay on the trailing edge in RTL. */ +export const RightToLeft: Story = { + render: () => ( + + {}} padding={8}> + } + mediaMode="light" + startContent={} + onOpenChange={() => {}} + /> + } + content={ + + جهّز مساحة عملك في ثلاث خطوات بسيطة. + + } + /> + + + ), +}; + +type MediaBleedFixture = { + id: string; + dir: 'ltr' | 'rtl'; + padding?: ComponentProps['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: () => ( + + {MEDIA_BLEED_FIXTURES.map(({id, dir, padding, themePadding}) => ( + + {}} + padding={padding} + width={320} + data-media-bleed-surface=""> + } + mediaMode="dark" + onOpenChange={() => {}} + /> + } + content={ + + Media bleed fixture + + } + /> + + + ))} + + ), + play: async ({canvasElement}) => { + await document.fonts.ready; + await new Promise(resolve => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + + const insets = new Map(); + for (const {id, dir, themePadding} of MEDIA_BLEED_FIXTURES) { + const fixture = canvasElement.querySelector( + `[data-media-bleed-fixture="${id}"]`, + ); + const surface = fixture?.querySelector( + '[data-media-bleed-surface]', + ); + const mediaArea = fixture?.querySelector('svg')?.parentElement; + const headerBox = mediaArea?.parentElement; + const title = fixture?.querySelector('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 { + const deadline = performance.now() + 5000; + while (!isMet()) { + if (performance.now() > deadline) { + throw new Error(`timed out waiting until ${description}`); + } + await new Promise(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 ( + {}}> + + Big moment + + } + media={} + mediaMode="dark" + onOpenChange={() => {}} + /> + } + content={ + + + + Re-renders after opening: {renderCount} + + + + } + /> + + ); + }, + 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(resolve => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + const heading = doc.querySelector('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.json index 97b4458b92bda..b3ae01dff6a2b 100644 --- a/internal/shadcn-registry/routes.lock.json +++ b/internal/shadcn-registry/routes.lock.json @@ -590,6 +590,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", @@ -4354,6 +4359,11 @@ "path": "showcases/dialog-header/default", "aliases": [] }, + { + "name": "showcase-dialog-hero-header-default", + "path": "showcases/dialog-hero-header/default", + "aliases": [] + }, { "name": "showcase-dialog-default", "path": "showcases/dialog/default", diff --git a/packages/cli/assets/discover/official-packages.json b/packages/cli/assets/discover/official-packages.json index 1bc625e358829..817ebf0cdb0d3 100644 --- a/packages/cli/assets/discover/official-packages.json +++ b/packages/cli/assets/discover/official-packages.json @@ -124,6 +124,10 @@ "kind": "component", "name": "CommentThread" }, + { + "kind": "component", + "name": "DialogHeroHeader" + }, { "kind": "component", "name": "DiffViewer" @@ -236,6 +240,10 @@ "kind": "template", "name": "CommentThreadShowcase" }, + { + "kind": "template", + "name": "DialogHeroHeaderShowcase" + }, { "kind": "template", "name": "DiffViewerShowcase" diff --git a/packages/core/package.json b/packages/core/package.json index 295c3d98433c4..dd119a33b384c 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -828,6 +828,11 @@ "source": "./src/internal/tokenizer-presentation.ts", "types": "./dist/internal/tokenizer-presentation.d.ts", "default": "./dist/internal/tokenizer-presentation.js" + }, + "./internal/dialog-context": { + "source": "./src/internal/dialog-context.ts", + "types": "./dist/internal/dialog-context.d.ts", + "default": "./dist/internal/dialog-context.js" } }, "files": [ diff --git a/packages/core/src/Dialog/Dialog.test.tsx b/packages/core/src/Dialog/Dialog.test.tsx index b676be021577d..119dc05d99f67 100644 --- a/packages/core/src/Dialog/Dialog.test.tsx +++ b/packages/core/src/Dialog/Dialog.test.tsx @@ -9,7 +9,7 @@ * SYNC: When Dialog.tsx changes, update tests to match new behavior */ -import {useState, type SyntheticEvent} from 'react'; +import {useLayoutEffect, useState, type SyntheticEvent} from 'react'; import {readFileSync} from 'node:fs'; import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest'; import type {MockInstance} from 'vitest'; @@ -20,6 +20,7 @@ import { resolveDialogPositionOffsets, } from './Dialog'; import {DialogHeader} from './DialogHeader'; +import {useDialogContext} from './DialogContext'; import {defineTheme, generateThemeCSS} from '../theme'; import {__resetInteractionModalityForTest} from '../utils/interactionModality'; @@ -1218,6 +1219,38 @@ describe('Dialog', () => { expect(dialog).toHaveAccessibleName('Rich dialog title'); }); + it('names itself by a header title that renders after the dialog mounts', () => { + // A composed header whose title arrives in a later commit asks the + // dialog to check its default name again. + function LateTitleHeader({isReady}: {isReady: boolean}) { + const context = useDialogContext(); + const syncDefaultName = context?.syncDefaultName; + useLayoutEffect(() => { + syncDefaultName?.(); + }, [isReady, syncDefaultName]); + return isReady ? Late title : null; + } + const {rerender} = render( + {}}> + + , + ); + const dialog = screen.getByRole('dialog'); + expect(dialog).not.toHaveAttribute('aria-labelledby'); + rerender( + {}}> + + , + ); + expect(dialog).toHaveAccessibleName('Late title'); + rerender( + {}}> + + , + ); + expect(dialog).not.toHaveAttribute('aria-labelledby'); + }); + it('prefers a consumer-provided aria-label over the header title', () => { render( {}} aria-label="Custom name"> diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx index 2f1e5806bddb0..04af612319248 100644 --- a/packages/core/src/Dialog/Dialog.tsx +++ b/packages/core/src/Dialog/Dialog.tsx @@ -15,6 +15,8 @@ * Fullscreen dialogs add safe-area protection to the default padding fallback * while preserving explicit prop/theme padding overrides, and fade in without * the centered-dialog translate/scale motion. + * Initial focus is applied after showModal; an explicit descendant request + * takes priority over a header's default title request. * * Under reduced motion the entrance never travels or scales * (docs/design/reduced-motion.md): on a touch screen the dialog fades in @@ -495,11 +497,6 @@ export function Dialog({ // would cost at the dialog level. const titleId = useId(); - const dialogContextValue = useMemo( - () => ({isInline, titleId}), - [isInline, titleId], - ); - // Consumer-provided labels always win over the DialogHeader default. const hasConsumerName = props['aria-label'] != null || props['aria-labelledby'] != null; @@ -526,6 +523,19 @@ export function Dialog({ [titleId, hasConsumerName], ); + // A composed header whose title renders after the dialog mounted asks the + // dialog to look for the title again. + const syncDefaultName = useCallback(() => { + if (dialogRef.current != null) { + attachDialog(dialogRef.current); + } + }, [attachDialog]); + + const dialogContextValue = useMemo( + () => ({isInline, titleId, syncDefaultName}), + [isInline, titleId, syncDefaultName], + ); + const mergedDialogRef = useMergedRefs(ref, attachDialog); // Capture the element that was focused when the dialog opened, for @@ -580,11 +590,27 @@ export function Dialog({ dialog.showModal(); // React's autoFocus calls .focus() during commit, before showModal() // makes the dialog visible, so the focus silently fails. - // Focus the first element with data-autofocus inside the dialog. - const autofocusTarget = - dialog.querySelector('[data-autofocus]'); - if (autofocusTarget) { - focusForLastInput(autofocusTarget); + // Explicit descendant intent takes priority over a header's default + // title. Keep the marker private to the focus-owning components. + const autofocusTargets = [ + ...dialog.querySelectorAll( + '[data-autofocus]:not([data-autofocus="dialog-title"])', + ), + ...dialog.querySelectorAll( + '[data-autofocus="dialog-title"]', + ), + ]; + for (const target of autofocusTargets) { + if (target.closest('[hidden], [inert], [aria-hidden="true"]')) { + continue; + } + // Disabled and CSS-hidden targets cannot receive focus in the + // browser. If a request cannot land, try the next eligible request + // and finally the title; otherwise preserve native initial focus. + focusForLastInput(target); + if (document.activeElement === target) { + break; + } } } } else { diff --git a/packages/core/src/Dialog/DialogContext.ts b/packages/core/src/Dialog/DialogContext.ts index 9872e43d5fe59..600160df8d0c1 100644 --- a/packages/core/src/Dialog/DialogContext.ts +++ b/packages/core/src/Dialog/DialogContext.ts @@ -6,7 +6,8 @@ * @file DialogContext.ts * @input React context * @output Internal dialog context for child focus behavior and default labelling - * @position Dialog internals; consumed by focus-managing children and DialogHeader + * @position Dialog internals; consumed by focus-managing children and DialogHeader, + * and by Lab's DialogHeroHeader through the internal/dialog-context entry */ import {createContext, use} from 'react'; @@ -21,6 +22,12 @@ export interface DialogContextValue { * when the title actually rendered — never pointing at a nonexistent id. */ titleId?: string; + /** + * Checks the default aria-labelledby again. The dialog looks for its title + * when it mounts; a composed header whose title element appears, changes, + * or leaves after that calls this so the dialog's name follows it. + */ + syncDefaultName?: () => void; } export const DialogContext = createContext(null); diff --git a/packages/core/src/internal/dialog-context.test.ts b/packages/core/src/internal/dialog-context.test.ts new file mode 100644 index 0000000000000..976496f876b24 --- /dev/null +++ b/packages/core/src/internal/dialog-context.test.ts @@ -0,0 +1,25 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +/** + * @file dialog-context.test.ts + * @input The internal `internal/dialog-context` entry and the Dialog module + * @output Proof that the entry re-exports the same hook Dialog provides, by + * name, and that the public Dialog barrel names no context + * @position Unit tests of packages/core/src/internal/dialog-context.ts + */ +import {describe, expect, it} from 'vitest'; + +describe('internal/dialog-context', () => { + it('re-exports the one Dialog context hook, the same value Dialog reads', async () => { + const entry: Record = await import('./dialog-context'); + const context = await import('../Dialog/DialogContext'); + expect(entry.useDialogContext).toBe(context.useDialogContext); + // Named re-exports only, nothing else. + expect(Object.keys(entry).sort()).toEqual(['useDialogContext']); + }); + + it('the public Dialog barrel exports no context surface', async () => { + const pub: Record = await import('../Dialog'); + expect(pub).not.toHaveProperty('DialogContext'); + expect(pub).not.toHaveProperty('useDialogContext'); + }); +}); diff --git a/packages/core/src/internal/dialog-context.ts b/packages/core/src/internal/dialog-context.ts new file mode 100644 index 0000000000000..aaf9ca18b4b55 --- /dev/null +++ b/packages/core/src/internal/dialog-context.ts @@ -0,0 +1,19 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file dialog-context.ts + * @input Dialog's internal context hook + * @output `@astryxdesign/core/internal/dialog-context`: `useDialogContext`, + * for Astryx's own packages + * @position An internal entry reserved for Astryx's own packages: + * undocumented, outside the public API and its compatibility promise + * (spec:AST-017 FR21), versioned in lockstep with Core, and allowed only in + * Core and Lab by the `@astryx/no-core-internal-import` lint rule + * (architecture:react-component-runtime INV13). Lab's DialogHeroHeader reads + * the Dialog's title id and inline state through it, so it names the dialog + * and requests title focus the way DialogHeader does. Named re-exports only. + * + * SYNC: When modified, update dialog-context.test.ts and + * scripts/sync-exports.js. + */ +export {useDialogContext} from '../Dialog/DialogContext'; diff --git a/packages/lab/blocks/DialogHeroHeaderShowcase.doc.mjs b/packages/lab/blocks/DialogHeroHeaderShowcase.doc.mjs new file mode 100644 index 0000000000000..ea93c85328356 --- /dev/null +++ b/packages/lab/blocks/DialogHeroHeaderShowcase.doc.mjs @@ -0,0 +1,29 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +/** + * @file DialogHeroHeaderShowcase.doc.mjs + * @input DialogHeroHeaderShowcase.tsx + * @output Showcase ownership and preview metadata + * @position Lab integration template registration for DialogHeroHeader + */ + +/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */ +export default { + type: 'block', + name: 'DialogHeroHeader', + displayName: 'Dialog Hero Header', + description: + 'An onboarding dialog with full-bleed artwork and an overlaid close button.', + exampleFor: 'DialogHeroHeader', + isShowcase: true, + aspectRatio: 4 / 3, + componentsUsed: [ + 'DialogHeroHeader', + 'Dialog', + 'Layout', + 'LayoutContent', + 'LayoutFooter', + 'Button', + 'Text', + ], +}; diff --git a/packages/lab/blocks/DialogHeroHeaderShowcase.tsx b/packages/lab/blocks/DialogHeroHeaderShowcase.tsx new file mode 100644 index 0000000000000..6a96bab10a62c --- /dev/null +++ b/packages/lab/blocks/DialogHeroHeaderShowcase.tsx @@ -0,0 +1,86 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. + +'use client'; + +/** + * @file DialogHeroHeaderShowcase.tsx + * @input DialogHeroHeader composed with Dialog and Layout + * @output A dismissible onboarding preview with full-bleed decorative media + * @position Canary Lab showcase shared by CLI discovery, docsite, and Storybook + */ + +import {useId, useState} from 'react'; +import * as stylex from '@stylexjs/stylex'; +import {DialogHeroHeader} from '@astryxdesign/lab'; +import {Button} from '@astryxdesign/core/Button'; +import {Dialog} from '@astryxdesign/core/Dialog'; +import {Layout, LayoutContent, LayoutFooter} from '@astryxdesign/core/Layout'; +import {Text} from '@astryxdesign/core/Text'; + +const styles = stylex.create({ + artwork: { + display: 'block', + }, +}); + +export default function DialogHeroHeaderShowcase() { + const [isOpen, setIsOpen] = useState(true); + const gradientId = useId(); + + return isOpen ? ( + + + + + + + + + + + + + + } + mediaMode="dark" + onOpenChange={setIsOpen} + /> + } + content={ + + + Bring your notes, projects, and collaborators together in one + workspace. You can make it your own as you go. + + + } + footer={ + + setIsOpen(false)} + /> + + } + /> + + ) : ( + setIsOpen(true)} + /> + ); +} diff --git a/packages/lab/src/DialogHeroHeader/DialogHeroHeader.doc.mjs b/packages/lab/src/DialogHeroHeader/DialogHeroHeader.doc.mjs new file mode 100644 index 0000000000000..6be1939d0a41d --- /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); + + } + mediaMode="dark" + onOpenChange={setIsOpen} + /> + } + content={Get started in three steps.} + footer={ + + + + } + /> +`, + }, + { + label: 'Hidden title (media carries the message)', + code: `} + 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.tsx new file mode 100644 index 0000000000000..de540915bc79c --- /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( + media} />, + ); + 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( + Custom heading} + media={media} + />, + ); + expect( + screen.getByRole('heading', {level: 3, name: 'Custom heading'}), + ).toBeInTheDocument(); + expect(screen.queryByRole('heading', {level: 2})).not.toBeInTheDocument(); + }); + + it('renders the media slot', () => { + render( + } + />, + ); + expect(screen.getByRole('img', {name: 'Illustration'})).toBeInTheDocument(); + }); + + it('renders startContent before the title', () => { + render( + media} + startContent={start} + />, + ); + expect(screen.getByText('start')).toBeInTheDocument(); + }); + + it('does not move page focus when rendered outside a Dialog', () => { + render(media} />); + expect(document.activeElement).toBe(document.body); + }); + + describe('close button', () => { + it('renders when onOpenChange is provided', () => { + render( + media} + onOpenChange={() => {}} + />, + ); + expect(screen.getByRole('button', {name: /close/i})).toBeInTheDocument(); + }); + + it('does not render when onOpenChange is not provided', () => { + render(media} />); + 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( + media} + 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: media, + onOpenChange: vi.fn(), + }; + const {rerender} = render(); + const button = screen.getByRole('button', {name: /close/i}); + button.focus(); + for (const mediaMode of ['dark', 'light', undefined] as const) { + rerender(); + expect(screen.getByRole('button', {name: /close/i})).toBe(button); + expect(button).toHaveFocus(); + } + }); + + it('wraps the close button in a MediaTheme surface', () => { + const {container} = render( + media} + 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( + media} + onOpenChange={() => {}} + />, + ); + expect(container.querySelector('[data-astryx-media]')).toBeNull(); + }); + }); + + describe('isTitleHidden', () => { + it('keeps the title in the accessibility tree', () => { + render( + media} + isTitleHidden + />, + ); + expect( + screen.getByRole('heading', {level: 2, name: 'Title'}), + ).toBeInTheDocument(); + }); + + it('changes the title row presentation', () => { + const {container: hidden} = render( + media} + isTitleHidden + />, + ); + const {container: visible} = render( + media} />, + ); + 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( + {}}> + media} /> + , + ); + expect(screen.getByRole('heading', {name: 'Welcome'})).toHaveFocus(); + expect(focusStates.length).toBeGreaterThan(0); + expect(focusStates.every(Boolean)).toBe(true); + rerender( + {}}> + {null} + , + ); + 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( + {}}> + New} + media={media} + /> + , + ); + expect(screen.getByRole('dialog')).toHaveAccessibleName('Welcome'); + rerender( + {}}> + Custom} + startContent={New} + media={media} + /> + , + ); + 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( + {}}> + Custom} + startContent={New} + media={media} + /> + , + ); + 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( + {}} aria-labelledby="own-title"> + + Own + + } + media={media} + /> + , + ); + 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( + {}} {...dialogProps}> + Custom} + media={media} + {...headerProps} + /> + , + ); + 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( + {}}> + First} + media={media} + /> + , + ); + const first = screen.getByRole('heading', {name: 'First'}); + rerender( + {}}> + Second} + media={media} + /> + , + ); + 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) => ( + {}}> + Custom} + media={{caption}} + /> + + ); + 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 ? Late : null; + } + render( + {}}> + } media={media} /> + , + ); + 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 Swapped; + } + render( + {}}> + } + media={media} + /> + , + ); + 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( + {}}> + media} /> + Continue + , + ); + 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( + {}}> + media} /> + + + Continue + + + , + ); + expect(screen.getByRole('heading', {name: 'Welcome'})).toHaveFocus(); + }, + ); + + it('does not request focus for a visually hidden title', () => { + render( + {}}> + media} + isTitleHidden + onOpenChange={() => {}} + /> + , + ); + 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( + {}}> + media} /> + , + ); + 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( + {}}> + media} + isTitleHidden + /> + , + ); + 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( + {}}> + media} /> + , + ); + expect(document.activeElement).toBe(document.body); + }); + }); + + describe('divider', () => { + it('renders without divider by default (no context)', () => { + const {container: noCtx} = render( + media} />, + ); + const {container: explicitFalse} = render( + media} + 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( + + media} /> + , + ); + const {container: explicitTrue} = render( + media} + hasDivider + />, + ); + const {container: overridden} = render( + + media} + hasDivider={false} + /> + , + ); + 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( + media} + 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.tsx new file mode 100644 index 0000000000000..d347acfd98f11 --- /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(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 { + /** Ref forwarded to the root element */ + ref?: React.Ref; + + /** + * 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 + * ``` + * setIsOpen(open)}> + * } + * mediaMode="dark" + * onOpenChange={open => setIsOpen(open)} + * /> + * } + * content={Content} + * footer={Actions} + * /> + * + * ``` + */ +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 && ( + } + 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 = ( + + {startContent != null && ( + {startContent} + )} + {typeof title === 'string' ? ( + + {title} + + ) : ( + + {title} + + )} + + ); + + return ( + + + {media} + {closeButton && ( + {closeButton} + )} + + {isTitleHidden ? ( + {titleRow} + ) : ( + titleRow + )} + + ); +} + +DialogHeroHeader.displayName = 'DialogHeroHeader'; diff --git a/packages/lab/src/DialogHeroHeader/index.ts b/packages/lab/src/DialogHeroHeader/index.ts new file mode 100644 index 0000000000000..64cfac3d89785 --- /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.ts index 4e6d9f0f7f673..5e8df137ad211 100644 --- a/packages/lab/src/index.ts +++ b/packages/lab/src/index.ts @@ -88,6 +88,13 @@ export { } from './ChatReasoning/ChatReasoning'; export * from './Chat'; +// DialogHeroHeader — hero-style Dialog header (facebook/astryx#4182) +export { + DialogHeroHeader, + type DialogHeroHeaderProps, + type DialogHeroHeaderMediaMode, +} from './DialogHeroHeader'; + // Tour — guided product-tour / NUX walkthrough (facebook/astryx#4239) export { Tour, diff --git a/scripts/sync-exports.js b/scripts/sync-exports.js index ee5316c7916a1..ec61b3c86cb0a 100644 --- a/scripts/sync-exports.js +++ b/scripts/sync-exports.js @@ -239,6 +239,7 @@ const FILE_MODULE_SUBPATH_EXPORTS = [ // (architecture:react-component-runtime INV13). 'internal/touch', 'internal/tokenizer-presentation', + 'internal/dialog-context', ]; /**