Skip to content

Commit

Permalink
feat(DropdownToggle): only add aria-haspopup, when approriate
Browse files Browse the repository at this point in the history
  • Loading branch information
jquense committed Jul 14, 2021
1 parent 1ff2841 commit 84e5450
Show file tree
Hide file tree
Showing 3 changed files with 149 additions and 146 deletions.
5 changes: 2 additions & 3 deletions src/Dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import DropdownMenu, {
import DropdownToggle, {
DropdownToggleProps,
UseDropdownToggleMetadata,
isRoleMenu,
} from './DropdownToggle';
import DropdownItem, { DropdownItemProps } from './DropdownItem';
import SelectableContext from './SelectableContext';
Expand Down Expand Up @@ -224,9 +225,7 @@ function Dropdown({

if (focusType == null) {
focusType =
menuRef.current && matches(menuRef.current, '[role=menu]')
? 'keyboard'
: false;
menuRef.current && isRoleMenu(menuRef.current) ? 'keyboard' : false;
}

if (
Expand Down
33 changes: 21 additions & 12 deletions src/DropdownToggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,17 @@ import { useSSRSafeId } from '@react-aria/ssr';
import { useContext, useCallback } from 'react';
import * as React from 'react';
import DropdownContext, { DropdownContextValue } from './DropdownContext';
import useIsomorphicEffect from '@restart/hooks/useIsomorphicEffect';

export const isRoleMenu = (el: HTMLElement) =>
el.getAttribute('role')?.toLowerCase() == 'menu';

export interface UseDropdownToggleProps {
id: string;
ref: DropdownContextValue['setToggle'];
onClick: React.MouseEventHandler;
'aria-haspopup': boolean;
'aria-expanded': boolean;
'aria-haspopup'?: true;
}

export interface UseDropdownToggleMetadata {
Expand All @@ -31,7 +35,7 @@ export function useDropdownToggle(): [
UseDropdownToggleMetadata,
] {
const id = useSSRSafeId();
const { show = false, toggle = noop, setToggle } =
const { show = false, toggle = noop, setToggle, menuElement } =
useContext(DropdownContext) || {};
const handleClick = useCallback(
(e) => {
Expand All @@ -40,16 +44,21 @@ export function useDropdownToggle(): [
[show, toggle],
);

return [
{
id,
ref: setToggle || noop,
onClick: handleClick,
'aria-haspopup': true,
'aria-expanded': !!show,
},
{ show, toggle },
];
const props: UseDropdownToggleProps = {
id,
ref: setToggle || noop,
onClick: handleClick,
'aria-expanded': !!show,
};

// This is maybe better down in an effect, but
// the component is going to update anyway when the menu element
// is set so might return new props.
if (menuElement && isRoleMenu(menuElement)) {
props['aria-haspopup'] = true;
}

return [props, { show, toggle }];
}

const propTypes = {
Expand Down
Loading

0 comments on commit 84e5450

Please sign in to comment.