Skip to content

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

TypeScript

fix(Dialog): auto-focus first input element when dialog opens (#1044)

Andrey Goder8d476d14de8c
diff --git a/apps/storybook/stories/Dialog.stories.tsx b/apps/storybook/stories/Dialog.stories.tsx
index 11aa19c86a..8bf6d2d944 100644
--- a/apps/storybook/stories/Dialog.stories.tsx
+++ b/apps/storybook/stories/Dialog.stories.tsx
@@ -9,6 +9,7 @@ import {
} from '@xds/core/Layout';
import {XDSButton} from '@xds/core/Button';
import {XDSText} from '@xds/core/Text';
+import {XDSTextInput} from '@xds/core/TextInput';
import * as stylex from '@stylexjs/stylex';
const styles = stylex.create({
@@ -654,3 +655,45 @@ export const AllPurposes: Story = {
</div>
),
};
+
+/**
+ * Dialog with auto-focused input
+ */
+function AutoFocusInputExample() {
+ const [isOpen, setIsOpen] = useState(false);
+ const [value, setValue] = useState('');
+ return (
+ <>
+ <XDSButton
+ label="Open Dialog"
+ variant="secondary"
+ onClick={() => setIsOpen(true)}
+ />
+ <XDSDialog isOpen={isOpen} onOpenChange={open => setIsOpen(open)}>
+ <XDSLayout
+ header={
+ <XDSDialogHeader
+ title="Auto-focused Input"
+ onOpenChange={open => setIsOpen(open)}
+ />
+ }
+ content={
+ <XDSLayoutContent>
+ <XDSTextInput
+ label="Name"
+ placeholder="This input is focused on mount"
+ value={value}
+ onChange={setValue}
+ hasAutoFocus
+ />
+ </XDSLayoutContent>
+ }
+ />
+ </XDSDialog>
+ </>
+ );
+}
+
+export const AutoFocusInput: Story = {
+ render: () => <AutoFocusInputExample />,
+};
diff --git a/packages/core/src/Dialog/XDSDialog.tsx b/packages/core/src/Dialog/XDSDialog.tsx
index 5e22672652..0125896389 100644
--- a/packages/core/src/Dialog/XDSDialog.tsx
+++ b/packages/core/src/Dialog/XDSDialog.tsx
@@ -307,6 +307,14 @@ export function XDSDialog({
if (isOpen) {
if (!dialog.open) {
dialog.showModal();
+ // React's autoFocus calls .focus() during commit, before showModal()
+ // makes the dialog visible, so the focus silently fails.
+ // Focus the first element with data-autofocus inside the dialog.
+ const autofocusTarget =
+ dialog.querySelector<HTMLElement>('[data-autofocus]');
+ if (autofocusTarget) {
+ autofocusTarget.focus();
+ }
}
} else {
if (dialog.open) {
diff --git a/packages/core/src/TextInput/XDSTextInput.tsx b/packages/core/src/TextInput/XDSTextInput.tsx
index 9029497c09..93c7aff6e5 100644
--- a/packages/core/src/TextInput/XDSTextInput.tsx
+++ b/packages/core/src/TextInput/XDSTextInput.tsx
@@ -299,6 +299,7 @@ export function XDSTextInput({
placeholder={placeholder}
disabled={isDisabled}
autoFocus={hasAutoFocus}
+ data-autofocus={hasAutoFocus || undefined}
aria-describedby={ariaDescribedBy}
aria-required={isRequired === true ? 'true' : undefined}
aria-invalid={status?.type === 'error' ? 'true' : undefined}