Skip to content

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

TypeScript

refactor(core): share per-instance warning dedupe and temporary focus targets (#10655)

Humberto Virtudesdb40c6b01d65
diff --git a/.changeset/core-shared-warning-focus-owners.md b/.changeset/core-shared-warning-focus-owners.md
new file mode 100644
index 0000000000..0932565de9
--- /dev/null
+++ b/.changeset/core-shared-warning-focus-owners.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/core': patch
+---
+
+[chore] Internal: per-instance warning deduplication and temporary focus targets each have one shared owner in Core. Resizable, Dialog and TabList dedupe their development warnings through it, and Chat's Done button parks focus through it. Warning text and focus behavior are unchanged; apps import nothing new.
+
+@humbertovirtudes
diff --git a/packages/core/src/Chat/useChatKeyboard.ts b/packages/core/src/Chat/useChatKeyboard.ts
index 3ee04a7637..7648f01a8b 100644
--- a/packages/core/src/Chat/useChatKeyboard.ts
+++ b/packages/core/src/Chat/useChatKeyboard.ts
@@ -39,7 +39,11 @@ import {
import type {KeyboardTransition} from '../keyboard/keyboardModel';
import {rideKeyboard} from '../keyboard/rideKeyboard';
import {layoutViewportHeight} from '../utils/layoutViewport';
-import {useInteractionModalityTrackingFor} from '../utils/interactionModality';
+import {
+ useInteractionModalityTrackingFor,
+ type InteractionModality,
+} from '../utils/interactionModality';
+import {focusForLastInputTemporarily} from '../utils/focusReturn';
import {isCoarsePointer} from '../utils/coarsePointer';
import {useTouchPresentation} from '../utils/touchPresentation';
import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';
@@ -149,20 +153,18 @@ export function editableToClaim(target: unknown): HTMLElement | null {
* region gives the focus stop up as soon as focus leaves it. It shows the
* focus ring only after keyboard input, as other script focus does.
*/
-function parkFocus(region: HTMLElement, showsRing: boolean): void {
- region.setAttribute('tabindex', '-1');
- if (!showsRing) {
+function parkFocus(region: HTMLElement, modality: InteractionModality): void {
+ // WebKit ignores `focusVisible: false`, so a park after touch input also
+ // hides the ring inline until focus leaves.
+ if (modality !== 'keyboard') {
region.style.setProperty('outline', 'none');
+ region.addEventListener(
+ 'blur',
+ () => region.style.removeProperty('outline'),
+ {once: true},
+ );
}
- region.addEventListener(
- 'blur',
- () => {
- region.removeAttribute('tabindex');
- region.style.removeProperty('outline');
- },
- {once: true},
- );
- region.focus({preventScroll: true});
+ focusForLastInputTemporarily(region, {preventScroll: true}, modality);
}
/**
@@ -463,7 +465,7 @@ export function useChatKeyboard({
claim: destination => findTextEntryControl(destination, composer),
park: origin => {
if (findTextEntryControl(origin, composer) != null) {
- parkFocus(composer, readModality() === 'keyboard');
+ parkFocus(composer, readModality());
}
},
});
diff --git a/packages/core/src/Dialog/Dialog.tsx b/packages/core/src/Dialog/Dialog.tsx
index 4dc26d04fe..d9a28feaa1 100644
--- a/packages/core/src/Dialog/Dialog.tsx
+++ b/packages/core/src/Dialog/Dialog.tsx
@@ -42,6 +42,7 @@ import {
useLayoutEffect,
useMemo,
useRef,
+ useState,
type ReactNode,
} from 'react';
import {useIsHydrating} from '../hooks/useIsHydrating';
@@ -80,7 +81,7 @@ import {
import type {SpacingStep} from '../utils/types';
import {mergeProps} from '../utils/mergeProps';
import {chainEventHandlers} from '../utils/chainEventHandlers';
-import {devWarn} from '../utils/devWarning';
+import {createDevWarnings} from '../utils/devWarning';
import {DialogContext} from './DialogContext';
import {themeProps} from '../utils/themeProps';
import type {DialogVariantMap} from './index';
@@ -744,27 +745,19 @@ export function Dialog({
});
// Dev-time guardrail: an open modal should always have an accessible name.
- // The header-title check reads the DOM, so this stays in an effect; the ref
- // keeps it to one warning per component instance.
- const warnedUnnamedDialogRef = useRef(false);
+ // The header-title check reads the DOM, so this stays in an effect.
+ const [warn] = useState(createDevWarnings);
useEffect(() => {
const hasHeaderTitle =
dialogRef.current?.querySelector(`#${CSS.escape(titleId)}`) != null;
- if (
- isOpen &&
- !isInline &&
- !hasConsumerName &&
- !hasHeaderTitle &&
- !warnedUnnamedDialogRef.current
- ) {
- warnedUnnamedDialogRef.current = true;
- devWarn(
+ if (isOpen && !isInline && !hasConsumerName && !hasHeaderTitle) {
+ warn(
'Dialog',
'open dialog has no accessible name. Add a DialogHeader ' +
'with a `title`, or pass `aria-label`/`aria-labelledby`.',
);
}
- }, [isOpen, isInline, hasConsumerName, titleId]);
+ }, [isOpen, isInline, hasConsumerName, titleId, warn]);
// A press on the ::backdrop targets the <dialog> itself, so native browser
// popups (date pickers, selects, color pickers) that render outside the
diff --git a/packages/core/src/Resizable/createResizable.ts b/packages/core/src/Resizable/createResizable.ts
index a861bbaf69..70284a88be 100644
--- a/packages/core/src/Resizable/createResizable.ts
+++ b/packages/core/src/Resizable/createResizable.ts
@@ -15,7 +15,7 @@
import {registerEnglishFallback} from '../i18n/englishFallback';
import english from '../i18n/generated-english/Resizable/createResizable.generated';
import {observeResize} from '../utils/sharedResizeObserver';
-import {devWarn} from '../utils/devWarning';
+import {createDevWarnings, devWarn} from '../utils/devWarning';
import {project} from '../motion/projection';
import {
rubberBand,
@@ -186,8 +186,8 @@ function readWindowExtent(direction: ResizableDirection): number | null {
return direction === 'vertical' ? window.innerHeight : window.innerWidth;
}
-/** Starts as warned: the factory warns, and this first-render read does not. */
-const QUIET = {current: true};
+/** The factory warns. This first-render read does not. */
+const QUIET = null;
/** How far a pull past a size bound can move the handle, in px. */
const RUBBER_BAND_TRAVEL_PX = 8;
@@ -441,12 +441,7 @@ export function createResizableAs(
const listeners = new Set<() => void>();
const isReversed = (): boolean => opts.isReversed ?? false;
const isDisabled = (): boolean => opts.isDisabled ?? false;
- const didWarn = {
- min: {current: false},
- max: {current: false},
- defaultSize: {current: false},
- inverted: false,
- };
+ const warn = createDevWarnings();
let persistedKey = opts.autoSaveId;
let persisted: PersistedResizableState | null = persistedKey
@@ -621,7 +616,7 @@ export function createResizableAs(
DEFAULT_MIN,
'minSize',
RESIZABLE_SIZE_GUIDANCE,
- didWarn.min,
+ warn,
source,
);
const max = resolveBound(
@@ -631,7 +626,7 @@ export function createResizableAs(
Infinity,
'maxSize',
RESIZABLE_SIZE_GUIDANCE,
- didWarn.max,
+ warn,
source,
);
// A basis-dependent default resolves ONCE into a pixel size; it is final
@@ -645,7 +640,7 @@ export function createResizableAs(
DEFAULT_SIZE_FALLBACK,
'defaultSize',
RESIZABLE_SIZE_GUIDANCE,
- didWarn.defaultSize,
+ warn,
source,
),
isFinal: isBasisMeasured,
@@ -683,12 +678,12 @@ export function createResizableAs(
collapsible() &&
(isControlled() ? Boolean(opts.isCollapsed) : uncontrolledIsCollapsed);
- if (min > max && !didWarn.inverted) {
- didWarn.inverted = true;
- devWarn(
+ if (min > max) {
+ warn(
source,
`the resolved minimum (${min}px) is above the resolved maximum ` +
`(${max}px). The maximum wins${isHook ? ', as it always has' : ''}.`,
+ 'inverted',
);
}
diff --git a/packages/core/src/Resizable/resizableModel.ts b/packages/core/src/Resizable/resizableModel.ts
index ce857af597..a096ec11e1 100644
--- a/packages/core/src/Resizable/resizableModel.ts
+++ b/packages/core/src/Resizable/resizableModel.ts
@@ -11,7 +11,7 @@
* clamp, snap and persist alike; no React, and no DOM work on import
*/
-import {devWarn} from '../utils/devWarning';
+import type {DevWarnings} from '../utils/devWarning';
export type ResizableDirection = 'horizontal' | 'vertical';
@@ -303,7 +303,7 @@ export function resolveBound(
fallback: number,
label: string,
accepted: string,
- didWarnRef: {current: boolean},
+ warn: DevWarnings | null,
source = 'useResizable',
): number {
if (raw === undefined) {
@@ -315,14 +315,12 @@ export function resolveBound(
return Infinity;
}
if (parsed == null) {
- if (!didWarnRef.current) {
- didWarnRef.current = true;
- devWarn(
- source,
- `${label}: ${describeSize(raw)} is not a size. ${accepted} ` +
- `Falling back to ${fallback}.`,
- );
- }
+ warn?.(
+ source,
+ `${label}: ${describeSize(raw)} is not a size. ${accepted} ` +
+ `Falling back to ${fallback}.`,
+ label,
+ );
return fallback;
}
return toPixels(parsed, basis) ?? fallback;
diff --git a/packages/core/src/TabList/TabList.tsx b/packages/core/src/TabList/TabList.tsx
index b3c3ea2018..8513e9b8f3 100644
--- a/packages/core/src/TabList/TabList.tsx
+++ b/packages/core/src/TabList/TabList.tsx
@@ -26,6 +26,7 @@ import React, {
useEffect,
useMemo,
useRef,
+ useState,
type AriaRole,
type ReactNode,
} from 'react';
@@ -54,7 +55,7 @@ import {Icon} from '../Icon';
import {EDGE_COMP_ATTR} from '../Layout/edgeCompensation.stylex';
import {themeProps} from '../utils/themeProps';
import {observeResize} from '../utils/sharedResizeObserver';
-import {devWarn} from '../utils/devWarning';
+import {createDevWarnings} from '../utils/devWarning';
import {focusOutlineProps} from '../utils/focusOutline.stylex';
import {useMergedRefs} from '../hooks/useMergedRefs';
@@ -640,26 +641,21 @@ export function TabList({
// `role="tablist"` owns only tabs, so anything else in the strip is invalid
// markup. Dev-only, and only under the asserted role — nothing else in the
// component reads the rendered DOM.
- const hasWarnedContentRef = useRef(false);
+ const [warn] = useState(createDevWarnings);
useEffect(() => {
const strip = stripRef.current;
- if (
- process.env.NODE_ENV === 'production' ||
- !isTabList ||
- !strip ||
- hasWarnedContentRef.current
- ) {
+ if (process.env.NODE_ENV === 'production' || !isTabList || !strip) {
return;
}
const stranger = Array.from(strip.children).find(
child => child.getAttribute('role') !== 'tab',
);
if (stranger) {
- hasWarnedContentRef.current = true;
- devWarn(
+ warn(
'TabList',
`role="tablist" owns only tabs, but the strip contains a <${stranger.tagName.toLowerCase()}> that is not one. ` +
'Render menus and other controls outside the strip, or drop the role for the navigation pattern.',
+ 'content',
);
}
// No dependency list: the check is on rendered DOM, which can change
diff --git a/packages/core/src/hooks/useDevWarning.test.tsx b/packages/core/src/hooks/useDevWarning.test.tsx
index 056b73b313..9c7564520a 100644
--- a/packages/core/src/hooks/useDevWarning.test.tsx
+++ b/packages/core/src/hooks/useDevWarning.test.tsx
@@ -2,7 +2,8 @@
import {afterEach, describe, expect, it, vi} from 'vitest';
import {render} from '@testing-library/react';
-import {useDevWarning} from './useDevWarning';
+import {StrictMode} from 'react';
+import {useDevWarning, useDevWarningPerMessage} from './useDevWarning';
afterEach(() => {
vi.restoreAllMocks();
@@ -11,14 +12,63 @@ afterEach(() => {
function Probe({
condition,
message = 'boom',
+ component = 'TestComponent',
}: {
condition: boolean;
message?: string;
+ component?: string;
}) {
- useDevWarning('TestComponent', message, condition);
+ useDevWarning(component, message, condition);
return null;
}
+function PerMessageProbe({
+ condition = true,
+ message,
+}: {
+ condition?: boolean;
+ message: string;
+}) {
+ useDevWarningPerMessage('TestComponent', message, condition);
+ return null;
+}
+
+describe('useDevWarningPerMessage', () => {
+ it('releases warning history when the component unmounts', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const view = render(<PerMessageProbe message="first" />);
+ view.unmount();
+ render(<PerMessageProbe message="first" />);
+ expect(warn).toHaveBeenCalledTimes(2);
+ });
+ it.each([false, true])(
+ 'warns once per distinct reason without repeating earlier reasons (StrictMode: %s)',
+ isStrict => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const wrap = (message: string, condition = true) =>
+ isStrict ? (
+ <StrictMode>
+ <PerMessageProbe message={message} condition={condition} />
+ </StrictMode>
+ ) : (
+ <PerMessageProbe message={message} condition={condition} />
+ );
+ const {rerender} = render(wrap('first'));
+ rerender(wrap('first'));
+ rerender(wrap('second', false));
+ expect(warn).toHaveBeenCalledTimes(1);
+ rerender(wrap('second'));
+ rerender(wrap('first'));
+ rerender(wrap('second'));
+ expect(warn).toHaveBeenCalledTimes(2);
+ expect(warn.mock.calls).toEqual([
+ ['TestComponent: first'],
+ ['TestComponent: second'],
+ ]);
+ },
+ );
+});
+
describe('useDevWarning', () => {
it('warns once, in the standardized format, when the condition is true', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
@@ -35,6 +85,31 @@ describe('useDevWarning', () => {
expect(warn).not.toHaveBeenCalled();
});
+ it('keeps the public once-per-mount behavior when the message changes', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const {rerender} = render(
+ <StrictMode>
+ <Probe condition={true} />
+ </StrictMode>,
+ );
+ rerender(
+ <StrictMode>
+ <Probe condition={true} message="changed" />
+ </StrictMode>,
+ );
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith('TestComponent: boom');
+ });
+
+ it('uses the current prefix when the condition first becomes true', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const view = render(<Probe component="Initial" condition={false} />);
+ view.rerender(<Probe component="Changed" condition />);
+ expect(warn).toHaveBeenCalledWith('Changed: boom');
+ view.rerender(<Probe component="Next" condition message="later" />);
+ expect(warn).toHaveBeenCalledTimes(1);
+ });
+
it('warns after the condition flips from false to true', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const {rerender} = render(<Probe condition={false} />);
diff --git a/packages/core/src/hooks/useDevWarning.ts b/packages/core/src/hooks/useDevWarning.ts
index b302e0e24e..e84300be3d 100644
--- a/packages/core/src/hooks/useDevWarning.ts
+++ b/packages/core/src/hooks/useDevWarning.ts
@@ -5,18 +5,17 @@
/**
* @file useDevWarning.ts
* @input A component name, a message, and a boolean condition
- * @output Fires a dev-only `Component: message` warning once per mount
- * @position Core hook; the render-safe way to warn the builder from a component.
- * A ref and an effect fire the warning once per mount, never during
- * render, and without a re-render.
+ * @output Public once-per-mount warnings and an internal per-message variant
+ * @position Core hook; both paths share one render-safe diagnostic owner.
+ * A stable instance and an effect warn after commit, without a re-render.
*
* SYNC: When modified, update:
* - /packages/core/src/hooks/index.ts
* - /packages/core/src/utils/devWarning.ts (the imperative counterpart)
*/
-import {useEffect, useRef} from 'react';
-import {devWarn} from '../utils/devWarning';
+import {useEffect, useState} from 'react';
+import {createDevWarnings} from '../utils/devWarning';
/**
* Fire a dev-only warning once per mount while `condition` is true.
@@ -39,13 +38,30 @@ export function useDevWarning(
message: string,
condition: boolean = true,
): void {
- const hasWarnedRef = useRef(false);
- // The console is outside React. The ref prints the warning one time, also
- // when StrictMode runs the Effect again.
+ useWarning(component, message, condition, false);
+}
+
+/** Warns once for each distinct message. Internal. */
+export function useDevWarningPerMessage(
+ component: string,
+ message: string,
+ condition: boolean = true,
+): void {
+ useWarning(component, message, condition, true);
+}
+
+function useWarning(
+ component: string,
+ message: string,
+ condition: boolean,
+ isPerMessage: boolean,
+): void {
+ // State survives Fast Refresh, so a hot update does not repeat a warning.
+ const [warn] = useState(createDevWarnings);
useEffect(() => {
- if (condition && !hasWarnedRef.current) {
- hasWarnedRef.current = true;
- devWarn(component, message);
+ // Synchronize the development diagnostic sink after committed renders.
+ if (condition) {
+ warn(component, message, isPerMessage ? message : '');
}
- }, [component, message, condition]);
+ }, [component, message, condition, isPerMessage, warn]);
}
diff --git a/packages/core/src/utils/devWarning.test.ts b/packages/core/src/utils/devWarning.test.ts
index a21ee25876..836323e085 100644
--- a/packages/core/src/utils/devWarning.test.ts
+++ b/packages/core/src/utils/devWarning.test.ts
@@ -1,6 +1,7 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {afterEach, describe, expect, it, vi} from 'vitest';
+import * as diagnostics from './devWarning';
import {
devWarn,
devError,
@@ -14,6 +15,54 @@ afterEach(() => {
vi.restoreAllMocks();
});
+function instanceWarnings() {
+ const create = diagnostics.createDevWarnings;
+ expect(typeof create).toBe('function');
+ return create();
+}
+
+describe('per-instance warnings', () => {
+ it('exposes a shared instance warning factory', () => {
+ instanceWarnings();
+ });
+ it('deduplicates messages per instance without sharing history across mounts', () => {
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const first = instanceWarnings();
+ first('Table', 'first');
+ first('Table', 'first');
+ first('Table', 'second');
+ const second = instanceWarnings();
+ second('Table', 'first');
+ expect(spy.mock.calls).toEqual([
+ ['Table: first'],
+ ['Table: second'],
+ ['Table: first'],
+ ]);
+ });
+ it('supports one stable key while preserving the current message prefix', () => {
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const warn = instanceWarnings();
+ warn('FirstComponent', 'initial', '');
+ warn('NextComponent', 'changed', '');
+ expect(spy.mock.calls).toEqual([['FirstComponent: initial']]);
+ });
+ it('keeps production diagnostics silent', async () => {
+ const spy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ vi.stubEnv('NODE_ENV', 'production');
+ vi.resetModules();
+ try {
+ const production = await import('./devWarning');
+ const create = production.createDevWarnings;
+ expect(typeof create).toBe('function');
+ create()('Table', 'silent');
+ expect(spy).not.toHaveBeenCalled();
+ } finally {
+ vi.unstubAllEnvs();
+ vi.resetModules();
+ }
+ });
+});
+
describe('formatDevMessage', () => {
it('formats as "Component: message"', () => {
expect(formatDevMessage('Field', 'oops')).toBe('Field: oops');
diff --git a/packages/core/src/utils/devWarning.ts b/packages/core/src/utils/devWarning.ts
index ad8f4960d0..9519296d34 100644
--- a/packages/core/src/utils/devWarning.ts
+++ b/packages/core/src/utils/devWarning.ts
@@ -48,6 +48,25 @@ export function devWarn(
console.warn(formatDevMessage(component, message), ...args);
}
+/** Warns once for each key. Internal. */
+export type DevWarnings = (
+ component: string,
+ message: string,
+ key?: string,
+) => void;
+
+/** Per-instance diagnostics for hooks and imperative callbacks. Internal. */
+export function createDevWarnings(): DevWarnings {
+ const warned = new Set<string>();
+ return (component: string, message: string, key: string = message): void => {
+ if (process.env.NODE_ENV === 'production' || warned.has(key)) {
+ return;
+ }
+ warned.add(key);
+ devWarn(component, message);
+ };
+}
+
/**
* `console.error` in the standardized `Component: message` format. Unlike
* {@link devWarn}, this runs in production too: it reports real runtime
diff --git a/packages/core/src/utils/focusReturn.test.ts b/packages/core/src/utils/focusReturn.test.ts
index bd31609819..cf9d5d3c7e 100644
--- a/packages/core/src/utils/focusReturn.test.ts
+++ b/packages/core/src/utils/focusReturn.test.ts
@@ -1,8 +1,11 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect, afterEach, beforeEach, vi} from 'vitest';
+import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
import {
focusForLastInput,
+ focusForLastInputTemporarily,
+ releaseTemporaryFocus,
isFocusLost,
moveFocusLeftBehind,
noteFocusWithin,
@@ -194,6 +197,129 @@ describe('focusForLastInput in a second document', () => {
});
});
+describe('temporary programmatic focus', () => {
+ afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+ });
+
+ it('uses the canonical focusable selector before acquiring a temporary tab stop', () => {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const matches = vi.spyOn(target, 'matches');
+ const dispose = focusForLastInputTemporarily(target);
+ expect(matches).toHaveBeenCalledWith(FOCUSABLE_SELECTOR);
+ expect(target).toHaveAttribute('tabindex', '-1');
+ dispose();
+ expect(target).not.toHaveAttribute('tabindex');
+ });
+
+ it('passes options and modality through and releases its attribute and listener on dispose', () => {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const focus = vi.spyOn(target, 'focus');
+ const remove = vi.spyOn(target, 'removeEventListener');
+ const dispose = focusForLastInputTemporarily(
+ target,
+ {preventScroll: true},
+ 'pointer',
+ );
+ expect(target).toHaveFocus();
+ expect(focus).toHaveBeenLastCalledWith({
+ preventScroll: true,
+ focusVisible: false,
+ });
+ expect(target).toHaveAttribute('tabindex', '-1');
+ dispose();
+ dispose();
+ expect(target).not.toHaveAttribute('tabindex');
+ expect(remove).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(['button', 'input', 'textarea', 'select'])(
+ 'preserves native %s focusability',
+ tag => {
+ const target = document.createElement(tag);
+ document.body.append(target);
+ const dispose = focusForLastInputTemporarily(target);
+ expect(target).toHaveFocus();
+ expect(target).not.toHaveAttribute('tabindex');
+ dispose();
+ expect(target).not.toHaveAttribute('tabindex');
+ },
+ );
+
+ it.each(['-1', '0', '3'])('preserves authored tabindex %s', value => {
+ const target = document.createElement('div');
+ target.setAttribute('tabindex', value);
+ document.body.append(target);
+ const dispose = focusForLastInputTemporarily(target);
+ expect(target).toHaveFocus();
+ target.blur();
+ dispose();
+ releaseTemporaryFocus(target);
+ expect(target).toHaveAttribute('tabindex', value);
+ });
+
+ it('keeps later authored changes and lets a newer focus owner survive old cleanup', () => {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const first = focusForLastInputTemporarily(target);
+ const second = focusForLastInputTemporarily(
+ target,
+ {preventScroll: true},
+ 'pointer',
+ );
+ first();
+ expect(target).toHaveFocus();
+ expect(target).toHaveAttribute('tabindex', '-1');
+ target.setAttribute('tabindex', '2');
+ second();
+ expect(target).toHaveAttribute('tabindex', '2');
+ });
+
+ it('explicitly releases ownership after removal and can refocus with keyboard options', () => {
+ const target = document.createElement('div');
+ document.body.append(target);
+ const focus = vi.spyOn(target, 'focus');
+ focusForLastInputTemporarily(target, {preventScroll: true}, 'keyboard');
+ expect(focus).toHaveBeenLastCalledWith({preventScroll: true});
+ target.remove();
+ releaseTemporaryFocus(target);
+ expect(target).not.toHaveAttribute('tabindex');
+ document.body.append(target);
+ const dispose = focusForLastInputTemporarily(target);
+ expect(target).toHaveFocus();
+ dispose();
+ });
+
+ it('cleans a target that cannot take focus and explicit release is idempotent', () => {
+ const target = document.createElement('div');
+ const dispose = focusForLastInputTemporarily(target);
+ expect(target).not.toHaveAttribute('tabindex');
+ releaseTemporaryFocus(target);
+ dispose();
+ expect(target).not.toHaveAttribute('tabindex');
+ });
+
+ it('lets a removal caller preserve scroll through the optional focus options', () => {
+ const container = document.createElement('div');
+ const inside = document.createElement('button');
+ container.append(inside);
+ document.body.append(container);
+ inside.focus();
+ const note = noteFocusWithin(container);
+ inside.remove();
+ const focus = vi.spyOn(container, 'focus');
+ expect(
+ moveFocusLeftBehind(note, container, null, {preventScroll: true}),
+ ).toBe(true);
+ expect(focus.mock.calls.at(-1)?.[0]).toMatchObject({preventScroll: true});
+ releaseTemporaryFocus(container);
+ expect(container).not.toHaveAttribute('tabindex');
+ });
+});
+
describe('isFocusLost', () => {
afterEach(() => {
document.body.innerHTML = '';
@@ -256,6 +382,28 @@ describe('noteFocusWithin and moveFocusLeftBehind', () => {
expect(target).toHaveFocus();
});
+ it('returns focus to an otherwise unfocusable container after removal', () => {
+ const {container, inside, outside} = setUp();
+ inside.focus();
+ const note = noteFocusWithin(container);
+ inside.remove();
+ expect(moveFocusLeftBehind(note, container)).toBe(true);
+ expect(container).toHaveFocus();
+ expect(container).toHaveAttribute('tabindex', '-1');
+ outside.focus();
+ expect(container).not.toHaveAttribute('tabindex');
+ });
+
+ it('preserves focus the caller chose after the noted element was removed', () => {
+ const {container, inside, target, outside} = setUp();
+ inside.focus();
+ const note = noteFocusWithin(container);
+ inside.remove();
+ outside.focus();
+ expect(moveFocusLeftBehind(note, target)).toBe(false);
+ expect(outside).toHaveFocus();
+ });
+
it('moves no focus that survived the change or was never inside', () => {
const {container, inside, target, outside} = setUp();
inside.focus();
diff --git a/packages/core/src/utils/focusReturn.ts b/packages/core/src/utils/focusReturn.ts
index 3a8d062201..227d4dfbfc 100644
--- a/packages/core/src/utils/focusReturn.ts
+++ b/packages/core/src/utils/focusReturn.ts
@@ -14,6 +14,7 @@
* which exports only it, does not reach this module.
*/
+import {FOCUSABLE_SELECTOR} from '../hooks/focusableSelector';
import {
getInteractionModality,
type InteractionModality,
@@ -69,6 +70,7 @@ export function moveFocusLeftBehind(
note: FocusWithin | null,
target: HTMLElement | null | undefined,
hidden: Element | null = null,
+ options?: FocusOptions,
): boolean {
if (
note == null ||
@@ -77,8 +79,53 @@ export function moveFocusLeftBehind(
) {
return false;
}
- focusForLastInput(target);
- return true;
+ focusForLastInputTemporarily(target, options);
+ return target.ownerDocument.activeElement === target;
+}
+
+const temporaryFocus = new WeakMap<HTMLElement, () => void>();
+
+/** Release only a temporary tab stop owned by this module. Internal. */
+export function releaseTemporaryFocus(element: HTMLElement): void {
+ temporaryFocus.get(element)?.();
+}
+
+/** Focuses the element. A nonfocusable element gets a tab stop until blur or disposal. Internal. */
+export function focusForLastInputTemporarily(
+ element: HTMLElement,
+ options?: FocusOptions,
+ modality: InteractionModality = getInteractionModality(element),
+): () => void {
+ releaseTemporaryFocus(element);
+ const needsTabIndex =
+ !element.hasAttribute('tabindex') &&
+ element.tabIndex < 0 &&
+ !element.isContentEditable &&
+ !element.matches(FOCUSABLE_SELECTOR);
+ if (!needsTabIndex) {
+ focusForLastInput(element, options, modality);
+ return () => {};
+ }
+ element.setAttribute('tabindex', '-1');
+ const dispose = () => {
+ if (temporaryFocus.get(element) !== dispose) {
+ return;
+ }
+ temporaryFocus.delete(element);
+ element.removeEventListener('blur', dispose);
+ if (element.getAttribute('tabindex') === '-1') {
+ element.removeAttribute('tabindex');
+ }
+ };
+ temporaryFocus.set(element, dispose);
+ focusForLastInput(element, options, modality);
+ // Pointer-modality refocus can blur first; acquire cleanup after that move.
+ if (element.ownerDocument.activeElement === element) {
+ element.addEventListener('blur', dispose, {once: true});
+ } else {
+ dispose();
+ }
+ return dispose;
}
/**