An open source design system that's fully customizable and agent ready
TypeScript
fix: suppress auto-focus in inline/showcase layer components (#2007)
Cindy Zhangb48764399a3b
diff --git a/packages/core/src/CommandPalette/CommandPaletteContext.ts b/packages/core/src/CommandPalette/CommandPaletteContext.tsindex 8413085955..d02404747c 100644--- a/packages/core/src/CommandPalette/CommandPaletteContext.ts+++ b/packages/core/src/CommandPalette/CommandPaletteContext.ts@@ -40,6 +40,8 @@ export interface CommandPaletteContextValue {isOpen: boolean;/** Whether an async search is in flight. */isBusy: boolean;+ /** Whether the palette is rendered inline (no modal behavior). */+ isInline: boolean;}export const CommandPaletteContext =diff --git a/packages/core/src/CommandPalette/XDSCommandPalette.doc.mjs b/packages/core/src/CommandPalette/XDSCommandPalette.doc.mjsindex 692688837d..e993333b6e 100644--- a/packages/core/src/CommandPalette/XDSCommandPalette.doc.mjs+++ b/packages/core/src/CommandPalette/XDSCommandPalette.doc.mjs@@ -104,7 +104,7 @@ export const docs = {{name: 'isInline',type: 'boolean',- description: 'Renders command palette content inline without modal behavior. For documentation previews and showcases only.',+ description: 'Renders command palette content inline without modal behavior. Automatically disables auto-focus on the input. For documentation previews and showcases only.',default: 'false',},],@@ -123,7 +123,7 @@ export const docs = {{name: 'hasAutoFocus',type: 'boolean',- description: 'Auto-focus the input when mounted.',+ description: 'Auto-focus the input when mounted. Automatically disabled when inside an inline command palette.',default: 'true',},{@@ -333,7 +333,7 @@ export const docsZh = {label: '命令面板对话框的无障碍标签。',width: '对话框宽度。',maxHeight: '对话框最大高度。',- isInline: '以内联方式渲染命令面板内容,不带模态行为。仅用于文档预览和展示。',+ isInline: '以内联方式渲染命令面板内容,不带模态行为。自动禁用输入框自动聚焦。仅用于文档预览和展示。',},},{@@ -341,7 +341,7 @@ export const docsZh = {description: '搜索输入插槽。挂载时自动聚焦。在 XDSCommandPalette 内使用时连接到上下文。',propDescriptions: {placeholder: '输入框的占位文本。',- hasAutoFocus: '挂载时自动聚焦输入框。',+ hasAutoFocus: '挂载时自动聚焦输入框。内联命令面板中自动禁用。',endContent: '渲染在输入框末尾的内容,位于加载指示器之后。',value: '搜索值。在 XDSCommandPalette 内省略时从上下文读取。',onValueChange: '搜索值变化时调用。在 XDSCommandPalette 内省略时写入上下文。',@@ -415,7 +415,7 @@ export const docsDense = {label: 'a11y label for dialog',width: 'dialog width',maxHeight: 'dialog max height',- isInline: 'inline rendering for docs previews, no modal behavior',+ isInline: 'inline rendering for docs previews, no modal behavior, auto-disables input focus',},},{@@ -423,7 +423,7 @@ export const docsDense = {description: 'search input; auto-focus on mount; wires to context inside XDSCommandPalette',propDescriptions: {placeholder: 'input placeholder text',- hasAutoFocus: 'auto-focus on mount',+ hasAutoFocus: 'auto-focus on mount; auto-disabled in inline mode',endContent: 'trailing content after spinner',value: 'search value; reads context when omitted inside palette',onValueChange: 'called on change; writes context when omitted inside palette',diff --git a/packages/core/src/CommandPalette/XDSCommandPalette.tsx b/packages/core/src/CommandPalette/XDSCommandPalette.tsxindex a88d0527c2..fde360f9d4 100644--- a/packages/core/src/CommandPalette/XDSCommandPalette.tsx+++ b/packages/core/src/CommandPalette/XDSCommandPalette.tsx@@ -448,6 +448,7 @@ export function XDSCommandPalette<onClose: handleClose,isOpen,isBusy,+ isInline: isInline ?? false,}),[optimisticSearch,@@ -466,6 +467,7 @@ export function XDSCommandPalette<handleClose,isOpen,isBusy,+ isInline,],);diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteInput.test.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteInput.test.tsxindex bd79b1525e..13b755f4fc 100644--- a/packages/core/src/CommandPalette/XDSCommandPaletteInput.test.tsx+++ b/packages/core/src/CommandPalette/XDSCommandPaletteInput.test.tsx@@ -8,6 +8,8 @@import {describe, it, expect, vi} from 'vitest';import {render, screen, fireEvent} from '@testing-library/react';import {XDSCommandPaletteInput} from './XDSCommandPaletteInput';+import {CommandPaletteContext} from './CommandPaletteContext';+import type {CommandPaletteContextValue} from './CommandPaletteContext';describe('XDSCommandPaletteInput', () => {it('renders with default placeholder', () => {@@ -67,3 +69,58 @@ describe('XDSCommandPaletteInput', () => {expect(input).toHaveAttribute('aria-autocomplete', 'list');});});++describe('XDSCommandPaletteInput inline context', () => {+ function makeContext(+ overrides: Partial<CommandPaletteContextValue> = {},+ ): CommandPaletteContextValue {+ return {+ search: '',+ setSearch: vi.fn(),+ value: '',+ setValue: vi.fn(),+ listId: 'list-1',+ highlightedIndex: -1,+ setHighlightedIndex: vi.fn(),+ getItemId: (i: number) => `item-${i}`,+ selectableItems: [],+ searchResults: [],+ selectItem: vi.fn(),+ onKeyDown: vi.fn(),+ onClose: vi.fn(),+ isOpen: true,+ isBusy: false,+ isInline: false,+ ...overrides,+ };+ }++ it('does not auto-focus when context isInline is true', () => {+ const focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');+ render(+ <CommandPaletteContext.Provider value={makeContext({isInline: true})}>+ <XDSCommandPaletteInput />+ </CommandPaletteContext.Provider>,+ );++ const input = screen.getByRole('combobox');+ const inputFocusCalls = focusSpy.mock.calls.filter((_, i) => {+ return focusSpy.mock.contexts[i] === input;+ });+ expect(inputFocusCalls).toHaveLength(0);+ focusSpy.mockRestore();+ });++ it('auto-focuses when context isInline is false', async () => {+ render(+ <CommandPaletteContext.Provider value={makeContext({isInline: false})}>+ <XDSCommandPaletteInput />+ </CommandPaletteContext.Provider>,+ );++ // Auto-focus uses requestAnimationFrame — flush it+ await vi.waitFor(() => {+ expect(screen.getByRole('combobox')).toHaveFocus();+ });+ });+});diff --git a/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsxindex 7081c00963..8515c34aa2 100644--- a/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx+++ b/packages/core/src/CommandPalette/XDSCommandPaletteInput.tsx@@ -174,6 +174,10 @@ export function XDSCommandPaletteInput({const value = controlledValue ?? ctx?.search;const handleValueChange = onValueChange ?? ctx?.setSearch;+ // When inside an inline CommandPalette, disable auto-focus by default+ // to avoid stealing focus from the surrounding page.+ const effectiveAutoFocus = hasAutoFocus && !(ctx?.isInline ?? false);+// Merge refsconst setRefs = (element: HTMLInputElement | null) => {(inputRef as React.MutableRefObject<HTMLInputElement | null>).current =@@ -188,12 +192,12 @@ export function XDSCommandPaletteInput({// Auto-focus on mountuseEffect(() => {- if (hasAutoFocus && inputRef.current) {+ if (effectiveAutoFocus && inputRef.current) {requestAnimationFrame(() => {inputRef.current?.focus();});}- }, [hasAutoFocus]);+ }, [effectiveAutoFocus]);// Keyboard navigation — delegates to useCombobox via contextconst handleKeyDown = useCallback(diff --git a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjsindex 1100ccfc74..5ee3441be2 100644--- a/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs+++ b/packages/core/src/DropdownMenu/DropdownMenu.doc.mjs@@ -65,6 +65,12 @@ export const docs = {description: 'Whether to show a chevron icon on the trigger button. Set to false for icon-only triggers.',default: 'true',},+ {+ name: 'hasAutoFocus',+ type: 'boolean',+ description: 'Whether to auto-focus the first menu item when the menu opens. Set to false for inline showcases or documentation previews.',+ default: 'true',+ },{name: 'children',type: '(item: XDSDropdownMenuItemData) => ReactNode',@@ -250,6 +256,12 @@ export const docsZh = {description: '是否在触发按钮上显示展开箭头。仅图标触发器设为 false。',default: 'true',},+ {+ name: 'hasAutoFocus',+ type: 'boolean',+ description: '菜单打开时是否自动聚焦第一个菜单项。内联展示或文档预览设为 false。',+ default: 'true',+ },{name: 'children',type: '(item: XDSDropdownMenuItemData) => ReactNode',@@ -396,6 +408,7 @@ export const docsDense = {menuWidth: 'custom menu width; default matches trigger button',onClick: 'trigger button click callback',hasChevron: 'show chevron on trigger; false for icon-only triggers',+ hasAutoFocus: 'auto-focus first item on open; false for showcases',children: 'custom render fn per item',},},diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsxindex 7405411d30..8842751edc 100644--- a/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx+++ b/packages/core/src/DropdownMenu/XDSDropdownMenu.test.tsx@@ -154,6 +154,29 @@ describe('XDSDropdownMenu controlled mode', () => {});});+describe('XDSDropdownMenu hasAutoFocus', () => {+ it('does not focus menu items when hasAutoFocus is false and isMenuOpen is true', () => {+ const focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');+ render(+ <XDSDropdownMenu+ button={{label: 'Actions'}}+ items={[{label: 'Edit'}, {label: 'Delete'}]}+ isMenuOpen={true}+ hasAutoFocus={false}+ onOpenChange={() => {}}+ />,+ );++ const menuItems = screen.getAllByRole('menuitem', {hidden: true});+ const menuItemFocusCalls = focusSpy.mock.calls.filter((_, i) => {+ const ctx = focusSpy.mock.contexts[i];+ return menuItems.includes(ctx as HTMLElement);+ });+ expect(menuItemFocusCalls).toHaveLength(0);+ focusSpy.mockRestore();+ });+});+describe('XDSDropdownMenu items', () => {it('renders items with labels', () => {render(diff --git a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsxindex ecb2d8e0da..aba6db32e8 100644--- a/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx+++ b/packages/core/src/DropdownMenu/XDSDropdownMenu.tsx@@ -118,6 +118,13 @@ interface XDSDropdownMenuBaseProps extends XDSBaseProps {menuWidth?: number | string;onClick?: () => void;hasChevron?: boolean;+ /**+ * Whether to auto-focus the first menu item when the menu opens.+ * Set to `false` for inline showcases or documentation previews+ * where stealing focus is undesirable.+ * @default true+ */+ hasAutoFocus?: boolean;'data-testid'?: string;}@@ -166,6 +173,7 @@ export function XDSDropdownMenu({menuWidth,onClick,hasChevron = true,+ hasAutoFocus = true,className,style,xstyle,@@ -218,16 +226,6 @@ export function XDSDropdownMenu({hasAutoFocus: false,});- React.useEffect(() => {- if (isControlled) {- if (controlledIsOpen && !popover.isOpen) {- popover.show();- } else if (!controlledIsOpen && popover.isOpen) {- popover.hide();- }- }- }, [controlledIsOpen, isControlled, popover]);-const closeMenu = useCallback(() => {popover.hide();}, [popover]);@@ -243,6 +241,20 @@ export function XDSDropdownMenu({onEscape: closeMenu,});+ // Sync controlled open state → popover, and focus first item on open+ React.useEffect(() => {+ if (isControlled) {+ if (controlledIsOpen && !popover.isOpen) {+ popover.show();+ if (hasAutoFocus) {+ requestAnimationFrame(() => focusFirst());+ }+ } else if (!controlledIsOpen && popover.isOpen) {+ popover.hide();+ }+ }+ }, [controlledIsOpen, isControlled, popover, hasAutoFocus, focusFirst]);+// Extend useListFocus with Enter/Space activationconst listKeyDown = useCallback((e: React.KeyboardEvent) => {@@ -261,8 +273,10 @@ export function XDSDropdownMenu({const openAndFocus = useCallback(() => {popover.show();- requestAnimationFrame(() => focusFirst());- }, [popover, focusFirst]);+ if (hasAutoFocus) {+ requestAnimationFrame(() => focusFirst());+ }+ }, [popover, hasAutoFocus, focusFirst]);const handleButtonClick = useCallback(() => {onClick?.();