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

feat(SegmentedControl): menu role option #7141

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
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 @@ -67,13 +67,18 @@ export interface SegmentedControlProps
options: Array<OptionProps<string>>;

/**
* Aria role for the overall component. Child buttons get appropriate roles.
* Aria role for the overall component (container).
* Child buttons get appropriate roles:
* - "radiogroup" -> "radio"
* - "group" -> "button"
* - "toolbar" -> "button"
* - "menu" -> "menuitemradio"
*
* @see https://www.w3.org/WAI/ARIA/apg/patterns/toolbar/examples/toolbar
*
* @default 'radiogroup'
*/
role?: Extract<React.AriaRole, "radiogroup" | "group" | "toolbar">;
role?: Extract<React.AriaRole, "radiogroup" | "group" | "toolbar" | "menu">;

/**
* Whether this control should use small buttons.
Expand Down Expand Up @@ -119,7 +124,7 @@ export const SegmentedControl: React.FC<SegmentedControlProps> = React.forwardRe

const handleKeyDown = React.useCallback(
(e: React.KeyboardEvent<HTMLDivElement>) => {
if (role === "radiogroup") {
if (role === "radiogroup" || role === "menu") {
// in a `radiogroup`, arrow keys select next item, not tab key.
const direction = Utils.getArrowKeyDirection(e, ["ArrowLeft", "ArrowUp"], ["ArrowRight", "ArrowDown"]);
const outerElement = outerRef.current;
Expand Down Expand Up @@ -153,6 +158,14 @@ export const SegmentedControl: React.FC<SegmentedControlProps> = React.forwardRe
});

const isAnySelected = options.some(option => selectedValue === option.value);
const buttonRole = (
{
radiogroup: "radio",
menu: "menuitemradio",
group: undefined,
toolbar: undefined,
} satisfies Record<typeof role, React.AriaRole | undefined>
)[role];

return (
<div
Expand All @@ -173,10 +186,10 @@ export const SegmentedControl: React.FC<SegmentedControlProps> = React.forwardRe
large={large}
onClick={handleOptionClick}
small={small}
{...(role === "radiogroup"
role={buttonRole}
{...(role === "radiogroup" || role === "menu"
? {
"aria-checked": isSelected,
role: "radio",
// "roving tabIndex" on a radiogroup: https://www.w3.org/WAI/ARIA/apg/practices/keyboard-interface/#kbd_roving_tabindex
// `!isAnySelected` accounts for case where no value is currently selected
// (passed value/defaultValue is not one of the values of the passed options.)
Expand Down