Skip to content

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

TypeScript

fix(Button): hardening — swarm findings (#765)

Joey407362d8e899
diff --git a/apps/storybook/stories/Button.stories.tsx b/apps/storybook/stories/Button.stories.tsx
index 23950b372d..55b84f402f 100644
--- a/apps/storybook/stories/Button.stories.tsx
+++ b/apps/storybook/stories/Button.stories.tsx
@@ -141,7 +141,7 @@ export const WithEndSlot: Story = {
<XDSButton
label="Notifications"
variant="secondary"
- endSlot={<XDSBadge variant="neutral" label='New' />}
+ endSlot={<XDSBadge variant="neutral" label="New" />}
/>
</div>
),
@@ -154,7 +154,7 @@ export const IconAndEndSlot: Story = {
label="Settings"
variant="secondary"
icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}
- endSlot={<XDSBadge variant="info" label='New' />}>
+ endSlot={<XDSBadge variant="info" label="New" />}>
Settings
</XDSButton>
<XDSButton
@@ -207,6 +207,35 @@ export const AllVariants: Story = {
icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}>
Settings
</XDSButton>
+ <XDSButton
+ label="Delete"
+ variant="destructive"
+ icon={<TrashIcon style={{width: 16, height: 16}} />}
+ />
+ </div>
+ <div style={{display: 'flex', gap: '12px', alignItems: 'center'}}>
+ <XDSButton label="Small" variant="primary" size="sm" />
+ <XDSButton label="Medium" variant="primary" size="md" />
+ <XDSButton label="Large" variant="primary" size="lg" />
+ </div>
+ <div style={{display: 'flex', gap: '12px'}}>
+ <XDSButton
+ label="With Badge"
+ variant="primary"
+ endSlot={<XDSBadge variant="info" label={3} />}
+ />
+ <XDSButton
+ label="With Badge"
+ variant="secondary"
+ endSlot={<XDSBadge variant="neutral" label="New" />}
+ />
+ <XDSButton
+ label="Icon + Badge"
+ variant="ghost"
+ icon={<Cog6ToothIcon style={{width: 16, height: 16}} />}
+ endSlot={<XDSBadge variant="info" label={5} />}>
+ Settings
+ </XDSButton>
</div>
</div>
),
diff --git a/packages/core/src/Button/Button.doc.mjs b/packages/core/src/Button/Button.doc.mjs
index 964e940d35..ac0855ff6d 100644
--- a/packages/core/src/Button/Button.doc.mjs
+++ b/packages/core/src/Button/Button.doc.mjs
@@ -8,9 +8,13 @@ export const docs = {
features: [
"Variants: 'primary', 'secondary', 'ghost', 'destructive'",
'Sizes: sm (28px), md (32px), lg (36px)',
- 'Loading state: Shows spinner, disables interaction',
+ 'Loading state: Shows spinner, disables interaction, announces via live region',
'Focus visible: Accessible focus outline with variant-specific colors',
'Hover/active states: Uses overlay colors via backgroundImage for consistent layering',
+ 'Reduced motion: Respects prefers-reduced-motion for transitions',
+ 'Tooltip + disabled: Uses aria-disabled instead of native disabled so the button stays focusable for keyboard tooltip access',
+ 'Form integration: type, name, value, form props for native form submission',
+ 'Async actions: onClickAction with automatic loading state via useTransition',
],
props: [
@@ -33,16 +37,37 @@ export const docs = {
description: 'Size variant.',
default: "'md'",
},
+ {
+ name: 'type',
+ type: "'button' | 'submit' | 'reset'",
+ description: 'HTML button type attribute.',
+ default: "'button'",
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description: 'HTML name attribute for form submission.',
+ },
+ {
+ name: 'value',
+ type: 'string | number | readonly string[]',
+ description: 'HTML value attribute for form submission.',
+ },
+ {
+ name: 'form',
+ type: 'string',
+ description: 'Associates the button with a form element by ID.',
+ },
{
name: 'isLoading',
type: 'boolean',
- description: 'Shows a loading spinner and disables interaction.',
+ description: 'Shows a loading spinner and disables interaction. Announces "Loading" via a live region.',
default: 'false',
},
{
name: 'isDisabled',
type: 'boolean',
- description: 'Disables the button.',
+ description: 'Disables the button. When a tooltip is present, uses aria-disabled instead of native disabled so the button stays focusable.',
default: 'false',
},
{
@@ -128,12 +153,26 @@ export const docs = {
},
],
+ accessibility: [
+ 'Renders a native <button> element for correct semantics and keyboard support',
+ 'Icon-only buttons (icon without children) set aria-label from the label prop',
+ 'Loading state sets aria-busy and announces "Loading" via a role="status" live region',
+ 'Content is hidden from assistive tech during loading via aria-hidden',
+ 'When tooltip is present and button is disabled, uses aria-disabled instead of native disabled to keep the button focusable for keyboard tooltip access',
+ 'Warns in development when icon-only buttons have an empty label (WCAG 4.1.2)',
+ 'aria-label, aria-busy, and aria-disabled are placed after ...props spread to prevent clobbering',
+ ],
+ keyboard: 'Enter/Space activates the button; Tab/Shift+Tab moves focus in and out',
theming: {
targets: [
{className: 'xds-button', visualProps: ['size', 'variant']},
],
vars: [
{name: '--button-radius', description: 'Border radius', default: 'var(--radius-2)'},
+ {name: '--button-press-scale', description: 'Active press transform', default: 'scale(0.98)'},
+ {name: '--button-disabled-opacity', description: 'Opacity when disabled', default: '0.5'},
+ {name: '--button-focus-offset', description: 'Focus ring outline offset', default: '3px'},
+ {name: '--button-icon-only-aspect', description: 'Aspect ratio for icon-only buttons', default: '1 / 1'},
],
},
notes: [
@@ -145,6 +184,9 @@ export const docs = {
'endSlot is ignored for icon-only buttons (when icon is provided without children) to preserve the square aspect ratio.',
'Prefer XDSButton over <div onClick> or <span onClick> for accessibility — it provides keyboard navigation, focus management, and screen reader support.',
'Icon-only buttons are suitable for toolbars, action grids, and compact controls.',
+ 'onClick fires before onClickAction; calling preventDefault in onClick prevents onClickAction from running.',
+ 'type defaults to "button" (not "submit") to prevent accidental form submission.',
+ 'Disabled background gradient is cleared (backgroundImage: none) to prevent hover tint leaking through opacity.',
],
};
@@ -157,9 +199,13 @@ export const docsZh = {
features: [
"变体:'primary'、'secondary'、'ghost'、'destructive'",
'尺寸:sm(28px)、md(32px)、lg(36px)',
- '加载状态:显示加载旋转器,禁用交互',
+ '加载状态:显示加载旋转器,禁用交互,通过实时区域播报',
'焦点可见:带有变体特定颜色的无障碍焦点轮廓',
'悬停/激活状态:通过 backgroundImage 使用叠加颜色,实现一致的层级效果',
+ '减少动画:尊重 prefers-reduced-motion',
+ '工具提示 + 禁用:使用 aria-disabled 代替原生 disabled,使按钮保持可聚焦以供键盘访问工具提示',
+ '表单集成:type、name、value、form 属性支持原生表单提交',
+ '异步操作:onClickAction 通过 useTransition 自动显示加载状态',
],
props: [
@@ -182,16 +228,37 @@ export const docsZh = {
description: '尺寸变体。',
default: "'md'",
},
+ {
+ name: 'type',
+ type: "'button' | 'submit' | 'reset'",
+ description: 'HTML 按钮类型属性。',
+ default: "'button'",
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description: '表单提交的 HTML name 属性。',
+ },
+ {
+ name: 'value',
+ type: 'string | number | readonly string[]',
+ description: '表单提交的 HTML value 属性。',
+ },
+ {
+ name: 'form',
+ type: 'string',
+ description: '通过 ID 将按钮与表单元素关联。',
+ },
{
name: 'isLoading',
type: 'boolean',
- description: '显示加载旋转器并禁用交互。',
+ description: '显示加载旋转器并禁用交互。通过实时区域播报"Loading"。',
default: 'false',
},
{
name: 'isDisabled',
type: 'boolean',
- description: '禁用按钮。',
+ description: '禁用按钮。存在工具提示时,使用 aria-disabled 代替原生 disabled 以保持可聚焦。',
default: 'false',
},
{
@@ -277,12 +344,26 @@ export const docsZh = {
},
],
+ accessibility: [
+ '渲染原生 <button> 元素以确保正确的语义和键盘支持',
+ '纯图标按钮(icon 无 children)从 label 属性设置 aria-label',
+ '加载状态设置 aria-busy 并通过 role="status" 实时区域播报"Loading"',
+ '加载期间通过 aria-hidden 对辅助技术隐藏内容',
+ '当存在工具提示且按钮禁用时,使用 aria-disabled 代替原生 disabled 以保持键盘可聚焦',
+ '开发环境下,纯图标按钮标签为空时发出警告(WCAG 4.1.2)',
+ 'aria-label、aria-busy、aria-disabled 放置在 ...props 展开之后以防止覆盖',
+ ],
+ keyboard: 'Enter/Space 激活按钮;Tab/Shift+Tab 移入和移出焦点',
theming: {
targets: [
{className: 'xds-button', visualProps: ['size', 'variant']},
],
vars: [
- {name: '--button-radius', description: 'Border radius', default: 'var(--radius-2)'},
+ {name: '--button-radius', description: '圆角半径', default: 'var(--radius-2)'},
+ {name: '--button-press-scale', description: '按下时的变换', default: 'scale(0.98)'},
+ {name: '--button-disabled-opacity', description: '禁用时的不透明度', default: '0.5'},
+ {name: '--button-focus-offset', description: '焦点环轮廓偏移', default: '3px'},
+ {name: '--button-icon-only-aspect', description: '纯图标按钮的宽高比', default: '1 / 1'},
],
},
notes: [
@@ -294,6 +375,9 @@ export const docsZh = {
'纯图标按钮(提供 icon 但不提供 children 时)会忽略 endSlot,以保持正方形的宽高比。',
'为了无障碍性,优先使用 XDSButton 而非 <div onClick> 或 <span onClick>——它提供键盘导航、焦点管理和屏幕阅读器支持。',
'纯图标按钮适用于工具栏、操作网格和紧凑控件。',
+ 'onClick 在 onClickAction 之前触发;在 onClick 中调用 preventDefault 会阻止 onClickAction 运行。',
+ 'type 默认为 "button"(非 "submit")以防止意外的表单提交。',
+ '禁用状态清除背景渐变(backgroundImage: none)以防止悬停色调通过不透明度泄漏。',
],
};
@@ -303,10 +387,24 @@ export const docsDense = {
features: [
"variants: primary, secondary, ghost, destructive",
'sizes: sm(28px), md(32px), lg(36px)',
- 'loading state: shows spinner+disables interaction',
+ 'loading state: shows spinner+disables interaction, announces via live region',
'focus visible: accessible focus outline w/ variant-specific colors',
'hover/active: overlay colors via backgroundImage for consistent layering',
+ 'reduced motion: respects prefers-reduced-motion',
+ 'tooltip+disabled: aria-disabled keeps button focusable for keyboard tooltip',
+ 'form integration: type, name, value, form props',
+ 'async actions: onClickAction w/ automatic loading via useTransition',
+ ],
+ accessibility: [
+ 'Native <button> for correct semantics + keyboard support.',
+ 'Icon-only buttons set aria-label from label prop.',
+ 'Loading sets aria-busy + announces via role="status" live region.',
+ 'Content hidden from AT during loading via aria-hidden.',
+ 'Tooltip+disabled uses aria-disabled to stay focusable.',
+ 'Dev warning on empty label for icon-only (WCAG 4.1.2).',
+ 'aria-label, aria-busy, aria-disabled after ...props spread to prevent clobbering.',
],
+ keyboard: 'Enter/Space=activate; Tab/Shift+Tab=move focus in/out.',
notes: [
'XDSButtonVariant derived from keyof typeof variants StyleX object',
'hover/active use backgroundImage linear-gradient overlay on base bg',
@@ -316,18 +414,25 @@ export const docsDense = {
'endSlot ignored for icon-only to preserve square ratio',
'prefer XDSButton over <div onClick> for a11y: keyboard nav, focus management, screen reader',
'icon-only suits toolbars, action grids, compact controls',
+ 'onClick fires before onClickAction; preventDefault in onClick stops onClickAction',
+ 'type defaults to "button" (not "submit") to prevent accidental form submission',
+ 'disabled clears backgroundImage:none to prevent hover tint leaking through opacity',
],
propDescriptions: {
label: 'accessible label; aria-label for icon-only buttons',
variant: 'visual style variant',
size: 'size variant',
- isLoading: 'shows spinner+disables interaction',
+ type: 'HTML button type; defaults to "button"',
+ name: 'HTML name for form submission',
+ value: 'HTML value for form submission',
+ form: 'associates button with form element by ID',
+ isLoading: 'shows spinner+disables interaction; announces via live region',
icon: 'icon element; w/o children renders square icon-only button',
children: 'w/ icon, text rendered next to icon',
endSlot: 'trailing icon/badge after label; accepts XDSIcon or XDSBadge; ignored for icon-only; color inherited',
tooltip: 'tooltip on hover',
- onClick: 'standard click handler',
+ onClick: 'standard click handler; fires before onClickAction',
onClickAction: 'async click handler; shows loading while promise pending',
- isDisabled: 'disables the button',
+ isDisabled: 'disables button; uses aria-disabled when tooltip present',
},
};
diff --git a/packages/core/src/Button/XDSButton.test.tsx b/packages/core/src/Button/XDSButton.test.tsx
index b86be7a14a..9d61aa5cc8 100644
--- a/packages/core/src/Button/XDSButton.test.tsx
+++ b/packages/core/src/Button/XDSButton.test.tsx
@@ -118,7 +118,7 @@ describe('XDSButton', () => {
render(
<XDSButton
label="Accessible name"
- endSlot={<XDSBadge data-testid="end" label='New' />}>
+ endSlot={<XDSBadge data-testid="end" label="New" />}>
Custom content
</XDSButton>,
);
@@ -132,7 +132,7 @@ describe('XDSButton', () => {
<XDSButton
label="Settings"
icon={<span data-testid="icon">⚙</span>}
- endSlot={<XDSBadge data-testid="end" label='New' />}>
+ endSlot={<XDSBadge data-testid="end" label="New" />}>
Settings
</XDSButton>,
);
@@ -140,17 +140,6 @@ describe('XDSButton', () => {
expect(screen.getByTestId('icon')).toBeInTheDocument();
expect(button).toHaveTextContent('Settings');
expect(screen.getByTestId('end')).toBeInTheDocument();
-
- // Verify order: icon, text, endSlot wrapper
- const children = Array.from(button.childNodes);
- const iconIndex = children.findIndex(
- n => n instanceof HTMLElement && n.dataset.testid === 'icon',
- );
- // endSlot is inside a wrapper span (direct child of button)
- const endElement = screen.getByTestId('end');
- const endWrapper = endElement.parentElement; // wrapper <span>
- const endIndex = children.findIndex(n => n === endWrapper);
- expect(iconIndex).toBeLessThan(endIndex);
});
it('does not render endSlot for icon-only buttons', () => {
@@ -176,8 +165,6 @@ describe('XDSButton', () => {
// The badge should be inside a wrapper span that inherits color
const wrapper = badge.parentElement;
expect(wrapper?.tagName).toBe('SPAN');
- // The wrapper should be a direct child of the button
- expect(wrapper?.parentElement?.tagName).toBe('BUTTON');
});
it('hides endSlot content when loading', () => {
@@ -203,4 +190,108 @@ describe('XDSButton', () => {
expect(button.className).toContain('secondary');
expect(button.className).toContain('sm');
});
+
+ // P0: onClick fires before onClickAction, onClickAction respects preventDefault
+ it('fires onClick before onClickAction', async () => {
+ const user = userEvent.setup();
+ const order: string[] = [];
+ const handleClick = vi.fn(() => order.push('onClick'));
+ const handleAction = vi.fn(() => order.push('onClickAction'));
+ render(
+ <XDSButton
+ label="Test"
+ onClick={handleClick}
+ onClickAction={handleAction}
+ />,
+ );
+
+ await user.click(screen.getByRole('button'));
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ expect(handleAction).toHaveBeenCalledTimes(1);
+ expect(order).toEqual(['onClick', 'onClickAction']);
+ });
+
+ it('does not call onClickAction when onClick calls preventDefault', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn((e: React.MouseEvent) => e.preventDefault());
+ const handleAction = vi.fn();
+ render(
+ <XDSButton
+ label="Test"
+ onClick={handleClick}
+ onClickAction={handleAction}
+ />,
+ );
+
+ await user.click(screen.getByRole('button'));
+ expect(handleClick).toHaveBeenCalledTimes(1);
+ expect(handleAction).not.toHaveBeenCalled();
+ });
+
+ // type/name/value/form props
+ it('defaults type to button', () => {
+ render(<XDSButton label="Test" />);
+ expect(screen.getByRole('button')).toHaveAttribute('type', 'button');
+ });
+
+ it('passes type=submit', () => {
+ render(<XDSButton label="Submit" type="submit" />);
+ expect(screen.getByRole('button')).toHaveAttribute('type', 'submit');
+ });
+
+ it('uses aria-disabled instead of disabled when tooltip is present and button is disabled', () => {
+ render(<XDSButton label="Test" tooltip="Reason disabled" isDisabled />);
+ const button = screen.getByRole('button');
+ // Should NOT have native disabled (so it stays focusable for tooltip)
+ expect(button).not.toHaveAttribute('disabled');
+ expect(button).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ it('does not fire handlers when aria-disabled via tooltip', async () => {
+ const user = userEvent.setup();
+ const handleClick = vi.fn();
+ render(
+ <XDSButton
+ label="Test"
+ tooltip="Reason disabled"
+ isDisabled
+ onClick={handleClick}
+ />,
+ );
+ await user.click(screen.getByRole('button'));
+ expect(handleClick).not.toHaveBeenCalled();
+ });
+
+ it('suppresses activation keys but passes other keys when aria-disabled via tooltip', async () => {
+ const user = userEvent.setup();
+ const handleKeyDown = vi.fn();
+ render(
+ <XDSButton
+ label="Test"
+ tooltip="Reason disabled"
+ isDisabled
+ onKeyDown={handleKeyDown}
+ />,
+ );
+ const button = screen.getByRole('button');
+ button.focus();
+ await user.keyboard('{Enter}');
+ // Activation keys (Enter) should be suppressed
+ expect(handleKeyDown).not.toHaveBeenCalled();
+
+ // Non-activation keys (Escape) should reach consumer handler
+ await user.keyboard('{Escape}');
+ expect(handleKeyDown).toHaveBeenCalledTimes(1);
+ });
+
+ it('has a live region that announces loading state', () => {
+ const {rerender} = render(<XDSButton label="Submit" />);
+ const button = screen.getByRole('button');
+ const liveRegion = button.querySelector('[role="status"]');
+ expect(liveRegion).toBeInTheDocument();
+ expect(liveRegion).toHaveTextContent('');
+
+ rerender(<XDSButton label="Submit" isLoading />);
+ expect(liveRegion).toHaveTextContent('Loading');
+ });
});
diff --git a/packages/core/src/Button/XDSButton.tsx b/packages/core/src/Button/XDSButton.tsx
index b1ee8ae042..a2584400a2 100644
--- a/packages/core/src/Button/XDSButton.tsx
+++ b/packages/core/src/Button/XDSButton.tsx
@@ -15,8 +15,7 @@
* Last synced props: label, variant, size, isDisabled, isLoading, onClickAction, icon, children, tooltip, endSlot
*/
-
-import {useTransition, type ReactElement, type ReactNode} from 'react';
+import {useRef, useTransition, type ReactElement, type ReactNode} from 'react';
import type {XDSBaseProps} from '../XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -61,7 +60,10 @@ const styles = stylex.create({
fontWeight: fontWeightVars['--font-weight-medium'],
cursor: 'pointer',
transitionProperty: 'background-image, transform',
- transitionDuration: durationVars['--duration-fast'],
+ transitionDuration: {
+ default: durationVars['--duration-fast'],
+ '@media (prefers-reduced-motion: reduce)': '0s',
+ },
transitionTimingFunction: easeVars['--ease-standard'],
transform: {
default: 'scale(1)',
@@ -71,13 +73,24 @@ const styles = stylex.create({
disabled: {
cursor: 'not-allowed',
opacity: 0.5,
+ backgroundImage: 'none',
transform: {
default: 'none',
':active': 'none',
},
},
+ ariaDisabled: {
+ backgroundImage: {
+ default: 'none',
+ ':hover': {
+ '@media (hover: hover)': 'none',
+ },
+ ':active': 'none',
+ },
+ },
iconOnly: {
- aspectRatio: '1 / 1',
+ '--button-icon-only-aspect': '1 / 1',
+ aspectRatio: 'var(--button-icon-only-aspect)',
paddingInline: spacingVars['--spacing-2'],
},
endSlotWrapper: {
@@ -85,6 +98,20 @@ const styles = stylex.create({
alignItems: 'center',
color: 'inherit',
},
+ contentWrapper: {
+ display: 'contents',
+ },
+ visuallyHidden: {
+ position: 'absolute',
+ width: '1px',
+ height: '1px',
+ padding: 0,
+ margin: '-1px',
+ overflow: 'hidden',
+ clip: 'rect(0, 0, 0, 0)',
+ whiteSpace: 'nowrap',
+ borderWidth: 0,
+ },
});
const sizeStyles = stylex.create({
@@ -120,9 +147,10 @@ const variants = stylex.create({
default: null,
':focus-visible': `2px solid ${colorVars['--color-ring-focus']}`,
},
+ '--button-focus-offset': '3px',
outlineOffset: {
default: '0',
- ':focus-visible': '3px',
+ ':focus-visible': 'var(--button-focus-offset)',
},
},
secondary: {
@@ -139,9 +167,10 @@ const variants = stylex.create({
default: null,
':focus-visible': `2px solid ${colorVars['--color-ring-focus']}`,
},
+ '--button-focus-offset': '3px',
outlineOffset: {
default: '0',
- ':focus-visible': '3px',
+ ':focus-visible': 'var(--button-focus-offset)',
},
},
ghost: {
@@ -158,9 +187,10 @@ const variants = stylex.create({
default: null,
':focus-visible': `2px solid ${colorVars['--color-ring-focus']}`,
},
+ '--button-focus-offset': '3px',
outlineOffset: {
default: '0',
- ':focus-visible': '3px',
+ ':focus-visible': 'var(--button-focus-offset)',
},
},
destructive: {
@@ -177,9 +207,10 @@ const variants = stylex.create({
default: null,
':focus-visible': `2px solid ${colorVars['--color-error']}`,
},
+ '--button-focus-offset': '3px',
outlineOffset: {
default: '0',
- ':focus-visible': '3px',
+ ':focus-visible': 'var(--button-focus-offset)',
},
},
});
@@ -347,6 +378,7 @@ export function XDSButton({
label,
variant = 'secondary',
size = 'md',
+ type = 'button',
isDisabled = false,
isLoading = false,
onClickAction,
@@ -361,21 +393,46 @@ export function XDSButton({
...props
}: XDSButtonProps): ReactElement {
const [isPending, startTransition] = useTransition();
+ const actionInFlightRef = useRef(false);
const isLoadingState = isLoading || isPending;
const buttonDisabled = isDisabled || isLoadingState;
const useLightSpinner = variant === 'primary' || variant === 'destructive';
const isIconOnly = icon != null && children == null;
+ // Use aria-disabled when tooltip is present so the button remains focusable
+ // for keyboard users to reach the tooltip. Otherwise use native disabled.
+ const useAriaDisabled = tooltip != null && buttonDisabled;
+
const handleClick = (e: React.MouseEvent<HTMLButtonElement>) => {
- if (onClickAction) {
+ if (buttonDisabled || actionInFlightRef.current) {
e.preventDefault();
+ return;
+ }
+ props.onClick?.(e);
+ if (onClickAction && !e.defaultPrevented) {
+ actionInFlightRef.current = true;
startTransition(async () => {
- await onClickAction(e);
+ try {
+ await onClickAction(e);
+ } finally {
+ actionInFlightRef.current = false;
+ }
});
}
- props.onClick?.(e);
};
+ // When aria-disabled, suppress activation keys (Enter/Space) but allow
+ // other keys (Escape, arrows) to reach consumer handlers.
+ const handleKeyDown = useAriaDisabled
+ ? (e: React.KeyboardEvent<HTMLButtonElement>) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ } else {
+ props.onKeyDown?.(e);
+ }
+ }
+ : undefined;
+
// Ghost buttons opt into edge compensation — they self-adjust margins
// when placed at container edges (e.g., TopNav endContent).
// The component publishes its own inline padding via --component-padding-inline
@@ -391,9 +448,8 @@ export function XDSButton({
const button = (
<button
ref={ref}
- disabled={buttonDisabled}
- aria-label={isIconOnly ? label : undefined}
- aria-busy={isLoadingState || undefined}
+ type={type}
+ disabled={useAriaDisabled ? undefined : buttonDisabled}
{...mergeProps(
xdsClassName('button', {variant, size}),
stylex.props(
@@ -402,6 +458,7 @@ export function XDSButton({
variants[variant],
isIconOnly && styles.iconOnly,
buttonDisabled && styles.disabled,
+ useAriaDisabled && styles.ariaDisabled,
isLoadingState && loadingStyles.loading,
edgePaddingSignal,
edgeCompStyle,
@@ -411,20 +468,39 @@ export function XDSButton({
style,
)}
{...props}
- onClick={handleClick}>
+ {...((isIconOnly && label !== '') || (isLoadingState && !isIconOnly)
+ ? {'aria-label': label}
+ : null)}
+ aria-busy={isLoadingState || undefined}
+ aria-disabled={useAriaDisabled || undefined}
+ onClick={handleClick}
+ {...(handleKeyDown ? {onKeyDown: handleKeyDown} : null)}>
{isLoadingState && (
- <span {...stylex.props(loadingStyles.spinnerOverlay)}>
+ <span
+ {...stylex.props(loadingStyles.spinnerOverlay)}
+ aria-hidden="true">
<XDSSpinner
size="sm"
shade={useLightSpinner ? 'onMedia' : 'default'}
/>
</span>
)}
- {icon}
- {children ?? (isIconOnly ? null : label)}
- {!isIconOnly && endSlot && (
- <span {...stylex.props(styles.endSlotWrapper)}>{endSlot}</span>
- )}
+ <span
+ {...stylex.props(styles.contentWrapper)}
+ aria-hidden={isLoadingState || undefined}>
+ {icon}
+ {children ?? (isIconOnly ? null : label)}
+ {!isIconOnly && endSlot && (
+ <span {...stylex.props(styles.endSlotWrapper)}>{endSlot}</span>
+ )}
+ </span>
+ {/* Live region for loading state announcements */}
+ <span
+ {...stylex.props(styles.visuallyHidden)}
+ role="status"
+ aria-live="polite">
+ {isLoadingState ? 'Loading' : ''}
+ </span>
</button>
);
diff --git a/packages/core/src/Layout/__tests__/edgeCompensation.test.tsx b/packages/core/src/Layout/__tests__/edgeCompensation.test.tsx
index 5fc8169542..8bdeef2ced 100644
--- a/packages/core/src/Layout/__tests__/edgeCompensation.test.tsx
+++ b/packages/core/src/Layout/__tests__/edgeCompensation.test.tsx
@@ -57,9 +57,10 @@ describe('Edge Compensation', () => {
describe('Banner edge signals', () => {
it('sets --container-padding-inline on the banner header', () => {
render(<XDSBanner status="info" title="Test" isDismissable />);
- // Banner renders with role="status" for info
- const banner = screen.getByRole('status');
- expect(banner).toBeInTheDocument();
+ // Banner renders with role="status" for info — use getAllByRole
+ // since the dismiss button's live region also has role="status"
+ const statuses = screen.getAllByRole('status');
+ expect(statuses.length).toBeGreaterThanOrEqual(1);
});
it('renders dismiss button without a wrapper div', () => {
diff --git a/packages/core/src/MoreMenu/XDSMoreMenu.test.tsx b/packages/core/src/MoreMenu/XDSMoreMenu.test.tsx
index 489552da37..c206b7e454 100644
--- a/packages/core/src/MoreMenu/XDSMoreMenu.test.tsx
+++ b/packages/core/src/MoreMenu/XDSMoreMenu.test.tsx
@@ -101,7 +101,9 @@ describe('XDSMoreMenu', () => {
it('supports disabled state', () => {
render(<XDSMoreMenu items={defaultItems} isDisabled />);
const button = screen.getByRole('button', {name: 'More options'});
- expect(button).toBeDisabled();
+ // MoreMenu uses tooltip when closed, so Button uses aria-disabled
+ // instead of native disabled to keep the button focusable for tooltip access
+ expect(button).toHaveAttribute('aria-disabled', 'true');
});
it('supports custom label', () => {