Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[useButton] Fix focusableWhenDisabled components #1313

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 10 additions & 14 deletions packages/react/src/collapsible/trigger/useCollapsibleTrigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,17 @@ export function useCollapsibleTrigger(

const getRootProps: useCollapsibleTrigger.ReturnValue['getRootProps'] = React.useCallback(
(externalProps: GenericHTMLProps = {}) =>
mergeReactProps(
externalProps,
mergeReactProps(
{
type: 'button',
'aria-controls': panelId,
'aria-expanded': open,
disabled,
onClick() {
setOpen(!open);
},
ref: handleRef,
getButtonProps(
mergeReactProps(externalProps, {
type: 'button',
'aria-controls': panelId,
'aria-expanded': open,
disabled,
onClick() {
setOpen(!open);
},
getButtonProps(),
),
ref: handleRef,
}),
),
[panelId, disabled, getButtonProps, handleRef, open, setOpen],
);
Expand Down
39 changes: 38 additions & 1 deletion packages/react/src/menu/item/MenuItem.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react';
import { expect } from 'chai';
import { spy } from 'sinon';
import { MemoryRouter, Route, Routes, Link, useLocation } from 'react-router-dom';
import { act, screen, waitFor } from '@mui/internal-test-utils';
import { act, fireEvent, screen, waitFor } from '@mui/internal-test-utils';
import { Menu } from '@base-ui-components/react/menu';
import { describeConformance, createRenderer, isJSDOM } from '#test-utils';

Expand Down Expand Up @@ -237,4 +237,41 @@ describe('<Menu.Item />', () => {
expect(locationDisplay).to.have.text('/');
});
});

describe('disabled state', () => {
it('can be focused but not interacted with when disabled', async () => {
const handleKeyDown = spy();
const handleClick = spy();

const { getByRole } = await render(
<Menu.Root open>
<Menu.Portal>
<Menu.Positioner>
<Menu.Popup>
<Menu.Item disabled onClick={handleClick} onKeyDown={handleKeyDown}>
Item
</Menu.Item>
</Menu.Popup>
</Menu.Positioner>
</Menu.Portal>
</Menu.Root>,
);

const item = getByRole('menuitem');
act(() => item.focus());
expect(item).toHaveFocus();

fireEvent.keyDown(item, { key: 'Enter' });
expect(handleKeyDown.callCount).to.equal(1);
expect(handleClick.callCount).to.equal(0);

fireEvent.keyDown(item, { key: 'Space' });
expect(handleKeyDown.callCount).to.equal(2);
expect(handleClick.callCount).to.equal(0);

fireEvent.click(item);
expect(handleKeyDown.callCount).to.equal(2);
expect(handleClick.callCount).to.equal(0);
});
});
});
8 changes: 3 additions & 5 deletions packages/react/src/menu/trigger/useMenuTrigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,8 @@ export function useMenuTrigger(parameters: useMenuTrigger.Parameters): useMenuTr

const getTriggerProps = React.useCallback(
(externalProps?: GenericHTMLProps): GenericHTMLProps => {
return mergeReactProps(
externalProps,
{
return getButtonProps(
mergeReactProps(externalProps, {
'aria-haspopup': 'menu' as const,
tabIndex: 0, // this is needed to make the button focused after click in Safari
ref: handleRef,
Expand Down Expand Up @@ -95,8 +94,7 @@ export function useMenuTrigger(parameters: useMenuTrigger.Parameters): useMenuTr

doc.addEventListener('mouseup', handleMouseUp, { once: true });
},
},
getButtonProps(),
}),
);
},
[getButtonProps, handleRef, open, setOpen, positionerRef, allowMouseUpTriggerRef],
Expand Down
25 changes: 24 additions & 1 deletion packages/react/src/select/item/SelectItem.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as React from 'react';
import { Select } from '@base-ui-components/react/select';
import { fireEvent, flushMicrotasks, screen, waitFor } from '@mui/internal-test-utils';
import { act, fireEvent, flushMicrotasks, screen, waitFor } from '@mui/internal-test-utils';
import { createRenderer, describeConformance, isJSDOM } from '#test-utils';
import { expect } from 'chai';

Expand Down Expand Up @@ -117,6 +117,29 @@ describe('<Select.Item />', () => {
});
});

it('should focus disabled items', async () => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that hovering over disabled options doesn't focus them (unlike menu items)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found that SelectItem inlines pointer-events: 'none' when disabled which causes this, is it safe to handle it in the handlers instead like this @atomiks ? 52838ad

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mj12albert yes, should be

await render(
<Select.Root open>
<Select.Trigger data-testid="trigger">
<Select.Value data-testid="value" />
</Select.Trigger>
<Select.Portal>
<Select.Positioner>
<Select.Popup>
<Select.Item value="two" disabled>
two
</Select.Item>
</Select.Popup>
</Select.Positioner>
</Select.Portal>
</Select.Root>,
);

const item = screen.getByText('two');
act(() => item.focus());
expect(item).toHaveFocus();
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Select should now follow Menu with useListNavigation's disabledIndices prop


it('should not select disabled item', async () => {
await render(
<Select.Root>
Expand Down
8 changes: 3 additions & 5 deletions packages/react/src/select/trigger/useSelectTrigger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,9 +73,8 @@ export function useSelectTrigger(

const getTriggerProps = React.useCallback(
(externalProps?: GenericHTMLProps): GenericHTMLProps => {
return mergeReactProps<'button'>(
fieldControlValidation.getValidationProps(externalProps),
{
return getButtonProps(
mergeReactProps<'button'>(fieldControlValidation.getValidationProps(externalProps), {
'aria-labelledby': labelId,
'aria-readonly': readOnly || undefined,
tabIndex: 0, // this is needed to make the button focused after click in Safari
Expand Down Expand Up @@ -138,8 +137,7 @@ export function useSelectTrigger(
doc.addEventListener('mouseup', handleMouseUp, { once: true });
});
},
},
getButtonProps(),
}),
);
},
[
Expand Down
51 changes: 49 additions & 2 deletions packages/react/src/use-button/useButton.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,59 @@ import { expect } from 'chai';
import { spy } from 'sinon';
import { act, fireEvent } from '@mui/internal-test-utils';
import { createRenderer, isJSDOM } from '#test-utils';
import { useButton } from '.';
import { useButton } from './useButton';

describe('useButton', () => {
const { render, renderToString } = createRenderer();

describe('tabIndex', () => {
describe('param: focusableWhenDisabled', () => {
it('allows disabled buttons to be focused', async () => {
function TestButton(props: React.ButtonHTMLAttributes<HTMLButtonElement>) {
const { disabled, ...otherProps } = props;
const { getButtonProps } = useButton({ disabled, focusableWhenDisabled: true });

return <button {...getButtonProps(otherProps)} />;
}
const { getByRole } = await render(<TestButton disabled />);
const button = getByRole('button');
act(() => button.focus());
mj12albert marked this conversation as resolved.
Show resolved Hide resolved
expect(button).toHaveFocus();
});

it('prevents interactions with the button', async () => {
const handleKeyDown = spy();
const handleClick = spy();

function TestButton(props: React.ButtonHTMLAttributes<HTMLButtonElement>) {
const { disabled, ...otherProps } = props;
const { getButtonProps } = useButton({ disabled, focusableWhenDisabled: true });

return <span {...getButtonProps(otherProps)} />;
}

const { getByRole } = await render(
<TestButton disabled onKeyDown={handleKeyDown} onClick={handleClick} />,
);
const button = getByRole('button');

act(() => button.focus());
expect(button).toHaveFocus();

fireEvent.keyDown(button, { key: 'Enter' });
expect(handleKeyDown.callCount).to.equal(1);
expect(handleClick.callCount).to.equal(0);

fireEvent.keyDown(button, { key: 'Space' });
mj12albert marked this conversation as resolved.
Show resolved Hide resolved
expect(handleKeyDown.callCount).to.equal(2);
expect(handleClick.callCount).to.equal(0);

fireEvent.click(button);
expect(handleKeyDown.callCount).to.equal(2);
expect(handleClick.callCount).to.equal(0);
});
});

describe('param: tabIndex', () => {
it('does not return tabIndex in getButtonProps when host component is BUTTON', async () => {
function TestButton() {
const { getButtonProps } = useButton();
Expand Down
18 changes: 14 additions & 4 deletions packages/react/src/use-button/useButton.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use client';
import * as React from 'react';
import { NOOP } from '../utils/noop';
import { useForkRef } from '../utils/useForkRef';
import { mergeReactProps } from '../utils/mergeReactProps';
import { useEventCallback } from '../utils/useEventCallback';
Expand Down Expand Up @@ -65,9 +66,18 @@ export function useButton(parameters: useButton.Parameters = {}): useButton.Retu
}, [disabled, elementName, focusableWhenDisabled, tabIndex]);

const getButtonProps = React.useCallback(
(externalProps: GenericButtonProps): GenericButtonProps => {
return mergeReactProps(externalProps, buttonProps, {
(externalProps: GenericButtonProps = {}): GenericButtonProps => {
const onClickProp = externalProps?.onClick ?? NOOP;

const otherExternalProps = { ...externalProps };
delete otherExternalProps.onClick;
return mergeReactProps(otherExternalProps, buttonProps, {
type,
onClick(event: React.MouseEvent) {
if (!disabled) {
onClickProp(event);
}
},
onKeyDown(event: React.KeyboardEvent) {
if (event.target === event.currentTarget && !isNativeButton() && event.key === ' ') {
event.preventDefault();
Expand All @@ -81,7 +91,7 @@ export function useButton(parameters: useButton.Parameters = {}): useButton.Retu
event.key === 'Enter' &&
!disabled
) {
externalProps?.onClick?.(event);
onClickProp(event);
event.preventDefault();
}
},
Expand All @@ -95,7 +105,7 @@ export function useButton(parameters: useButton.Parameters = {}): useButton.Retu
!disabled &&
event.key === ' '
) {
externalProps.onClick?.(event);
onClickProp(event);
}
},
ref: mergedRef,
Expand Down
Loading