Skip to content

fix: improved accessibility of dropdown #954

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

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,8 @@ exports[`Accordion Accordion renders custom content and its buttons are clickabl
>
<li
class="list-item"
role="option"
tabindex="0"
>
<button
aria-disabled="false"
Expand All @@ -590,6 +592,8 @@ exports[`Accordion Accordion renders custom content and its buttons are clickabl
</li>
<li
class="list-item"
role="option"
tabindex="-1"
>
<button
aria-disabled="false"
Expand Down
182 changes: 121 additions & 61 deletions src/components/Dropdown/Dropdown.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react';
import React, { useState, useRef } from 'react';
import { Stories } from '@storybook/addon-docs';
import { ComponentStory, ComponentMeta } from '@storybook/react';
import {
Expand Down Expand Up @@ -123,21 +123,38 @@ const Overlay = () => (
<List<User>
items={sampleList}
renderItem={(item) => (
<Button
alignText={ButtonTextAlign.Left}
buttonWidth={ButtonWidth.fill}
iconProps={{
path: item.icon,
}}
role="listitem"
<div
className="dropdown-item"
role="option"
tabIndex={-1}
style={{
display: 'flex',
alignItems: 'center',
padding: '8px 12px',
margin: '4px 0',
cursor: 'pointer',
width: '100%',
gap: '8px',
}}
text={item.name}
variant={ButtonVariant.Default}
/>
>
<span
aria-hidden="true"
className="icon-wrapper_fkuzpfU"
role="presentation"
>
<Icon path={item.icon} size="20px" role="presentation" />
</span>
<span>{item.name}</span>
</div>
)}
role="list"
role="listbox"
className="list-container vertical"
itemProps={{
role: 'option',
'aria-selected': 'false',
className: 'list-item',
}}
layout="vertical"
/>
);

Expand All @@ -146,19 +163,29 @@ const OverlayWithAdditionalListItem = () => (
additionalItem={sampleAdditionalItem}
items={sampleList}
renderItem={(item) => (
<Button
alignText={ButtonTextAlign.Left}
buttonWidth={ButtonWidth.fill}
iconProps={{
path: item.icon,
}}
role="listitem"
<div
className="dropdown-item"
role="option"
tabIndex={-1}
style={{
display: 'flex',
alignItems: 'center',
padding: '8px 12px',
margin: '4px 0',
cursor: 'pointer',
width: '100%',
gap: '8px',
}}
text={item.name}
variant={ButtonVariant.Default}
/>
>
<span
aria-hidden="true"
className="icon-wrapper_fkuzpfU"
role="presentation"
>
<Icon path={item.icon} size="20px" role="presentation" />
</span>
<span>{item.name}</span>
</div>
)}
renderAdditionalItem={(item) => (
<Button
Expand All @@ -175,7 +202,14 @@ const OverlayWithAdditionalListItem = () => (
variant={ButtonVariant.Secondary}
/>
)}
role="list"
role="listbox"
className="list-container vertical"
itemProps={{
role: 'option',
'aria-selected': 'false',
className: 'list-item',
}}
layout="vertical"
/>
);

Expand Down Expand Up @@ -268,28 +302,28 @@ const Dropdown_External_Story: ComponentStory<typeof Dropdown> = (args) => {
};

const Dropdown_Advanced_Story: ComponentStory<typeof Dropdown> = (args) => {
const [checkedItems, setCheckedItems] = useState({});
const [checkedItems, setCheckedItems] = useState<{
[key: string]: {
[itemName: string]: boolean;
};
}>({
'filter one': {},
'filter two': {},
'filter three': {},
});
const [visibleQuickFilter, setVisibleQuickFilter] = useState<{
[x: string]: boolean;
}>({});
const currentDropdown = Object.keys(visibleQuickFilter)?.[0] || '';

useEffect(() => {
if (currentDropdown) {
console.log('Dropdown is: ' + currentDropdown);
} else {
setCheckedItems({});
console.log('checkedItems cleared');
}
}, [currentDropdown]);

useEffect(() => {
console.log('checkedItems: ', checkedItems);

if (checkedItems) {
setVisibleQuickFilter({});
}
}, [checkedItems]);
const checkboxRefs = useRef<{
[filterName: string]: {
[itemName: string]: HTMLInputElement | null;
};
}>({
'filter one': {},
'filter two': {},
'filter three': {},
});

const toggleQuickFilterVisibility = ({
key,
Expand All @@ -316,40 +350,64 @@ const Dropdown_Advanced_Story: ComponentStory<typeof Dropdown> = (args) => {
},
];

const handleChange = (event: { target: { value: any; checked: any } }) => {
setCheckedItems({
...checkedItems,
[event.target.value]: event.target.checked,
});
const handleChange = (
event: React.ChangeEvent<HTMLInputElement>,
filterName: string
) => {
const { value, checked } = event.target;
setCheckedItems((prevState) => ({
...prevState,
[filterName]: {
...prevState[filterName],
[value]: checked,
},
}));
};

const Overlay = () => (
const Overlay = (filterName: string) => (
<List
items={sampleList}
itemProps={{ role: 'listitem' }}
itemProps={{
role: 'option',
'aria-selected': 'false',
className: 'list-item',
}}
itemStyle={{
margin: '4px 0',
}}
renderItem={(item) => (
<CheckBox
checked={(checkedItems as any)?.[item.name]}
label={item.name}
onChange={handleChange}
role="listitem"
value={item.name}
/>
)}
role="list"
renderItem={(item) => {
const isChecked = !!checkedItems[filterName]?.[item.name];
return (
<CheckBox
checked={isChecked}
label={item.name}
onChange={(e) => handleChange(e, filterName)}
role="listitem"
value={item.name}
ref={(el) => {
if (el) {
const inputEl = el.querySelector('input[type="checkbox"]');
checkboxRefs.current[filterName][item.name] =
inputEl as HTMLInputElement;
}
}}
/>
);
}}
role="listbox"
className="list-container vertical"
layout="vertical"
/>
);

return (
<Stack direction="horizontal" flexGap="l">
<Dropdown
{...args}
overlay={Overlay()}
overlay={Overlay('filter one')}
closeOnDropdownClick={false}
closeOnOutsideClick={false}
closeOnElementClick={false}
onVisibleChange={(visible) => {
toggleQuickFilterVisibility({
key: 'filter one',
Expand All @@ -373,9 +431,10 @@ const Dropdown_Advanced_Story: ComponentStory<typeof Dropdown> = (args) => {
</Dropdown>
<Dropdown
{...args}
overlay={Overlay()}
overlay={Overlay('filter two')}
closeOnDropdownClick={false}
closeOnOutsideClick={false}
closeOnElementClick={false}
onVisibleChange={(visible) => {
toggleQuickFilterVisibility({
key: 'filter two',
Expand All @@ -399,9 +458,10 @@ const Dropdown_Advanced_Story: ComponentStory<typeof Dropdown> = (args) => {
</Dropdown>
<Dropdown
{...args}
overlay={Overlay()}
overlay={Overlay('filter three')}
closeOnDropdownClick={false}
closeOnOutsideClick={false}
closeOnElementClick={false}
onVisibleChange={(visible) => {
toggleQuickFilterVisibility({
key: 'filter three',
Expand Down
85 changes: 82 additions & 3 deletions src/components/Dropdown/Dropdown.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -518,9 +518,13 @@ describe('Dropdown', () => {
});
await waitFor(() => screen.getByTestId('User profile 1'));
await waitFor(() =>
expect(screen.getByTestId('User profile 1').matches(':focus')).toBe(true)
expect(
screen.getByTestId('User profile 1').closest('li')?.matches(':focus')
).toBe(true)
);
expect(screen.getByTestId('User profile 1').matches(':focus')).toBe(true);
expect(
screen.getByTestId('User profile 1').closest('li')?.matches(':focus')
).toBe(true);
});

test('Focuses the reference element when not visible', async () => {
Expand All @@ -544,6 +548,79 @@ describe('Dropdown', () => {
expect(referenceElement).toHaveFocus();
});

test('Should not close dropdown when clicking on list item content with closeOnElementClick=false', async () => {
// Create a test component with closeOnElementClick set to false
const CloseOnElementClickTestComponent = (): JSX.Element => {
const [visible, setVisibility] = useState(false);
return (
<Dropdown
{...dropdownProps}
closeOnElementClick={false}
onVisibleChange={(isVisible) => setVisibility(isVisible)}
>
<Button
alignIcon={ButtonIconAlign.Right}
text={'Dropdown menu test'}
iconProps={{
path: IconName.mdiChevronDown,
rotate: visible ? 180 : 0,
}}
data-testid="dropdown-reference"
/>
</Dropdown>
);
};

const { container } = render(<CloseOnElementClickTestComponent />);
const referenceElement = screen.getByTestId('dropdown-reference');

// Open the dropdown
act(() => {
userEvent.click(referenceElement);
});

// Wait for dropdown to be visible
await waitFor(() => screen.getByText('User profile 1'));

// Click on a button inside a list item (not the list item itself)
const listItemButton = screen.getByTestId('User profile 1');
act(() => {
userEvent.click(listItemButton);
});

// Dropdown should still be open
await waitFor(() => {
expect(referenceElement.getAttribute('aria-expanded')).toBe('true');
expect(screen.getByText('User profile 1')).toBeInTheDocument();
});
});

test('Should close dropdown when clicking on list item content with closeOnElementClick=true', async () => {
// Create a test component with closeOnElementClick set to true (default)
const { container } = render(<DropdownComponent />);
const referenceElement = screen.getByTestId('dropdown-reference');

// Open the dropdown
act(() => {
userEvent.click(referenceElement);
});

// Wait for dropdown to be visible
await waitFor(() => screen.getByText('User profile 1'));

// Click on a button inside a list item
const listItemButton = screen.getByTestId('User profile 1');
act(() => {
userEvent.click(listItemButton);
});

// Dropdown should close
await waitFor(() => {
expect(referenceElement.getAttribute('aria-expanded')).toBe('false');
expect(screen.queryByText('User profile 1')).not.toBeInTheDocument();
});
});

test('Allows tabbing into submenu after click', async () => {
const mockEventKeys = {
TAB: 'Tab',
Expand All @@ -561,7 +638,9 @@ describe('Dropdown', () => {

// Verify first menu item is focused
await waitFor(() =>
expect(screen.getByTestId('User profile 1').matches(':focus')).toBe(true)
expect(
screen.getByTestId('User profile 1').closest('li')?.matches(':focus')
).toBe(true)
);

// Tab to second menu item
Expand Down
Loading