@astryxdesign/core 0.7.4-canary.ac8260d → 0.7.4-canary.ad6782d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"FileInput.d.ts","sourceRoot":"","sources":["../../src/FileInput/FileInput.tsx"],"names":[],"mappings":"AAuCA,OAAO,EAGL,KAAK,WAAW,EAChB,KAAK,kBAAkB,EACxB,MAAM,UAAU,CAAC;AASlB,YAAY,EACV,WAAW,IAAI,eAAe,EAC9B,eAAe,IAAI,mBAAmB,GACvC,MAAM,UAAU,CAAC;AAGlB,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,gBAAgB,CAAC;AAmP9C,MAAM,WAAW,cAAe,SAAQ,IAAI,CAC1C,mBAAmB,EACnB,UAAU,GAAG,cAAc,GAAG,OAAO,CACtC;IACC,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAClC;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;IAC5B;;OAEG;IACH,QAAQ,EAAE,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,KAAK,IAAI,CAAC;IAChD;;;OAGG;IACH,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;;;;;;;;;;;;;;OAmBG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;OAEG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,IAAI,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC;IAC5B;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;OAIG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,EACxB,KAAK,EACL,aAAqB,EACrB,KAAK,EACL,QAAQ,EACR,YAAY,EACZ,MAAM,EACN,UAAkB,EAClB,OAAO,EACP,QAAQ,EACR,UAAkB,EAClB,eAAe,EACf,UAAkB,EAClB,SAAiB,EACjB,MAAM,EAAE,UAAU,EAClB,aAA0B,EAC1B,WAAW,EACX,WAAW,EACX,IAAc,EACd,UAAkB,EAClB,YAAY,EACZ,KAAK,EACL,eAAe,EACf,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,gBAAgB,EAChB,YAAY,EACZ,GAAG,EACH,EAAE,EAAE,MAAM,EACV,GAAG,SAAS,EACb,EAAE,cAAc,+BAochB;yBAnee,SAAS"}
1
+ {"version":3,"file":"FileInput.d.ts","sourceRoot":"","sources":["../../src/FileInput/FileInput.tsx"],"names":[],"mappings":"AAuCA,OAAO,EAGL,KAAK,WAAW,EAChB,KAAK,kBAAkB,EACxB,MAAM,UAAU,CAAC;AAUlB,YAAY,EACV,WAAW,IAAI,eAAe,EAC9B,eAAe,IAAI,mBAAmB,GACvC,MAAM,UAAU,CAAC;AAGlB,OAAO,EACL,KAAK,mBAAmB,EAEzB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAC,SAAS,EAAC,MAAM,gBAAgB,CAAC;AAmP9C,MAAM,WAAW,cAAe,SAAQ,IAAI,CAC1C,mBAAmB,EACnB,UAAU,GAAG,cAAc,GAAG,OAAO,CACtC;IACC,GAAG,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;IAClC;;OAEG;IACH,KAAK,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;OAEG;IACH,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,CAAC;IAC5B;;OAEG;IACH,QAAQ,EAAE,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,KAAK,IAAI,CAAC;IAChD;;;OAGG;IACH,YAAY,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,GAAG,IAAI,EAAE,GAAG,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAC9D;;;OAGG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;;OAIG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;;;;;;;;;;;;;;;;OAmBG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;OAGG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;OAEG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,kBAAkB,CAAC;IACnC;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,IAAI,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC;IAC5B;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;;;;OAIG;IACH,KAAK,CAAC,EAAE,SAAS,CAAC;IAClB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;;;;GAOG;AACH,wBAAgB,SAAS,CAAC,EACxB,KAAK,EACL,aAAqB,EACrB,KAAK,EACL,QAAQ,EACR,YAAY,EACZ,MAAM,EACN,UAAkB,EAClB,OAAO,EACP,QAAQ,EACR,UAAkB,EAClB,eAAe,EACf,UAAkB,EAClB,SAAiB,EACjB,MAAM,EAAE,UAAU,EAClB,aAA0B,EAC1B,WAAW,EACX,WAAW,EACX,IAAc,EACd,UAAkB,EAClB,YAAY,EACZ,KAAK,EACL,eAAe,EACf,kBAAkB,EAClB,cAAc,EACd,aAAa,EACb,gBAAgB,EAChB,YAAY,EACZ,GAAG,EACH,EAAE,EAAE,MAAM,EACV,GAAG,SAAS,EACb,EAAE,cAAc,+BAmdhB;yBAlfe,SAAS"}
@@ -24,6 +24,7 @@ import { Icon } from "../Icon/index.js";
24
24
  import { Spinner } from "../Spinner/index.js";
25
25
  import { VisuallyHidden } from "../VisuallyHidden/index.js";
26
26
  import { useAnnounce } from "../hooks/useAnnounce.js";
27
+ import { useBusyAnnouncement } from "../hooks/useBusyAnnouncement.js";
27
28
  import { useInputStatusIcon } from "../hooks/useInputStatusIcon.js";
28
29
  import { useClickableContainer } from "../hooks/useClickableContainer.js";
29
30
  import { useTooltip } from "../Tooltip/index.js";
@@ -232,6 +233,16 @@ export function FileInput({
232
233
  const [, startTransition] = useTransition();
233
234
  const [optimisticValue, setOptimisticValue] = useOptimistic(value);
234
235
  const isBusy = isLoading || optimisticValue !== value;
236
+ // A pick is one user action, already announced as "file selected"; a busy
237
+ // period it starts (changeAction, or a caller setting isLoading from
238
+ // onChange) adds no second message (spec:AST-086 FR6). The mark lasts until
239
+ // the field is idle again. Other busy starts announce; the Spinner stays
240
+ // decorative (FR8).
241
+ const [isPickAnnounced, setIsPickAnnounced] = useState(false);
242
+ if (isPickAnnounced && !isBusy) {
243
+ setIsPickAnnounced(false);
244
+ }
245
+ useBusyAnnouncement(isBusy && !isPickAnnounced, t('@astryx.spinner.loading'), containerRef);
235
246
 
236
247
  // Announce successful file selection to screen readers via a persistent
237
248
  // live region (forms-17). Validation errors are announced (assertively) by
@@ -299,6 +310,7 @@ export function FileInput({
299
310
  // status mounts, so only announce the attach here (do not
300
311
  // double-announce errors).
301
312
  if (errors.length === 0) {
313
+ setIsPickAnnounced(true);
302
314
  announce(valid.length === 1 ? t('@astryx.fileInput.fileSelected', {
303
315
  fileName: valid[0].name
304
316
  }) : t('@astryx.fileInput.filesSelected', {
@@ -414,7 +426,8 @@ export function FileInput({
414
426
  const renderDropzoneContent = () => {
415
427
  if (isBusy) {
416
428
  return /*#__PURE__*/_jsx(Spinner, {
417
- size: "md"
429
+ size: "md",
430
+ "aria-hidden": "true"
418
431
  });
419
432
  }
420
433
  if (hasFiles) {
@@ -450,7 +463,8 @@ export function FileInput({
450
463
  },
451
464
  children: fileNames ?? displayPlaceholder
452
465
  }), /*#__PURE__*/_jsx(Spinner, {
453
- size: "sm"
466
+ size: "sm",
467
+ "aria-hidden": "true"
454
468
  })]
455
469
  });
456
470
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astryxdesign/core",
3
- "version": "0.7.4-canary.ac8260d",
3
+ "version": "0.7.4-canary.ad6782d",
4
4
  "displayName": "Astryx Core",
5
5
  "description": "The component library. Accessible, themeable React components with built-in spacing, dark mode, and StyleX styling.",
6
6
  "author": "Meta Open Source",
@@ -792,8 +792,8 @@
792
792
  "react-dom": ">=19.0.0"
793
793
  },
794
794
  "devDependencies": {
795
- "@astryxdesign/a11y-spec": "0.7.4-canary.ac8260d",
796
- "@astryxdesign/cli": "0.7.4-canary.ac8260d",
795
+ "@astryxdesign/a11y-spec": "0.7.4-canary.ad6782d",
796
+ "@astryxdesign/cli": "0.7.4-canary.ad6782d",
797
797
  "@babel/cli": "^7.29.7",
798
798
  "@babel/core": "^7.29.7",
799
799
  "@babel/preset-react": "^7.29.7",
@@ -15,6 +15,7 @@ verified_by:
15
15
  packages/core/src/BottomSheet/BottomSheet.test.tsx,
16
16
  packages/core/src/BottomSheet/BottomSheetPanel.test.tsx,
17
17
  packages/core/src/BottomSheet/BottomSheetKeyboard.test.tsx,
18
+ packages/core/src/BottomSheet/__tests__/BottomSheetNativeModal.a11y.browser.spec.ts,
18
19
  packages/core/src/BottomSheet/__tests__/BottomSheetKeyboard.a11y.browser.spec.ts,
19
20
  apps/storybook/stories/BottomSheet.stories.tsx,
20
21
  scripts/check-knowledge.mjs,
@@ -148,15 +148,38 @@ describe('BottomSheetEdgeTint', () => {
148
148
  expect(tints()).toHaveLength(1);
149
149
  });
150
150
 
151
- it('gives a modal switcher flow exactly one tint', () => {
152
- render(
151
+ it('gives a modal switcher flow exactly one tint at rest, and one per presented dialog through a handoff', () => {
152
+ const {rerender} = render(
153
153
  <BottomSheetSwitcher activeSheet="comment" onActiveSheetChange={() => {}}>
154
154
  <BottomSheet sheetId="comment" label="Add a comment">
155
155
  Comment
156
156
  </BottomSheet>
157
+ <BottomSheet sheetId="confirmation" label="Confirmation">
158
+ Confirmation
159
+ </BottomSheet>
157
160
  </BottomSheetSwitcher>,
158
161
  );
159
162
  expect(tints()).toHaveLength(1);
163
+ expect(tints()[0]?.closest('dialog')?.getAttribute('aria-label')).toBe(
164
+ 'Add a comment',
165
+ );
166
+
167
+ rerender(
168
+ <BottomSheetSwitcher
169
+ activeSheet="confirmation"
170
+ onActiveSheetChange={() => {}}>
171
+ <BottomSheet sheetId="comment" label="Add a comment">
172
+ Comment
173
+ </BottomSheet>
174
+ <BottomSheet sheetId="confirmation" label="Confirmation">
175
+ Confirmation
176
+ </BottomSheet>
177
+ </BottomSheetSwitcher>,
178
+ );
179
+ // Mid-handoff both dialogs are presented; each carries its own tint.
180
+ expect(
181
+ tints().map(tint => tint.closest('dialog')?.getAttribute('aria-label')),
182
+ ).toEqual(['Add a comment', 'Confirmation']);
160
183
  });
161
184
 
162
185
  it('keeps the tint out of the accessibility tree and out of hit testing', async () => {
@@ -13,6 +13,7 @@ review_triggers: [public-api, behavior, layout, theming, accessibility]
13
13
  verified_by:
14
14
  [
15
15
  packages/core/src/BottomSheet/BottomSheetSwitcher.test.tsx,
16
+ packages/core/src/BottomSheet/__tests__/BottomSheetNativeModal.a11y.browser.spec.ts,
16
17
  apps/storybook/stories/BottomSheetSwitcher.stories.tsx,
17
18
  scripts/check-knowledge.mjs,
18
19
  ]
@@ -192,12 +193,12 @@ Consumer migration instructions belong in consumer docs and release notes.
192
193
 
193
194
  ## Verification map
194
195
 
195
- | Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
196
- | ---------------- | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
197
- | FR1–FR4, FR8 | `BottomSheetSwitcher.test.tsx` | closed, first open, handoffs in either completion order, rapid replacement, unmount, close | A child becomes interactive at the wrong time, a retained child disappears early, a second backdrop paints, or a sheet dialog's lifecycle breaks. | `audit:BottomSheetSwitcher/behavior` |
198
- | FR5–FR7, AR1–AR3 | `BottomSheetSwitcher.test.tsx`; `BottomSheetNativeModal.a11y.browser.spec.ts` (implementation gap: not yet in the tree) | modal/non-modal, info/form/required, nested layer, IME, focus return, scroll lock in engines, non-modal local ordering | Modality, dismissal order, naming, inertness, scroll lock, or focus behavior diverges, or a sheet dialog takes a page-level z-index. | `audit:BottomSheetSwitcher/accessibility` |
199
- | FR9 | `BottomSheetSwitcher.test.tsx`; export checks | ref across open/handoff/close/unmount, callback-ref cleanup, `id` once, DOM/ARIA/data/events, class, style, xstyle | A supported input is dropped or duplicated, an object ref is null while a sheet is mounted or skips a cleanup, or an input overrides component-owned semantics accidentally. | `audit:BottomSheetSwitcher/api` |
200
- | Theming anatomy | `scripts/check-knowledge.mjs`; theming tests | dialog, delegated sheet panel, scrim | A non-painting host gains a target, a delegated panel loses its owner, or the scrim gap disappears without review. | `audit:BottomSheetSwitcher/theming` |
196
+ | Contract | Verification | Representative states | Mutation or failure expectation | Audit section |
197
+ | ---------------- | ----------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------- |
198
+ | FR1–FR4, FR8 | `BottomSheetSwitcher.test.tsx` | closed, first open, handoffs in either completion order, rapid replacement, unmount, close | A child becomes interactive at the wrong time, a retained child disappears early, a second backdrop paints, or a sheet dialog's lifecycle breaks. | `audit:BottomSheetSwitcher/behavior` |
199
+ | FR5–FR7, AR1–AR3 | `BottomSheetSwitcher.test.tsx`; `BottomSheetNativeModal.a11y.browser.spec.ts` | modal/non-modal, info/form/required, nested layer, IME, focus return, scroll lock in engines, non-modal local ordering | Modality, dismissal order, naming, inertness, scroll lock, or focus behavior diverges, or a sheet dialog takes a page-level z-index. | `audit:BottomSheetSwitcher/accessibility` |
200
+ | FR9 | `BottomSheetSwitcher.test.tsx`; export checks | ref across open/handoff/close/unmount, callback-ref cleanup, `id` once, DOM/ARIA/data/events, class, style, xstyle | A supported input is dropped or duplicated, an object ref is null while a sheet is mounted or skips a cleanup, or an input overrides component-owned semantics accidentally. | `audit:BottomSheetSwitcher/api` |
201
+ | Theming anatomy | `scripts/check-knowledge.mjs`; theming tests | dialog, delegated sheet panel, scrim | A non-painting host gains a target, a delegated panel loses its owner, or the scrim gap disappears without review. | `audit:BottomSheetSwitcher/theming` |
201
202
 
202
203
  ## Decision log
203
204
 
@@ -10,7 +10,7 @@
10
10
  * update these tests to match the public behavior.
11
11
  */
12
12
 
13
- import {fireEvent, render, screen} from '@testing-library/react';
13
+ import {act, fireEvent, render, screen} from '@testing-library/react';
14
14
  import {
15
15
  StrictMode,
16
16
  createRef,
@@ -22,6 +22,9 @@ import {
22
22
  import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
23
23
  import {hasActiveFocusTrapEscape, useFocusTrap} from '../hooks';
24
24
  import {useLayerDismissal} from '../Layer/useLayerDismissal';
25
+ import {Dialog} from '../Dialog';
26
+ import {hydrateRoot} from 'react-dom/client';
27
+ import {renderToString} from 'react-dom/server';
25
28
  import {BottomSheet} from './BottomSheet';
26
29
  import {BottomSheetSwitcher} from './BottomSheetSwitcher';
27
30
 
@@ -260,6 +263,12 @@ function RequiredConfirmFlow() {
260
263
  );
261
264
  }
262
265
 
266
+ /**
267
+ * A three-step flow that mounts closed, for the host-dialog contract: the
268
+ * switcher's ref, `id`, and `data-testid`. `onMountLayout` and
269
+ * `onMountPassive` run in the consumer's own mount effects, where a parent
270
+ * would first read the ref.
271
+ */
263
272
  function HostFlow({
264
273
  dialogRef,
265
274
  dialogProps,
@@ -344,6 +353,50 @@ function isScrollLockEngaged(): boolean {
344
353
  return document.body.style.position === 'fixed';
345
354
  }
346
355
 
356
+ /** A two-step flow whose second step opens a Core Dialog above itself. */
357
+ function DialogInStepFlow() {
358
+ const [activeSheet, setActiveSheet] = useState<string | null>(null);
359
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
360
+ return (
361
+ <>
362
+ <button type="button" onClick={() => setActiveSheet('details')}>
363
+ Start flow
364
+ </button>
365
+ <BottomSheetSwitcher
366
+ activeSheet={activeSheet}
367
+ onActiveSheetChange={setActiveSheet}>
368
+ <BottomSheet
369
+ sheetId="details"
370
+ label="Details"
371
+ data-testid="details-sheet">
372
+ <button type="button" onClick={() => setActiveSheet('confirm')}>
373
+ Continue
374
+ </button>
375
+ </BottomSheet>
376
+ <BottomSheet
377
+ sheetId="confirm"
378
+ label="Confirm"
379
+ data-testid="confirm-sheet">
380
+ <button type="button" onClick={() => setIsDialogOpen(true)}>
381
+ Open dialog
382
+ </button>
383
+ <Dialog
384
+ isOpen={isDialogOpen}
385
+ onOpenChange={setIsDialogOpen}
386
+ aria-label="Are you sure">
387
+ <button type="button" onClick={() => setIsDialogOpen(false)}>
388
+ Close dialog
389
+ </button>
390
+ </Dialog>
391
+ <button type="button" onClick={() => setActiveSheet(null)}>
392
+ Done
393
+ </button>
394
+ </BottomSheet>
395
+ </BottomSheetSwitcher>
396
+ </>
397
+ );
398
+ }
399
+
347
400
  /**
348
401
  * Records every native dialog call with the dialog's accessible label, and
349
402
  * returns focus the way Chromium and WebKit do: close() on a dialog presented
@@ -1352,6 +1405,42 @@ describe('BottomSheetSwitcher', () => {
1352
1405
  expect(window.scrollTo).toHaveBeenCalledWith(0, 120);
1353
1406
  });
1354
1407
 
1408
+ it('keeps the lock engaged under a Core Dialog opened from a step, and the Dialog paints above the step', () => {
1409
+ render(<DialogInStepFlow />);
1410
+ fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));
1411
+ fireEvent.click(screen.getByRole('button', {name: 'Continue'}));
1412
+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');
1413
+ finishSheetTransition(getSheetLayer('details-sheet'), 'opacity');
1414
+ const confirmDialog = getSheetDialog('confirm-sheet');
1415
+
1416
+ fireEvent.click(screen.getByRole('button', {name: 'Open dialog'}));
1417
+ const dialog = screen.getByRole('dialog', {name: 'Are you sure'});
1418
+ expect(dialog).toHaveAttribute('open');
1419
+ // The Dialog was presented after the step's dialog, so the top layer
1420
+ // paints it above; the Dialog and the flow share the lock's counter,
1421
+ // so the step beneath keeps the pin when the Dialog gives its hold back.
1422
+ expect(HTMLDialogElement.prototype.showModal).toHaveBeenLastCalledWith();
1423
+ expect(
1424
+ vi.mocked(HTMLDialogElement.prototype.showModal).mock.contexts.at(-1),
1425
+ ).toBe(dialog);
1426
+ expect(confirmDialog).toHaveAttribute('open');
1427
+ expect(isScrollLockEngaged()).toBe(true);
1428
+
1429
+ expect(window.scrollTo).not.toHaveBeenCalled();
1430
+
1431
+ // Escape reaches the Dialog first, not the step beneath it.
1432
+ fireEvent.keyDown(dialog, {key: 'Escape'});
1433
+ expect(dialog).not.toHaveAttribute('open');
1434
+ expect(confirmDialog).toHaveAttribute('open');
1435
+ expect(isScrollLockEngaged()).toBe(true);
1436
+ expect(window.scrollTo).not.toHaveBeenCalled();
1437
+
1438
+ fireEvent.click(screen.getByRole('button', {name: 'Done'}));
1439
+ finishSheetTransition(getSheetLayer('confirm-sheet'), 'transform');
1440
+ expect(isScrollLockEngaged()).toBe(false);
1441
+ expect(window.scrollTo).toHaveBeenCalledTimes(1);
1442
+ });
1443
+
1355
1444
  it("resolves the switcher ref to the host sheet's dialog and never to null while a sheet is mounted, from the first commit on", () => {
1356
1445
  const dialogRef = createRef<HTMLDialogElement>();
1357
1446
  const seenAtMount: {layout?: Element | null; passive?: Element | null} =
@@ -1473,6 +1562,88 @@ describe('BottomSheetSwitcher', () => {
1473
1562
  expect(withId()).toEqual([dialogs[1]]);
1474
1563
  });
1475
1564
 
1565
+ it("renders the switcher id and data-testid once, on the active sheet's dialog, in the server markup of a flow that mounts open", () => {
1566
+ // The active sheet is known from props, so the host needs no commit:
1567
+ // server markup carries both attributes on that sheet's dialog, once.
1568
+ const markup = renderToString(
1569
+ <BottomSheetSwitcher
1570
+ id="checkout"
1571
+ data-testid="checkout-flow"
1572
+ activeSheet="confirm"
1573
+ onActiveSheetChange={() => {}}>
1574
+ <BottomSheet sheetId="details" label="Details">
1575
+ Content
1576
+ </BottomSheet>
1577
+ <BottomSheet sheetId="confirm" label="Confirm">
1578
+ Content
1579
+ </BottomSheet>
1580
+ </BottomSheetSwitcher>,
1581
+ );
1582
+ const dialogs = markup.match(/<dialog\b[^>]*>/g) ?? [];
1583
+ expect(dialogs).toHaveLength(2);
1584
+ expect(markup.match(/id="checkout"/g)).toHaveLength(1);
1585
+ expect(markup.match(/data-testid="checkout-flow"/g)).toHaveLength(1);
1586
+ const host = dialogs.find(tag => tag.includes('id="checkout"'));
1587
+ expect(host).toContain('aria-label="Confirm"');
1588
+ expect(host).toContain('data-testid="checkout-flow"');
1589
+ expect(
1590
+ dialogs.find(tag => tag.includes('aria-label="Details"')),
1591
+ ).not.toContain('id=');
1592
+ });
1593
+
1594
+ it('renders every sheet dialog closed in server markup, with the switcher id on no element until the first commit', () => {
1595
+ // Which sheet mounts first is known once its dialog registers during
1596
+ // the first commit; server rendering has no commit, so the id waits for
1597
+ // the client. What server markup must still get right: one closed
1598
+ // dialog per sheet, none `open`, and the id never duplicated.
1599
+ const markup = renderToString(
1600
+ <BottomSheetSwitcher
1601
+ id="checkout"
1602
+ data-testid="checkout-flow"
1603
+ activeSheet={null}
1604
+ onActiveSheetChange={() => {}}>
1605
+ <BottomSheet sheetId="details" label="Details">
1606
+ Content
1607
+ </BottomSheet>
1608
+ <BottomSheet sheetId="confirm" label="Confirm">
1609
+ Content
1610
+ </BottomSheet>
1611
+ </BottomSheetSwitcher>,
1612
+ );
1613
+ expect(markup.match(/<dialog\b/g)).toHaveLength(2);
1614
+ expect(markup).not.toMatch(/<dialog[^>]*\sopen/);
1615
+ expect(markup.match(/id="checkout"/g) ?? []).toHaveLength(0);
1616
+
1617
+ // Hydrating the same tree on the client: the first commit's synchronous
1618
+ // re-render puts the id on the first sheet's dialog, exactly once.
1619
+ const container = document.createElement('div');
1620
+ container.innerHTML = markup;
1621
+ document.body.appendChild(container);
1622
+ act(() => {
1623
+ hydrateRoot(
1624
+ container,
1625
+ <BottomSheetSwitcher
1626
+ id="checkout"
1627
+ data-testid="checkout-flow"
1628
+ activeSheet={null}
1629
+ onActiveSheetChange={() => {}}>
1630
+ <BottomSheet sheetId="details" label="Details">
1631
+ Content
1632
+ </BottomSheet>
1633
+ <BottomSheet sheetId="confirm" label="Confirm">
1634
+ Content
1635
+ </BottomSheet>
1636
+ </BottomSheetSwitcher>,
1637
+ );
1638
+ });
1639
+ const withId = container.querySelectorAll('[id="checkout"]');
1640
+ expect(withId).toHaveLength(1);
1641
+ expect(withId[0]).toBe(container.querySelector('dialog'));
1642
+ expect(withId[0]).toHaveAttribute('data-testid', 'checkout-flow');
1643
+ expect(withId[0]).toHaveAttribute('aria-label', 'Details');
1644
+ container.remove();
1645
+ });
1646
+
1476
1647
  it('orders a non-modal handoff inside the switcher-owned isolation surface, with no page-wide z-index on a sheet dialog', () => {
1477
1648
  render(<HostFlow hasScrim={false} initialSheet="details" />);
1478
1649
  const detailsDialog = getSheetDialog('details-sheet');
@@ -1544,6 +1715,55 @@ describe('BottomSheetSwitcher', () => {
1544
1715
  expect(getSheetDialog('b')).toHaveAttribute('aria-label', 'Confirm');
1545
1716
  });
1546
1717
 
1718
+ it('forces alertdialog on a required step and leaves the other sheet dialogs with no role when the switcher sets none', () => {
1719
+ render(
1720
+ <BottomSheetSwitcher
1721
+ activeSheet="details"
1722
+ onActiveSheetChange={() => {}}>
1723
+ <BottomSheet sheetId="details" label="Details" data-testid="a">
1724
+ Content
1725
+ </BottomSheet>
1726
+ <BottomSheet
1727
+ sheetId="danger"
1728
+ label="Danger"
1729
+ purpose="required"
1730
+ data-testid="c">
1731
+ Content
1732
+ </BottomSheet>
1733
+ </BottomSheetSwitcher>,
1734
+ );
1735
+ expect(getSheetDialog('a')).not.toHaveAttribute('role');
1736
+ expect(getSheetDialog('c')).toHaveAttribute('role', 'alertdialog');
1737
+ });
1738
+
1739
+ it('keeps the scrim takeover pin under prefers-reduced-motion: the reduced duration reads the pinned variable', () => {
1740
+ render(<HostFlow initialSheet="details" />);
1741
+ // jsdom evaluates neither @media nor ::backdrop; read the compiled
1742
+ // rules the dialog's scrim class produced. The reduced-motion rule for
1743
+ // the backdrop's transition-duration must defer to the takeover pin
1744
+ // (`--_sheet-scrim-duration: 0s` for one style flush); a literal 0.01s
1745
+ // there would win the cascade and paint a frame with no scrim.
1746
+ const rules: string[] = [];
1747
+ for (const sheet of Array.from(document.styleSheets)) {
1748
+ for (const rule of Array.from(sheet.cssRules)) {
1749
+ rules.push(rule.cssText);
1750
+ }
1751
+ }
1752
+ const reducedBackdropDurations = rules.filter(
1753
+ text =>
1754
+ text.includes('prefers-reduced-motion: reduce') &&
1755
+ text.includes('::backdrop') &&
1756
+ text.includes('transition-duration'),
1757
+ );
1758
+ expect(reducedBackdropDurations.length).toBeGreaterThan(0);
1759
+ for (const text of reducedBackdropDurations) {
1760
+ expect(text).toMatch(
1761
+ /transition-duration:\s*var\(--_sheet-scrim-duration,\s*0?\.01s\)/,
1762
+ );
1763
+ expect(text).not.toMatch(/transition-duration:\s*0?\.01s/);
1764
+ }
1765
+ });
1766
+
1547
1767
  it('paints one scrim through a handoff and hands it over without a fade', () => {
1548
1768
  render(<Flow />);
1549
1769
  fireEvent.click(screen.getByRole('button', {name: 'Start flow'}));
@@ -0,0 +1,461 @@
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+
3
+ /**
4
+ * @file BottomSheetNativeModal.a11y.browser.spec.ts
5
+ * @input The `Core/BottomSheetSwitcher` stories in a built Storybook, and
6
+ * real Chromium/WebKit wheel, keyboard, and pointer input.
7
+ * @output Browser evidence for a flow whose every sheet owns a native modal
8
+ * dialog: the flow's one page scroll lock (the shared hook, as Dialog)
9
+ * holding while two sheet dialogs are open through a handoff and under a
10
+ * Core Dialog opened from a step, never released between steps nor when
11
+ * that Dialog closes, and the page's offset restored after the exit; Tab landing inside the entering sheet's dialog
12
+ * as soon as both dialogs are open and on Tab stops for as long as the
13
+ * retained dialog is open beneath it (its fade included), never the page
14
+ * once the handoff is done, by the browser's own containment, with the
15
+ * retained dialog carrying `inert` and `aria-hidden` on every step it is
16
+ * open; Escape and
17
+ * the backdrop dismissing by purpose with focus returned to the opener;
18
+ * and one steady scrim through a handoff.
19
+ * @position Cross-browser proof; jsdom presents no dialog and contains no
20
+ * focus, so BottomSheetSwitcher.test.tsx can only assert the calls. WebKit
21
+ * here is desktop WebKit under Playwright, not iOS Safari.
22
+ */
23
+
24
+ import {expect, test, type Page} from '@playwright/test';
25
+ import {
26
+ DEFAULT_STORYBOOK_DIR,
27
+ serveStorybook,
28
+ type StaticServer,
29
+ } from '@astryxdesign/a11y-spec/storybook';
30
+
31
+ let storybook: StaticServer;
32
+ test.beforeAll(async () => {
33
+ storybook = await serveStorybook(
34
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
35
+ );
36
+ });
37
+ test.afterAll(async () => {
38
+ await storybook?.close();
39
+ });
40
+
41
+ test.use({viewport: {width: 390, height: 844}, hasTouch: true});
42
+
43
+ const OPENER = 'Set up notifications';
44
+
45
+ /**
46
+ * Open a switcher story with the flow closed and the page made scrollable:
47
+ * a tall spacer below the story, scrolled part way down, so a lock that
48
+ * fails would show as a change in `scrollY`.
49
+ */
50
+ async function mountScrollable(page: Page, story = 'hug-content') {
51
+ await page.goto(
52
+ `${storybook.origin}/iframe.html?id=core-bottomsheetswitcher--${story}&viewMode=story`,
53
+ );
54
+ // The story's play function opens the flow; start from closed.
55
+ await expect(page.locator('dialog[open]')).toHaveCount(1);
56
+ await page.keyboard.press('Escape');
57
+ await expect(page.locator('dialog[open]')).toHaveCount(0);
58
+ await page.evaluate(() => {
59
+ const spacer = document.createElement('div');
60
+ spacer.id = 'spacer';
61
+ spacer.style.height = '3000px';
62
+ document.body.appendChild(spacer);
63
+ const counter = window as {__scrollEvents?: number};
64
+ counter.__scrollEvents = 0;
65
+ window.addEventListener('scroll', () => {
66
+ counter.__scrollEvents = (counter.__scrollEvents ?? 0) + 1;
67
+ });
68
+ window.scrollTo(0, 300);
69
+ });
70
+ expect(await page.evaluate(() => window.scrollY)).toBe(300);
71
+ }
72
+
73
+ /**
74
+ * The shared lock's pin on <body>, and the page's offset as the lock sees
75
+ * it: while pinned, `scrollY` reads 0 and the saved offset is `top`; after
76
+ * release, `scrollY` is the restored offset. `scrollEvents` counts window
77
+ * scroll events since `resetScrollCounter`: a lock released and re-acquired
78
+ * between steps restores the offset and pins again, which fires one.
79
+ */
80
+ async function lockState(page: Page): Promise<{
81
+ position: string;
82
+ top: string;
83
+ scrollY: number;
84
+ scrollEvents: number;
85
+ }> {
86
+ return page.evaluate(() => ({
87
+ position: document.body.style.position,
88
+ top: document.body.style.top,
89
+ scrollY: window.scrollY,
90
+ scrollEvents: (window as {__scrollEvents?: number}).__scrollEvents ?? 0,
91
+ }));
92
+ }
93
+
94
+ /**
95
+ * Zero the counter once the events already owed have arrived: the spacer
96
+ * scroll in `mountScrollable` and the lock's own pin (300 → 0) each fire one
97
+ * window `scroll` event, and WebKit delivers them late on a cold run.
98
+ */
99
+ async function resetScrollCounter(page: Page) {
100
+ await page
101
+ .waitForFunction(
102
+ () => ((window as {__scrollEvents?: number}).__scrollEvents ?? 0) >= 2,
103
+ undefined,
104
+ {timeout: 3000},
105
+ )
106
+ .catch(() => {});
107
+ await page.evaluate(() => {
108
+ (window as {__scrollEvents?: number}).__scrollEvents = 0;
109
+ });
110
+ }
111
+
112
+ async function wheelDown(page: Page) {
113
+ // Over the top of the viewport: the backdrop when a modal sheet is open,
114
+ // the page otherwise.
115
+ await page.mouse.move(195, 80);
116
+ await page.mouse.wheel(0, 400);
117
+ await page.waitForTimeout(250);
118
+ }
119
+
120
+ /** A finger drag over the backdrop; Chromium only (CDP), WebKit has no API. */
121
+ async function touchScrollDown(page: Page, browserName: string) {
122
+ if (browserName !== 'chromium') {
123
+ return;
124
+ }
125
+ const session = await page.context().newCDPSession(page);
126
+ await session.send('Input.synthesizeScrollGesture', {
127
+ x: 195,
128
+ y: 120,
129
+ yDistance: -300,
130
+ gestureSourceType: 'touch',
131
+ speed: 800,
132
+ });
133
+ await session.detach();
134
+ await page.waitForTimeout(250);
135
+ }
136
+
137
+ /**
138
+ * Open the flow from its opener without scrolling the page: a pointer click
139
+ * would first scroll the opener into view, and the lock tests need the page
140
+ * to stay where it was scrolled. The opener is focused first, as a real
141
+ * activation would leave it, so focus return has somewhere to go.
142
+ */
143
+ async function openFlow(page: Page) {
144
+ await page.evaluate(name => {
145
+ const opener = Array.from(document.querySelectorAll('button')).find(
146
+ button => button.textContent?.trim() === name,
147
+ );
148
+ opener?.focus({preventScroll: true});
149
+ opener?.click();
150
+ }, OPENER);
151
+ await expect(page.getByRole('dialog', {name: OPENER})).toBeVisible();
152
+ await page.waitForTimeout(500);
153
+ }
154
+
155
+ test('the flow holds one page scroll lock through a handoff and under a Core Dialog opened from a step, never released between steps, and restores the offset after the exit', async ({
156
+ page,
157
+ browserName,
158
+ }) => {
159
+ await mountScrollable(page, 'dialog-from-step');
160
+ await openFlow(page);
161
+ let state = await lockState(page);
162
+ expect(state.position).toBe('fixed');
163
+ expect(state.top).toBe('-300px');
164
+ await resetScrollCounter(page);
165
+
166
+ await page.getByRole('button', {name: 'Continue', exact: true}).click();
167
+ await expect(page.locator('dialog[open]')).toHaveCount(2);
168
+ state = await lockState(page);
169
+ expect(state.position).toBe('fixed');
170
+ expect(state.top).toBe('-300px');
171
+ // Wheel and finger over the backdrop with both dialogs open: the pinned
172
+ // page does not move.
173
+ await wheelDown(page);
174
+ await touchScrollDown(page, browserName);
175
+ state = await lockState(page);
176
+ expect(state.position).toBe('fixed');
177
+ expect(state.top).toBe('-300px');
178
+ expect(state.scrollY).toBe(0);
179
+ await expect(page.locator('dialog[open]')).toHaveCount(1, {timeout: 3000});
180
+ // One lock for the flow: the handoff released nothing, so the page never
181
+ // scrolled back and forth between steps.
182
+ state = await lockState(page);
183
+ expect(state.position).toBe('fixed');
184
+ expect(state.scrollEvents).toBe(0);
185
+
186
+ // A Core Dialog opened from the step, as a builder would, takes the same
187
+ // shared lock a second time; closing it must give back only its own hold,
188
+ // leaving the flow's pin in place with the saved offset untouched.
189
+ await page.getByRole('button', {name: 'Reset', exact: true}).click();
190
+ const resetDialog = page.getByRole('dialog', {name: 'Reset frequency?'});
191
+ await expect(resetDialog).toBeVisible();
192
+ await wheelDown(page);
193
+ state = await lockState(page);
194
+ expect(state.position).toBe('fixed');
195
+ expect(state.top).toBe('-300px');
196
+ expect(state.scrollY).toBe(0);
197
+ await page.getByRole('button', {name: 'Keep', exact: true}).click();
198
+ await expect(resetDialog).toBeHidden();
199
+ await page.waitForTimeout(400);
200
+ state = await lockState(page);
201
+ expect(state.position).toBe('fixed');
202
+ expect(state.top).toBe('-300px');
203
+ expect(state.scrollY).toBe(0);
204
+ expect(state.scrollEvents).toBe(0);
205
+ await wheelDown(page);
206
+ expect(await page.evaluate(() => window.scrollY)).toBe(0);
207
+ // The Dialog returned focus into the step, so Escape closes the flow.
208
+ await expect(page.locator('dialog[open]')).toHaveCount(1);
209
+
210
+ await page.keyboard.press('Escape');
211
+ await expect(page.locator('dialog[open]')).toHaveCount(0, {timeout: 3000});
212
+ state = await lockState(page);
213
+ expect(state.position).toBe('');
214
+ expect(state.top).toBe('');
215
+ expect(state.scrollY).toBe(300);
216
+ // The page scrolls again.
217
+ await wheelDown(page);
218
+ expect(await page.evaluate(() => window.scrollY)).toBeGreaterThan(300);
219
+ });
220
+
221
+ /**
222
+ * One synchronous read per step: how many sheet dialogs are open, where focus
223
+ * is (and whether it moved since the last read and sits outside any inert
224
+ * subtree), and whether the retained dialog (by accessible name) still
225
+ * carries `inert` and `aria-hidden`. Read together so a close between two
226
+ * reads cannot make a stale attribute look like a regression, or hide one.
227
+ */
228
+ async function handoffStep(
229
+ page: Page,
230
+ retainedName: string,
231
+ ): Promise<{
232
+ openCount: number;
233
+ /** Page-clock ms since the second dialog opened; -1 before that. */
234
+ sinceBothOpen: number;
235
+ where: string;
236
+ moved: boolean;
237
+ insideInert: boolean;
238
+ retained: {open: boolean; inert: boolean; ariaHidden: string | null} | null;
239
+ }> {
240
+ return page.evaluate(name => {
241
+ const openDialogs = Array.from(document.querySelectorAll('dialog[open]'));
242
+ const clock = window as {__bothOpenAt?: number};
243
+ const sinceBothOpen =
244
+ clock.__bothOpenAt == null
245
+ ? -1
246
+ : Math.round(performance.now() - clock.__bothOpenAt);
247
+ const active = document.activeElement;
248
+ const tracker = window as {__lastActive?: Element | null};
249
+ const moved = active !== tracker.__lastActive;
250
+ tracker.__lastActive = active;
251
+ const insideInert = active?.closest('[inert]') != null;
252
+ const activeDialog = active?.closest('dialog') ?? null;
253
+ const where =
254
+ active == null || active === document.body
255
+ ? 'body'
256
+ : activeDialog == null
257
+ ? 'page'
258
+ : (activeDialog.getAttribute('aria-label') ?? '?');
259
+ const retainedDialog = Array.from(document.querySelectorAll('dialog')).find(
260
+ dialog => dialog.getAttribute('aria-label') === name,
261
+ );
262
+ return {
263
+ openCount: openDialogs.length,
264
+ sinceBothOpen,
265
+ where,
266
+ moved,
267
+ insideInert,
268
+ retained:
269
+ retainedDialog == null
270
+ ? null
271
+ : {
272
+ open: retainedDialog.hasAttribute('open'),
273
+ inert: retainedDialog.hasAttribute('inert'),
274
+ ariaHidden: retainedDialog.getAttribute('aria-hidden'),
275
+ },
276
+ };
277
+ }, retainedName);
278
+ }
279
+
280
+ test('focus is inside the entering sheet as soon as both dialogs are open, and Tab reaches stops inside it for as long as the retained dialog is open, which stays inert and hidden through its fade, and inside the flow after the handoff', async ({
281
+ page,
282
+ }) => {
283
+ await mountScrollable(page);
284
+ await openFlow(page);
285
+ // Stamp the page clock the moment the second dialog opens, so the late
286
+ // window below is measured from the handoff itself, not from when the
287
+ // test runner got around to reading it on a slow run.
288
+ await page.evaluate(() => {
289
+ const clock = window as {__bothOpenAt?: number};
290
+ clock.__bothOpenAt = undefined;
291
+ const observer = new MutationObserver(() => {
292
+ if (
293
+ clock.__bothOpenAt == null &&
294
+ document.querySelectorAll('dialog[open]').length >= 2
295
+ ) {
296
+ clock.__bothOpenAt = performance.now();
297
+ observer.disconnect();
298
+ }
299
+ });
300
+ observer.observe(document.body, {
301
+ subtree: true,
302
+ attributes: true,
303
+ attributeFilter: ['open'],
304
+ });
305
+ });
306
+ await page.getByRole('button', {name: 'Continue', exact: true}).click();
307
+ // Both dialogs are open for the handoff's ~650ms: the retained one holds
308
+ // still, then fades from ~345ms, then closes. Step with Tab until it has
309
+ // closed, reading open count, focus, and the retained dialog's attributes
310
+ // in one evaluate per step: focus must land in the entering sheet's dialog
311
+ // ("Notification frequency"), never in the retained one ("Set up
312
+ // notifications") or the page, and the retained dialog must carry `inert`
313
+ // and `aria-hidden` on every step it is still open, the fade included.
314
+ await expect(page.locator('dialog[open]')).toHaveCount(2);
315
+ // The entering sheet takes focus with its presentation, before any Tab:
316
+ // the moment both dialogs are open, focus is inside "Notification
317
+ // frequency" and outside every inert subtree. An entering sheet made
318
+ // inert while it enters would leave focus on <body> for its first ~300ms.
319
+ const atOpen = await handoffStep(page, OPENER);
320
+ expect(atOpen.openCount).toBe(2);
321
+ expect(atOpen.where, 'focus as soon as both dialogs are open').toBe(
322
+ 'Notification frequency',
323
+ );
324
+ expect(atOpen.insideInert, 'focus inside an inert subtree at open').toBe(
325
+ false,
326
+ );
327
+ expect(atOpen.sinceBothOpen).toBeGreaterThanOrEqual(0);
328
+ let midHandoffPresses = 0;
329
+ let lateHandoffPresses = 0;
330
+ let midHandoffStopsInside = 0;
331
+ let lateHandoffStopsInside = 0;
332
+ for (let index = 0; index < 40; index += 1) {
333
+ await page.keyboard.press('Tab');
334
+ const step = await handoffStep(page, OPENER);
335
+ if (step.openCount < 2 || step.retained?.open !== true) {
336
+ break;
337
+ }
338
+ midHandoffPresses += 1;
339
+ // "Late" is inside the retained dialog's fade (from ~345ms after both
340
+ // opened), on the page's own clock.
341
+ const isLate = step.sinceBothOpen > 400;
342
+ if (isLate) {
343
+ lateHandoffPresses += 1;
344
+ }
345
+ const label = `mid-handoff, Tab ${index + 1} at ${step.sinceBothOpen}ms`;
346
+ expect(step.where, label).not.toBe('page');
347
+ expect(step.where, label).not.toBe(OPENER);
348
+ expect(['Notification frequency', 'body'], label).toContain(step.where);
349
+ // A stop inside the entering sheet is a Tab that moved focus onto a
350
+ // focusable element there, outside any inert subtree; focus merely left
351
+ // where the presentation put it, inside a dialog that went inert, is not.
352
+ expect(step.insideInert, `${label}: focus inside an inert subtree`).toBe(
353
+ false,
354
+ );
355
+ if (step.where === 'Notification frequency' && step.moved) {
356
+ midHandoffStopsInside += 1;
357
+ if (isLate) {
358
+ lateHandoffStopsInside += 1;
359
+ }
360
+ }
361
+ expect(step.retained.inert, `${label}: retained dialog inert`).toBe(true);
362
+ expect(step.retained.ariaHidden, `${label}: retained aria-hidden`).toBe(
363
+ 'true',
364
+ );
365
+ await page.waitForTimeout(40);
366
+ }
367
+ // Presses landed both before and during the retained dialog's fade, else
368
+ // the test proved nothing about the handoff; and at least one of them
369
+ // stopped inside the entering sheet, else an entering sheet that can never
370
+ // take focus (every stop on the browser-UI `body` stop) would pass.
371
+ expect(midHandoffPresses).toBeGreaterThan(2);
372
+ expect(lateHandoffPresses).toBeGreaterThan(0);
373
+ expect(midHandoffStopsInside).toBeGreaterThan(0);
374
+ // ...and at least one of those stops landed inside the retained dialog's
375
+ // fade (from ~345ms), so an entering sheet that went inert only while the
376
+ // retained one fades would not pass.
377
+ expect(lateHandoffStopsInside).toBeGreaterThan(0);
378
+
379
+ await expect(page.locator('dialog[open]')).toHaveCount(1, {timeout: 3000});
380
+ let stopsInside = 0;
381
+ for (let index = 0; index < 8; index += 1) {
382
+ await page.keyboard.press('Tab');
383
+ const step = await handoffStep(page, OPENER);
384
+ expect(step.where, `after the handoff, Tab ${index + 1}`).not.toBe('page');
385
+ expect(['Notification frequency', 'body']).toContain(step.where);
386
+ expect(step.insideInert, `after the handoff, Tab ${index + 1}`).toBe(false);
387
+ if (step.where === 'Notification frequency' && step.moved) {
388
+ stopsInside += 1;
389
+ }
390
+ }
391
+ expect(stopsInside).toBeGreaterThan(0);
392
+ });
393
+
394
+ test('Escape and a backdrop tap dismiss an info flow and return focus to the opener', async ({
395
+ page,
396
+ }) => {
397
+ await mountScrollable(page);
398
+ const opener = page.getByRole('button', {name: OPENER});
399
+ await openFlow(page);
400
+ await page.getByRole('button', {name: 'Continue', exact: true}).click();
401
+ await page.waitForTimeout(900);
402
+
403
+ await page.keyboard.press('Escape');
404
+ await expect(page.locator('dialog[open]')).toHaveCount(0, {timeout: 3000});
405
+ await expect(opener).toBeFocused();
406
+
407
+ await openFlow(page);
408
+ await page.mouse.click(195, 60);
409
+ await expect(page.locator('dialog[open]')).toHaveCount(0, {timeout: 3000});
410
+ await expect(opener).toBeFocused();
411
+ });
412
+
413
+ test('one steady scrim through a handoff: no dip and no double dim', async ({
414
+ page,
415
+ }) => {
416
+ await mountScrollable(page);
417
+ await openFlow(page);
418
+ const samples = await page.evaluate(
419
+ async () =>
420
+ new Promise<number[]>(resolve => {
421
+ const dims: number[] = [];
422
+ const start = performance.now();
423
+ const tick = () => {
424
+ let combined = 1;
425
+ for (const dialog of document.querySelectorAll('dialog[open]')) {
426
+ if (!dialog.matches(':modal')) {
427
+ continue;
428
+ }
429
+ const style = getComputedStyle(dialog, '::backdrop');
430
+ const match = /rgba?\(([^)]+)\)/.exec(style.backgroundColor);
431
+ const parts = match
432
+ ? match[1].split(/[,/]\s*|\s+/).filter(Boolean)
433
+ : [];
434
+ const alpha = parts.length === 4 ? Number(parts[3]) : 1;
435
+ combined *= 1 - alpha * Number(style.opacity);
436
+ }
437
+ dims.push(Number((1 - combined).toFixed(3)));
438
+ if (performance.now() - start < 1100) {
439
+ requestAnimationFrame(tick);
440
+ } else {
441
+ resolve(dims);
442
+ }
443
+ };
444
+ Array.from(
445
+ document.querySelectorAll<HTMLButtonElement>(
446
+ 'dialog[open]:not([inert]) button',
447
+ ),
448
+ )
449
+ .find(button => button.textContent?.trim() === 'Continue')
450
+ ?.click();
451
+ requestAnimationFrame(tick);
452
+ }),
453
+ );
454
+ expect(samples.length).toBeGreaterThan(20);
455
+ const steady = samples[0];
456
+ expect(steady).toBeGreaterThan(0.3);
457
+ for (const dim of samples) {
458
+ expect(dim).toBeGreaterThanOrEqual(steady * 0.9);
459
+ expect(dim).toBeLessThanOrEqual(steady * 1.05);
460
+ }
461
+ });
@@ -47,6 +47,7 @@ import {Icon} from '../Icon';
47
47
  import {Spinner} from '../Spinner';
48
48
  import {VisuallyHidden} from '../VisuallyHidden';
49
49
  import {useAnnounce} from '../hooks/useAnnounce';
50
+ import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';
50
51
  import {useInputStatusIcon} from '../hooks/useInputStatusIcon';
51
52
  import {useClickableContainer} from '../hooks/useClickableContainer';
52
53
  import {useTooltip} from '../Tooltip';
@@ -490,6 +491,20 @@ export function FileInput({
490
491
  const [, startTransition] = useTransition();
491
492
  const [optimisticValue, setOptimisticValue] = useOptimistic(value);
492
493
  const isBusy = isLoading || optimisticValue !== value;
494
+ // A pick is one user action, already announced as "file selected"; a busy
495
+ // period it starts (changeAction, or a caller setting isLoading from
496
+ // onChange) adds no second message (spec:AST-086 FR6). The mark lasts until
497
+ // the field is idle again. Other busy starts announce; the Spinner stays
498
+ // decorative (FR8).
499
+ const [isPickAnnounced, setIsPickAnnounced] = useState(false);
500
+ if (isPickAnnounced && !isBusy) {
501
+ setIsPickAnnounced(false);
502
+ }
503
+ useBusyAnnouncement(
504
+ isBusy && !isPickAnnounced,
505
+ t('@astryx.spinner.loading'),
506
+ containerRef,
507
+ );
493
508
 
494
509
  // Announce successful file selection to screen readers via a persistent
495
510
  // live region (forms-17). Validation errors are announced (assertively) by
@@ -580,6 +595,7 @@ export function FileInput({
580
595
  // status mounts, so only announce the attach here (do not
581
596
  // double-announce errors).
582
597
  if (errors.length === 0) {
598
+ setIsPickAnnounced(true);
583
599
  announce(
584
600
  valid.length === 1
585
601
  ? t('@astryx.fileInput.fileSelected', {fileName: valid[0].name})
@@ -741,7 +757,7 @@ export function FileInput({
741
757
 
742
758
  const renderDropzoneContent = () => {
743
759
  if (isBusy) {
744
- return <Spinner size="md" />;
760
+ return <Spinner size="md" aria-hidden="true" />;
745
761
  }
746
762
  if (hasFiles) {
747
763
  return (
@@ -772,7 +788,7 @@ export function FileInput({
772
788
  <span {...stylex.props(styles.fileNameText)}>
773
789
  {fileNames ?? displayPlaceholder}
774
790
  </span>
775
- <Spinner size="sm" />
791
+ <Spinner size="sm" aria-hidden="true" />
776
792
  </>
777
793
  );
778
794
  }
@@ -8,7 +8,13 @@
8
8
  * owning control announces each busy start once through the shared channel
9
9
  */
10
10
 
11
- import {StrictMode, useEffect, useRef, type ReactElement} from 'react';
11
+ import {
12
+ StrictMode,
13
+ useEffect,
14
+ useRef,
15
+ useState,
16
+ type ReactElement,
17
+ } from 'react';
12
18
  import {
13
19
  afterAll,
14
20
  afterEach,
@@ -30,6 +36,7 @@ import {DateRangeInput} from '../DateRangeInput';
30
36
  import {DateTimeInput} from '../DateTimeInput';
31
37
  import {TimeInput} from '../TimeInput';
32
38
  import {CheckboxInput} from '../CheckboxInput';
39
+ import {FileInput} from '../FileInput';
33
40
  import {Thumbnail} from '../Thumbnail';
34
41
  import {
35
42
  DropdownMenu,
@@ -156,6 +163,21 @@ const OWNERS: ReadonlyArray<
156
163
  <Thumbnail src="/local.jpg" alt="Upload" isLoading={isLoading} />
157
164
  ),
158
165
  ],
166
+ ...(['dropzone', 'input'] as const).map(
167
+ mode =>
168
+ [
169
+ `FileInput (${mode})`,
170
+ (isLoading: boolean) => (
171
+ <FileInput
172
+ label="Attachment"
173
+ mode={mode}
174
+ value={null}
175
+ onChange={() => {}}
176
+ isLoading={isLoading}
177
+ />
178
+ ),
179
+ ] as const,
180
+ ),
159
181
  [
160
182
  'DateRangeInput',
161
183
  isLoading => (
@@ -574,3 +596,117 @@ describe('ChatMessageList top loader (spec:AST-086 FR4, FR8)', () => {
574
596
  expect(busyAnnouncements()).toEqual([['Loading', 'polite']]);
575
597
  });
576
598
  });
599
+
600
+ describe('FileInput busy start from a pick or a clear (spec:AST-086 FR6, FR8)', () => {
601
+ const file = new File(['x'], 'report.pdf', {type: 'application/pdf'});
602
+
603
+ it('keeps a pick under a pending changeAction to its one "selected" message', async () => {
604
+ const {container} = render(
605
+ strict(
606
+ <FileInput
607
+ label="Attachment"
608
+ value={null}
609
+ onChange={() => {}}
610
+ changeAction={async () => new Promise<void>(() => {})}
611
+ />,
612
+ ),
613
+ );
614
+ act(() => {
615
+ fireEvent.change(
616
+ container.querySelector('input[type="file"]') as HTMLInputElement,
617
+ {target: {files: [file]}},
618
+ );
619
+ });
620
+ await nextFrame();
621
+ expect(container.querySelector('.astryx-spinner')).toHaveAttribute(
622
+ 'aria-hidden',
623
+ 'true',
624
+ );
625
+ expect(announce).toHaveBeenCalledWith('1 file selected: report.pdf');
626
+ expect(busyAnnouncements()).toEqual([]);
627
+ });
628
+
629
+ it('keeps a pick whose onChange starts an upload (isLoading) to its one "selected" message', async () => {
630
+ function Uploader() {
631
+ const [value, setValue] = useState<File | null>(null);
632
+ const [isLoading, setIsLoading] = useState(false);
633
+ return (
634
+ <FileInput
635
+ label="Attachment"
636
+ value={value}
637
+ isLoading={isLoading}
638
+ onChange={next => {
639
+ setValue(next as File | null);
640
+ setIsLoading(true);
641
+ }}
642
+ />
643
+ );
644
+ }
645
+ const {container} = render(strict(<Uploader />));
646
+ act(() => {
647
+ fireEvent.change(
648
+ container.querySelector('input[type="file"]') as HTMLInputElement,
649
+ {target: {files: [file]}},
650
+ );
651
+ });
652
+ await nextFrame();
653
+ await nextFrame();
654
+ expect(announce).toHaveBeenCalledWith('1 file selected: report.pdf');
655
+ expect(busyAnnouncements()).toEqual([]);
656
+ });
657
+
658
+ it('announces nothing more when an earlier pick settles while a later one is still pending', async () => {
659
+ const settles: (() => void)[] = [];
660
+ const {container} = render(
661
+ strict(
662
+ <FileInput
663
+ label="Attachment"
664
+ value={null}
665
+ onChange={() => {}}
666
+ changeAction={async () =>
667
+ new Promise<void>(resolve => {
668
+ settles.push(resolve);
669
+ })
670
+ }
671
+ />,
672
+ ),
673
+ );
674
+ const input = container.querySelector(
675
+ 'input[type="file"]',
676
+ ) as HTMLInputElement;
677
+ act(() => {
678
+ fireEvent.change(input, {target: {files: [file]}});
679
+ });
680
+ await nextFrame();
681
+ act(() => {
682
+ fireEvent.change(input, {
683
+ target: {files: [new File(['y'], 'notes.txt', {type: 'text/plain'})]},
684
+ });
685
+ });
686
+ await nextFrame();
687
+ await act(async () => {
688
+ settles[0]();
689
+ });
690
+ await nextFrame();
691
+ await nextFrame();
692
+ expect(busyAnnouncements()).toEqual([]);
693
+ });
694
+
695
+ it('announces the busy start of a clear under a pending changeAction', async () => {
696
+ render(
697
+ strict(
698
+ <FileInput
699
+ label="Attachment"
700
+ value={file}
701
+ onChange={() => {}}
702
+ changeAction={async () => new Promise<void>(() => {})}
703
+ />,
704
+ ),
705
+ );
706
+ act(() => {
707
+ fireEvent.click(screen.getByRole('button', {name: /Clear/}));
708
+ });
709
+ await nextFrame();
710
+ expect(busyAnnouncements()).toEqual([['Loading', 'polite']]);
711
+ });
712
+ });