An open source design system that's fully customizable and agent ready
TypeScript
fix(DateInput): a press in the field's own input, clear button or label keeps the calendar open (#9433)
Cindy Zhangbeb03f8bd712
diff --git a/.changeset/dateinput-input-press-keeps-calendar.md b/.changeset/dateinput-input-press-keeps-calendar.mdnew file mode 100644index 0000000000..2a440d04ba--- /dev/null+++ b/.changeset/dateinput-input-press-keeps-calendar.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] A press in a DateInput's own text input, on its clear button or on its label no longer closes its open calendar. Clicking into the date text to fix a digit keeps the calendar showing; a press anywhere else on the page and Escape still close it, and moving focus from anywhere in the field (its text, clear button or calendar button) to another field now closes it too.++@cixzhangdiff --git a/docs/architecture/layer-runtime.md b/docs/architecture/layer-runtime.mdindex 4758058426..2515f6f035 100644--- a/docs/architecture/layer-runtime.md+++ b/docs/architecture/layer-runtime.md@@ -300,14 +300,14 @@ during a press so native light dismissal does not mistake them for outsideinteraction. Their click action is cancelled as an invoker toggle so the controlcan perform its own action without closing the layer.-A text input cannot be an invoker, so BaseTypeahead's list, DateTimeInput's-time list and ChatComposerInput's trigger menu, which their text fields own,-are manual popovers. A press that starts and ends on the field's input or its-buttons, or in the list, is inside, judged across open shadow roots; a press-that starts and ends anywhere else closes the list, a scroll or pinch that-starts outside does not, and Escape stays on the shared stack. Implementation-gap: DateInput's calendar is still an auto popover with native light dismiss,-so a press in its own text input closes it.+A text input cannot be an invoker, so BaseTypeahead's list, DateInput's+calendar, DateTimeInput's time list and ChatComposerInput's trigger menu, which+their text fields own, are manual popovers. A press that starts and ends on the+field's input or its buttons (and DateInput's label), or in the layer, is+inside, judged across open shadow roots; a press that starts and ends anywhere+else closes the layer, a scroll or pinch that starts outside does not, and+Escape stays on the shared stack. Focus leaving the field stays each owner's to+handle (`family:overlay-dismissal` AV4).### Current dismissal plumbing@@ -333,8 +333,9 @@ Outside interaction is not coordinated by the shared stack. Current paths areindependent:- auto popovers use native light dismiss;-- BaseTypeahead's list, DateTimeInput's time list and ChatComposerInput's- trigger menu, manual popovers, use Layer's outside-press watch,+- BaseTypeahead's list, DateInput's calendar, DateTimeInput's time list and+ ChatComposerInput's trigger menu, manual popovers, use Layer's outside-press+ watch,which closes on a press that starts and ends outside the field and the listand forgets a cancelled press (a scroll);- native dialogs handle backdrop clicks locally;@@ -661,8 +662,8 @@ is staged as `[breaking]` (`spec:AST-017` FR32) and `component:SelectableCard`- `Layer/useTouchTrigger.ts` owns touch trigger classification and the currenttouch-only outside listener for Tooltip/HoverCard.- `Layer/outsidePress.ts` owns the outside-press watch for a text field's- manual layer, used by BaseTypeahead, DateTimeInput and ChatComposerInput's- trigger menu.+ manual layer, used by BaseTypeahead, DateInput, DateTimeInput and+ ChatComposerInput's trigger menu.- `DropdownMenuContext` and `DropdownMenuSubMenu` own the current localmenu-cascade parent-close chain.- Dialog families own native modal/backdrop presentation and their local channeldiff --git a/docs/specs/components/DateInput/DateInput.spec.md b/docs/specs/components/DateInput/DateInput.spec.mdindex 465c78c2c2..b5622dd3b2 100644--- a/docs/specs/components/DateInput/DateInput.spec.md+++ b/docs/specs/components/DateInput/DateInput.spec.md@@ -133,7 +133,7 @@ Consumer migration instructions belong in consumer docs and release notes.| FR5 | Text, Calendar, bottom-sheet, and native commit paths MUST enforce `min`, `max`, and `dateConstraints`; a rejected value MUST NOT replace the controlled value. | Current source and all four focused suites || FR6 | Named committed formats MUST follow the InternationalizationProvider locale and shared Timestamp vocabulary; formatting MUST NOT rewrite in-progress typed text. Typed text MUST parse in the provider locale (`architecture:internationalization` INV1a, INV8). The touch sheet's month heading and each month pane's name are stand-alone month labels: they start with a capital where CLDR's stand-alone context transform titlecases the month, as `component:Calendar` FR1 states for Calendar's. Implementation gap: the typed parser accepts only English month names and ASCII digits, using the locale only to order day and month. | `architecture:internationalization`; current source, docs, locale tests; `spec:AST-043/FR5` || FR7 | Every value-change path MUST call `onChange` before `changeAction`, present the proposed value optimistically, and expose one busy state while the Action is pending. | `family:input-fields/FR6`; current source and focused tests |-| FR8 | The pointer field MUST open its Calendar from the input, calendar toggle, ArrowDown, or Alt+ArrowDown; Popover dismissal and focus return MUST remain owned by the shared Popover path. | Current source, Popover composition, keyboard/focus tests |+| FR8 | The pointer field MUST open its Calendar from the input, calendar toggle, ArrowDown, or Alt+ArrowDown; Popover dismissal and focus return MUST remain owned by the shared Popover path. The open pointer Calendar stays open for a press on the field's input, clear button or label, or in the Calendar, and closes for a press elsewhere (`architecture:layer-runtime`) or for focus moving from anywhere in the field (its input, clear button or calendar toggle) to anything outside the field and the Calendar (`family:overlay-dismissal` AV4). | Current source, Popover composition, keyboard/focus tests || FR9 | A pointer-surface Calendar selection MUST commit and close its Popover; a bottom-sheet Calendar selection MUST remain editable in the open sheet until Save closes the surface. | Current source and pointer/touch tests || FR10 | Standalone mode MUST compose Field; admitted InputGroup mode MUST remove competing Field chrome while preserving name, description, value, keyboard, focus, and editing semantics. The field has no root styling props; `control*` reaches the control box on every surface, and `container*` reaches the Field box where one renders (in a horizontal-labels FormLayout none renders and `container*` warns; inside an InputGroup it is dropped) (`family:input-fields` FR10). The field height is the shared element size for its size and MUST grow with a set text size (`spec:AST-102` FR4). Implementation gap: the height is fixed. | `family:input-fields` FR3, FR10; `spec:AST-102` FR4; current source and tests || FR11 | Clear MUST emit `undefined` through the ordinary change pipeline. The pointer and bottom-sheet surfaces restore field focus using their shipped timing; the native surface MUST NOT reclaim focus because doing so reopens the OS picker. Implementation gap: when the field becomes disabled or busy while its clear control holds focus, the control unmounts and focus falls to the document body; `spec:AST-085/FR4` requires focus to stay or move to a destination this record names. | Current source and focused clear tests; `spec:AST-085/FR4` |@@ -308,7 +308,7 @@ clear-glyph target of its own.| FR5 | `DateInput.test.tsx` min, max, and dateConstraints typed cases; `DateInputTouch.test.tsx` "disables days outside min/max and refuses to commit them", "honors custom date constraints"; `NativeDateField.test.tsx` "refuses an out-of-range date and announces it", "refuses a date dateConstraints rejects" | Typed, sheet, native; bounds and predicates | A constrained date that commits on any surface fails. Evidence gap: no test asserts constraints on a popover Calendar pick. | `audit:DateInput/behavior` || FR6 | `DateInput.test.tsx` format cases, including "updates when the InternationalizationProvider locale changes (#5074)" and "does not apply format to in-progress typed input"; `NativeDateField.test.tsx` format and locale cases; `DateInputTouch.test.tsx` "updates the field and open picker when the provider locale changes" | Named and function formats; locale change | A format that ignores the locale or rewrites typed text fails. Evidence gap: no test types a localized month name or non-ASCII digits (the FR6 gap). | `audit:DateInput/i18n` || FR7, ORD3 | `DateInput.test.tsx` "runs changeAction after onChange for a typed date"; `NativeDateField.test.tsx` "runs changeAction after onChange and exposes the pending state"; `DateInputTouch.test.tsx` "runs changeAction and shows a busy state"; `BusyOwnerAnnouncement.test.tsx` DateInput cases; `DateInputTouch.test.tsx` "announces a busy start from a pick inside the open sheet, not behind it (spec:AST-086 FR8, Platform support)" | Typed, native, sheet | An Action before `onChange`, a missing busy state, or a missing busy announcement fails. | `audit:DateInput/behavior` |-| FR8, AR2 | `DateInput.test.tsx` "opens the calendar popover on ArrowDown (keyboard, forms-13)", "opens the calendar popover on Alt+ArrowDown (keyboard, forms-13)", "input has aria-expanded attribute", "combobox input has aria-haspopup=\"dialog\" attribute", "moves focus into the calendar on each open from the toggle"; `DateInputTouch.test.tsx` "opens from the keyboard, APG combobox style" | Pointer and touch fields | A missing open path, combobox state, or focus move fails. Evidence gap: no test asserts Escape outside IME composition on the popover. | `audit:DateInput/accessibility` |+| FR8, AR2 | `DateInput.test.tsx` "opens the calendar popover on ArrowDown (keyboard, forms-13)", "opens the calendar popover on Alt+ArrowDown (keyboard, forms-13)", "input has aria-expanded attribute", "combobox input has aria-haspopup=\"dialog\" attribute", "moves focus into the calendar on each open from the toggle"; `DateInputTouch.test.tsx` "opens from the keyboard, APG combobox style"; `DateInput.test.tsx` "press inside and outside the open calendar" cases | Pointer and touch fields | A missing open path, combobox state, or focus move fails. Evidence gap: no test asserts Escape outside IME composition on the popover. | `audit:DateInput/accessibility` || FR9 | `DateInputTouch.test.tsx` "commits the tapped day and LEAVES the sheet open", "lets a second tap correct the first, still without closing", "Save closes the sheet without touching the value" | Sheet picks and Save | A sheet that closes on a pick or a Save that changes the value fails. Evidence gap: no test asserts that a popover Calendar pick closes the popover. | `audit:DateInput/behavior` || FR10 | `DateInput.fr10.test.tsx` styling and per-surface cases ("has no root styling props and has the container* and control* parts", "rejects root xstyle, className, and style at compile time", "keeps control* on the control box in a horizontal-labels FormLayout") and handler-composition cases; `DateInput.test.tsx` InputGroup cases; `DateInputTouch.test.tsx` "drops the Field wrapper inside an InputGroup" | Standalone, grouped, horizontal labels; every surface | A root styling prop, `control*` off the control box, or Field chrome inside a group fails. Evidence gap: no test asserts the field height or its growth with text size (the FR10 gap). | `audit:DateInput/layout` || FR11, ORD4 | `DateInput.test.tsx` hasClear cases; `DateInputTouch.test.tsx` "clears from the field", "returns focus to the field without letting the page scroll"; `NativeDateField.test.tsx` "clears the value without taking focus back", "runs clear through changeAction after onChange" | Pointer, sheet, native clear | A clear that does not emit `undefined`, a native clear that takes focus, or a clear shown while disabled fails. Evidence gap: no test covers the clear control unmounting under focus (the FR11 gap). | `audit:DateInput/behavior` |diff --git a/packages/core/src/Chat/useTriggerMenu.tsx b/packages/core/src/Chat/useTriggerMenu.tsxindex ebfe74c518..45a1a95b15 100644--- a/packages/core/src/Chat/useTriggerMenu.tsx+++ b/packages/core/src/Chat/useTriggerMenu.tsx@@ -32,7 +32,7 @@ import {} from 'react';import * as stylex from '@stylexjs/stylex';import {usePopover} from '../Popover/usePopover';-import {useOutsidePress} from '../Layer/outsidePress';+import {isPressInsideOwnedLayer, useOutsidePress} from '../Layer/outsidePress';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';import {@@ -414,13 +414,7 @@ export function useTriggerMenu(}outsidePress.start(editable,- // The menu is hosted outside the editor, so it counts on its own.- path =>- path.some(- target =>- target === editable ||- (target instanceof Element && target.id === popover.id),- ),+ path => isPressInsideOwnedLayer(path, editable, popover.id),// Called after usePopover has returned, so `popover` is assigned.() => popover.hide(),);diff --git a/packages/core/src/DateInput/DateInput.test.tsx b/packages/core/src/DateInput/DateInput.test.tsxindex 9476264a32..77702f12d3 100644--- a/packages/core/src/DateInput/DateInput.test.tsx+++ b/packages/core/src/DateInput/DateInput.test.tsx@@ -421,6 +421,137 @@ describe('DateInput', () => {expect(input).toHaveAttribute('aria-expanded', 'true');});+ describe('press inside and outside the open calendar', () => {+ function press(target: Element) {+ fireEvent.pointerDown(target, {composed: true});+ fireEvent.pointerUp(target, {composed: true});+ }++ it('keeps the calendar open on a press in its own input, closes it on a press elsewhere', async () => {+ render(+ <>+ <DateInput label="Date" onChange={() => {}} />+ <p>Elsewhere</p>+ </>,+ );+ const input = screen.getByRole('combobox');+ fireEvent.keyDown(input, {key: 'ArrowDown'});+ expect(input).toHaveAttribute('aria-expanded', 'true');+ // The calendar is a manual popover, so the browser does not+ // light-dismiss it on a press in the input.+ expect(document.querySelector('[popover]')).toHaveAttribute(+ 'popover',+ 'manual',+ );++ press(input);+ expect(input).toHaveAttribute('aria-expanded', 'true');++ press(screen.getByText('Elsewhere'));+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('keeps a calendar hosted outside the field open on a press inside it', async () => {+ // Inside a list item, Layer hosts the calendar outside the field.+ render(+ <ul>+ <li>+ <DateInput label="Date" onChange={() => {}} />+ </li>+ <li>Elsewhere</li>+ </ul>,+ );+ const input = screen.getByRole('combobox');+ fireEvent.keyDown(input, {key: 'ArrowDown'});+ const layer = document.querySelector('[popover]') as HTMLElement;+ expect(layer.closest('li')?.contains(input) ?? false).toBe(false);++ press(layer);+ expect(input).toHaveAttribute('aria-expanded', 'true');++ press(screen.getByText('Elsewhere'));+ await waitFor(() => {+ expect(input).toHaveAttribute('aria-expanded', 'false');+ });+ });++ it('closes the calendar when focus moves to another field', async () => {+ render(+ <>+ <DateInput label="Start" onChange={() => {}} />+ <DateInput label="End" onChange={() => {}} />+ </>,+ );+ const [start, end] = screen.getAllByRole('combobox');+ start.focus();+ fireEvent.keyDown(start, {key: 'ArrowDown'});+ expect(start).toHaveAttribute('aria-expanded', 'true');+ end.focus();+ await waitFor(() => {+ expect(start).toHaveAttribute('aria-expanded', 'false');+ });+ // The close keeps focus where the person moved it.+ expect(document.activeElement).toBe(end);+ });++ it('closes the calendar when focus leaves the field from its clear button', async () => {+ render(+ <>+ <DateInput+ label="Start"+ value="2026-01-15"+ hasClear+ onChange={() => {}}+ />+ <DateInput label="End" onChange={() => {}} />+ </>,+ );+ const [start, end] = screen.getAllByRole('combobox');+ start.focus();+ fireEvent.keyDown(start, {key: 'ArrowDown'});+ expect(start).toHaveAttribute('aria-expanded', 'true');+ // Tab from the text lands on the clear button, still in the field.+ const clear = screen.getByRole('button', {name: /clear/i});+ clear.focus();+ expect(start).toHaveAttribute('aria-expanded', 'true');+ // The next Tab leaves the field from the clear button.+ end.focus();+ await waitFor(() => {+ expect(start).toHaveAttribute('aria-expanded', 'false');+ });+ expect(document.activeElement).toBe(end);+ });++ it('keeps the calendar open on a press on its label', () => {+ render(<DateInput label="Date" onChange={() => {}} />);+ const input = screen.getByRole('combobox');+ fireEvent.keyDown(input, {key: 'ArrowDown'});+ const label = document.querySelector(+ `label[for="${input.id}"]`,+ ) as HTMLLabelElement;+ expect(label).not.toBeNull();+ press(label);+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });++ it('keeps the calendar open when a scroll starts outside (pointercancel)', () => {+ render(+ <>+ <DateInput label="Date" onChange={() => {}} />+ <p>Elsewhere</p>+ </>,+ );+ const input = screen.getByRole('combobox');+ fireEvent.keyDown(input, {key: 'ArrowDown'});+ const elsewhere = screen.getByText('Elsewhere');+ fireEvent.pointerDown(elsewhere, {composed: true});+ fireEvent.pointerCancel(elsewhere, {composed: true});+ expect(input).toHaveAttribute('aria-expanded', 'true');+ });+ });+it('does not open on ArrowDown when disabled', () => {render(<DateInput label="Date" isDisabled onChange={() => {}} />);const input = screen.getByRole('combobox');diff --git a/packages/core/src/DateInput/DateInput.tsx b/packages/core/src/DateInput/DateInput.tsxindex dbcad609f5..7dbd43af93 100644--- a/packages/core/src/DateInput/DateInput.tsx+++ b/packages/core/src/DateInput/DateInput.tsx@@ -63,6 +63,11 @@ import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';import {useMediaQuery} from '../hooks/useMediaQuery';import {useResolvedRequired} from '../hooks/useResolvedRequired';import {usePopover} from '../Popover';+import {+ isFocusInsideOwnedLayer,+ isPressInsideOwnedLayer,+ useOutsidePress,+} from '../Layer/outsidePress';import {NativeDateField} from './NativeDateField';import {TouchDateField} from './TouchDateField';import {useTooltip} from '../Tooltip';@@ -475,6 +480,20 @@ export interface DateInputProps extends Omit<*/const TOUCH_POINTER_QUERY = '(pointer: coarse)';+/**+ * Whether `target` is a label whose control is `input`. Checked by nodeType+ * and tag name, so a label in a same-origin iframe counts.+ */+function isLabelFor(target: EventTarget, input: HTMLInputElement | null) {+ const node = target as Partial<HTMLLabelElement>;+ return (+ input != null &&+ node.nodeType === 1 &&+ node.localName === 'label' &&+ node.control === input+ );+}+/*** The pointer-driven field: a text input you can type into, with a calendar* in a popover beside it. `DateInput` renders this whenever the primary@@ -637,18 +656,44 @@ function PointerDateField({? true: parseDateInput(pendingInput, locale) !== null;+ const fieldElementRef = useRef<HTMLDivElement | null>(null);+ // Set just before a close that focus already left the field for, so onHide+ // does not pull focus back to the input.+ const isFocusMovingAwayRef = useRef(false);+ const outsidePress = useOutsidePress();const popover = usePopover({+ // A text input cannot be an invoker. Light dismiss would count a press in+ // it as outside and close the calendar.+ hasLightDismiss: false,+ onShow: () => {+ const field = fieldElementRef.current;+ if (field == null) {+ return;+ }+ outsidePress.start(+ field,+ // The label counts too: a press there focuses the input, which would+ // otherwise close the calendar and reopen it on the same press.+ path =>+ isPressInsideOwnedLayer(path, field, popover.id) ||+ path.some(target => isLabelFor(target, inputRef.current)),+ // Called after usePopover has returned, so `popover` is assigned.+ () => popover.hide(),+ );+ },dialogLabel: t('@astryx.dateInput.dialogLabel'),closeButtonLabel: t('@astryx.dateInput.closeCalendar'),// Return focus to the input when the calendar closes — but only when the// dismiss left focus detached (Escape, or a click on non-focusable empty- // space), which the focus trap can't restore on its own. A native- // popover="auto" light-dismiss fires synchronously with the pointer event- // that moved focus, so if the user clicked another control — the clear- // button, another field, anywhere — focus has already landed there;- // reclaiming it would fight their click.+ // space), which the focus trap can't restore on its own. An outside press+ // closes the calendar after the pointer event that moved focus, so if the+ // user clicked another control — another field, anywhere — focus has+ // already landed there; reclaiming it would fight their click.onHide: () => {- if (isFocusDetached()) {+ outsidePress.stop();+ const isFocusMovingAway = isFocusMovingAwayRef.current;+ isFocusMovingAwayRef.current = false;+ if (!isFocusMovingAway && isFocusDetached()) {inputRef.current?.focus();}},@@ -791,11 +836,30 @@ function PointerDateField({locale,]);- // Handle blur - validate, check constraints, and clear pending input+ // Handle blur - validate, check constraints, and clear pending input.const handleBlur = useCallback(() => {commitPendingInput();}, [commitPendingInput]);+ // A manual popover has no auto-popover exclusivity, so without this close+ // the next field's calendar would open beside this one. Focus going nowhere+ // (a window switch) leaves it open.+ const handleFieldBlur = useCallback(+ (e: React.FocusEvent<HTMLDivElement>) => {+ const next = e.relatedTarget;+ if (+ !popover.isOpen ||+ next == null ||+ isFocusInsideOwnedLayer(next, fieldElementRef.current, popover.id)+ ) {+ return;+ }+ isFocusMovingAwayRef.current = true;+ popover.hide();+ },+ [popover],+ );+// Handle keyboard events on inputconst handleInputKeyDown = useCallback((e: React.KeyboardEvent) => {@@ -831,12 +895,14 @@ function PointerDateField({const inputWrapper = (<divref={el => {+ fieldElementRef.current = el;popover.triggerRef(el);// Anchor + hover/focus listeners for the disabled-message tooltip.// Handlers are gated internally by isEnabled, and anchor names// compose, so attaching unconditionally is safe.disabledMessageTooltip.ref(el);}}+ onBlur={handleFieldBlur}{...(inputGroup ? inputGroupItemProps : undefined)}{...mergeProps(themeProps('date-input', {diff --git a/packages/core/src/DateInput/__tests__/DateInputFocusLeave.interaction.browser.spec.ts b/packages/core/src/DateInput/__tests__/DateInputFocusLeave.interaction.browser.spec.tsnew file mode 100644index 0000000000..aeae1949aa--- /dev/null+++ b/packages/core/src/DateInput/__tests__/DateInputFocusLeave.interaction.browser.spec.ts@@ -0,0 +1,58 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file DateInputFocusLeave.interaction.browser.spec.ts+ * @input Storybook story core-dateinput--formats (four DateInput fields)+ * @output In a real browser, with one calendar open from its input: a press+ * in the same input keeps it open; a press in another field's text or focus+ * moved to another field closes it, and focus stays where it moved (the+ * close never pulls focus back).+ * @position DateInput press and focus-leave evidence, run in the Chromium+ * interaction lane; jsdom has neither light dismiss nor real focus order.+ */++import {expect, test, type Page} from '@playwright/test';+import {openStory, withStorybook} from '@astryxdesign/interaction-harness';++const storybook = withStorybook(test);++// A fine pointer on a desktop-sized page, where the calendar is the anchored+// popover this record covers (a coarse pointer presents a bottom sheet).+test.use({+ isMobile: false,+ hasTouch: false,+ viewport: {width: 1024, height: 768},+});++async function openFirst(page: Page) {+ await openStory(page, storybook(), 'core-dateinput--formats');+ const fields = page.getByRole('combobox');+ await fields.first().waitFor();+ await fields.first().click();+ await expect(fields.first()).toHaveAttribute('aria-expanded', 'true');+ return fields;+}++test('a press in the same input keeps the calendar open', async ({page}) => {+ const fields = await openFirst(page);+ await fields.first().click();+ await expect(fields.first()).toHaveAttribute('aria-expanded', 'true');+});++test('a press in another field closes the calendar and keeps focus there', async ({+ page,+}) => {+ const fields = await openFirst(page);+ await fields.nth(1).click();+ await expect(fields.first()).toHaveAttribute('aria-expanded', 'false');+ await expect(fields.nth(1)).toBeFocused();+});++test('focus moved to another field closes the calendar and stays there', async ({+ page,+}) => {+ const fields = await openFirst(page);+ await fields.nth(2).focus();+ await expect(fields.first()).toHaveAttribute('aria-expanded', 'false');+ await expect(fields.nth(2)).toBeFocused();+});diff --git a/packages/core/src/DateTimeInput/DateTimeInput.tsx b/packages/core/src/DateTimeInput/DateTimeInput.tsxindex ed7e0c27d4..d62290a5da 100644--- a/packages/core/src/DateTimeInput/DateTimeInput.tsx+++ b/packages/core/src/DateTimeInput/DateTimeInput.tsx@@ -64,7 +64,11 @@ import {} from '../Calendar';import {useCalendarConstraints} from '../Calendar/hooks';import {usePopover} from '../Popover';-import {useOutsidePress} from '../Layer/outsidePress';+import {+ isFocusInsideOwnedLayer,+ isPressInsideOwnedLayer,+ useOutsidePress,+} from '../Layer/outsidePress';import {useTooltip} from '../Tooltip';import {useInputContainer} from '../hooks/useInputContainer';import {useBusyAnnouncement} from '../hooks/useBusyAnnouncement';@@ -1193,13 +1197,7 @@ function PointerDateTimeField({}timeOutsidePress.start(field,- // The list may be hosted outside the field, so it counts on its own.- path =>- path.some(- target =>- target === field ||- (target instanceof Element && target.id === timePopover.id),- ),+ path => isPressInsideOwnedLayer(path, field, timePopover.id),// Called after usePopover has returned, so `timePopover` is assigned.() => timePopover.hide(),);@@ -1448,18 +1446,15 @@ function PointerDateTimeField({// on the layer stack, so a focus move that is neither — Tab handled// elsewhere, or a programmatic focus — would strand the listbox open. Focus landing inside the// field or the popup itself is not a leave. Mirrors BaseTypeahead.- if (timePopover.isOpen) {- const next = e.relatedTarget as Node | null;- const popoverEl = next ? document.getElementById(timePopover.id) : null;- if (- !next ||- !(- timeContainerRef.current?.contains(next) ||- popoverEl?.contains(next)- )- ) {- timePopover.hide();- }+ if (+ timePopover.isOpen &&+ !isFocusInsideOwnedLayer(+ e.relatedTarget,+ timeContainerRef.current,+ timePopover.id,+ )+ ) {+ timePopover.hide();}if (timePendingInput === null) {diff --git a/packages/core/src/Layer/outsidePress.test.ts b/packages/core/src/Layer/outsidePress.test.tsnew file mode 100644index 0000000000..8a96eca862--- /dev/null+++ b/packages/core/src/Layer/outsidePress.test.ts@@ -0,0 +1,98 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file outsidePress.test.ts+ * @input isFocusInsideOwnedLayer and isPressInsideOwnedLayer+ * @output The shared focus-leave test: the field, the layer (by id, across+ * shadow roots and through popovers nested in it) are inside; anything+ * else and a null target are outside+ */++import {afterEach, describe, expect, it} from 'vitest';+import {isFocusInsideOwnedLayer, isPressInsideOwnedLayer} from './outsidePress';++describe('isFocusInsideOwnedLayer', () => {+ function setup() {+ const field = document.createElement('div');+ const input = document.createElement('input');+ field.append(input);+ const layer = document.createElement('div');+ layer.id = 'owned-layer';+ const option = document.createElement('button');+ // A popover nested in the layer (a tooltip on an option) is still in it.+ const nested = document.createElement('div');+ nested.setAttribute('popover', 'manual');+ const nestedButton = document.createElement('button');+ nested.append(nestedButton);+ layer.append(option, nested);+ const outside = document.createElement('button');+ document.body.append(field, layer, outside);+ return {field, input, option, nestedButton, outside};+ }++ afterEach(() => {+ document.body.replaceChildren();+ });++ it('counts the field, the layer and a popover nested in the layer as inside', () => {+ const {field, input, option, nestedButton} = setup();+ expect(isFocusInsideOwnedLayer(input, field, 'owned-layer')).toBe(true);+ expect(isFocusInsideOwnedLayer(option, field, 'owned-layer')).toBe(true);+ expect(isFocusInsideOwnedLayer(nestedButton, field, 'owned-layer')).toBe(+ true,+ );+ });++ it('never matches a layer by an empty id', () => {+ const {field, outside} = setup();+ expect(isPressInsideOwnedLayer([outside], field, '')).toBe(false);+ });++ it('counts anything else, and no target, as outside', () => {+ const {field, outside} = setup();+ expect(isFocusInsideOwnedLayer(outside, field, 'owned-layer')).toBe(false);+ expect(isFocusInsideOwnedLayer(null, field, 'owned-layer')).toBe(false);+ });++ it('finds a layer whose content sits inside a shadow root', () => {+ const host = document.createElement('div');+ host.id = 'owned-layer';+ const root = host.attachShadow({mode: 'open'});+ const option = document.createElement('button');+ root.append(option);+ document.body.append(host);+ expect(isFocusInsideOwnedLayer(option, null, 'owned-layer')).toBe(true);+ });+});++describe('inside tests across realms', () => {+ afterEach(() => {+ document.body.replaceChildren();+ });++ it('count a field and layer in a same-origin iframe, whose nodes fail instanceof here', () => {+ const frame = document.createElement('iframe');+ document.body.append(frame);+ const frameDocument = frame.contentDocument!;+ const field = frameDocument.createElement('div');+ const input = frameDocument.createElement('input');+ field.append(input);+ const layer = frameDocument.createElement('div');+ layer.id = 'framed-layer';+ const option = frameDocument.createElement('button');+ layer.append(option);+ frameDocument.body.append(field, layer);+ // The precondition this guards: another realm's nodes are not this+ // window's Node.+ expect(option instanceof Node).toBe(false);++ expect(isFocusInsideOwnedLayer(input, field, 'framed-layer')).toBe(true);+ expect(isFocusInsideOwnedLayer(option, field, 'framed-layer')).toBe(true);+ expect(+ isPressInsideOwnedLayer([option, layer], field, 'framed-layer'),+ ).toBe(true);+ expect(+ isPressInsideOwnedLayer([frameDocument.body], field, 'framed-layer'),+ ).toBe(false);+ });+});diff --git a/packages/core/src/Layer/outsidePress.ts b/packages/core/src/Layer/outsidePress.tsindex e59b9714da..b8e9ccf6b1 100644--- a/packages/core/src/Layer/outsidePress.ts+++ b/packages/core/src/Layer/outsidePress.ts@@ -6,7 +6,9 @@* @file outsidePress.ts* @input Listens for pointerdown, pointerup and pointercancel on a document* @output Exports watchOutsidePress and useOutsidePress, which owns one watch- * for a component: start on show, stop on hide, stop on unmount+ * for a component: start on show, stop on hide, stop on unmount; and the+ * inside tests a text field's owner runs: isPressInsideOwnedLayer for a+ * press, isFocusInsideOwnedLayer for a blur* @position Internal to Layer; the outside-press dismissal for a manual* popover whose owner decides what counts as inside (a combobox's field* and its list). Not exported from the package.@@ -97,3 +99,81 @@ export function useOutsidePress(): OutsidePressWatch {useEffect(() => stop, [stop]);return useMemo(() => ({start, stop}), [start, stop]);}++// Node, Element and ShadowRoot are checked by nodeType, not instanceof: a+// node from a same-origin iframe or a Picture-in-Picture window belongs to+// another realm, where instanceof against this window's classes is false.+function isNode(target: unknown): target is Node {+ return (+ typeof target === 'object' &&+ target !== null &&+ typeof (target as {nodeType?: unknown}).nodeType === 'number'+ );+}++function isElement(node: Node): node is Element {+ return node.nodeType === 1;+}++function isShadowRoot(node: Node): node is ShadowRoot {+ return node.nodeType === 11 && 'host' in node;+}++/** Whether `node` is the layer with this id, or inside it across shadow roots. */+function isWithinLayer(node: Node, layerId: string): boolean {+ for (+ let current: Node | null = node;+ current != null;+ current =+ current.parentNode ?? (isShadowRoot(current) ? current.host : null)+ ) {+ if (isElement(current) && current.id === layerId) {+ return true;+ }+ }+ return false;+}++/**+ * Whether a press with this composed path is on a text field or in the+ * field's own layer, which may be hosted outside the field.+ *+ * @param path - The press's composed path.+ * @param field - The field that owns the layer.+ * @param layerId - The layer element's id.+ */+export function isPressInsideOwnedLayer(+ path: ReadonlyArray<EventTarget>,+ field: Element,+ layerId: string,+): boolean {+ return path.some(+ target =>+ target === field ||+ (layerId !== '' &&+ isNode(target) &&+ isElement(target) &&+ target.id === layerId),+ );+}++/**+ * Whether focus moving to `next` stays with a text field's own layer: on the+ * field, or in the layer, which may be hosted outside the field or inside a+ * shadow root. Each owner decides what a blur that fails this means,+ * including when `next` is null.+ *+ * @param next - The blur's `relatedTarget`.+ * @param field - The field that owns the layer.+ * @param layerId - The layer element's id.+ */+export function isFocusInsideOwnedLayer(+ next: EventTarget | null,+ field: Element | null | undefined,+ layerId: string,+): boolean {+ return (+ isNode(next) &&+ (field?.contains(next) === true || isWithinLayer(next, layerId))+ );+}diff --git a/packages/core/src/Typeahead/BaseTypeahead.tsx b/packages/core/src/Typeahead/BaseTypeahead.tsxindex b60a08c3d1..92b22caa5f 100644--- a/packages/core/src/Typeahead/BaseTypeahead.tsx+++ b/packages/core/src/Typeahead/BaseTypeahead.tsx@@ -40,7 +40,11 @@ import {useAnnounce} from '../hooks/useAnnounce';import {useAnnounceRenderedText} from '../hooks/useAnnounceRenderedText';import {useHighlightedOptionScroll} from '../hooks/useHighlightedOptionScroll';import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';-import {useOutsidePress} from '../Layer/outsidePress';+import {+ isFocusInsideOwnedLayer,+ isPressInsideOwnedLayer,+ useOutsidePress,+} from '../Layer/outsidePress';import {isImeKeyEvent} from '../utils/ime';import {TypeaheadItem} from './TypeaheadItem';import {Icon} from '../Icon';@@ -842,13 +846,12 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({dropdownRef.current?.closest<HTMLElement>('[popover]') ?? null;outsidePress.start(anchorEl,- path => {- const anchor = anchorRef?.current ?? fallbackAnchorRef.current;- const layer = findLayer();- return path.some(- target => target === anchor || (layer != null && target === layer),- );- },+ path =>+ isPressInsideOwnedLayer(+ path,+ anchorRef?.current ?? fallbackAnchorRef.current ?? anchorEl,+ findLayer()?.id ?? '',+ ),() => findLayer()?.hidePopover(),);}, [onOpenChange, anchorRef, outsidePress]);@@ -1454,13 +1457,9 @@ export const BaseTypeahead = function BaseTypeahead<T extends SearchableItem>({if (!popover.isOpen) {return;}- const next = e.relatedTarget as Node | null;- if (next) {- const anchorEl = anchorRef?.current ?? fallbackAnchorRef.current;- const popoverEl = document.getElementById(popover.id);- if (anchorEl?.contains(next) || popoverEl?.contains(next)) {- return;- }+ const anchorEl = anchorRef?.current ?? fallbackAnchorRef.current;+ if (isFocusInsideOwnedLayer(e.relatedTarget, anchorEl, popover.id)) {+ return;}popover.hide();},