Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/components/SegmentedControl/SegmentedControl.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export const Default: Story = {
),
},
],
controlLabel: "Segmented Control",
},
};

Expand Down Expand Up @@ -88,6 +89,7 @@ export const Dense: Story = {
),
},
],
controlLabel: "Segmented Control",
},
};
/**
Expand Down
216 changes: 216 additions & 0 deletions src/components/SegmentedControl/SegmentedControl.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,220 @@ describe("SegmentedControl", () => {
"content2",
);
});

it("uses a roving tab index", () => {
render(
<SegmentedControl
segments={[
{
label: "label1",
content: <p>content1</p>,
},
{
label: "label2",
content: <p>content2</p>,
},
{
label: "label3",
content: <p>content3</p>,
},
]}
/>,
);

expect(screen.getByRole("tab", { name: "label1" })).toHaveAttribute(
"tabindex",
"0",
);
expect(screen.getByRole("tab", { name: "label2" })).toHaveAttribute(
"tabindex",
"-1",
);
expect(screen.getByRole("tab", { name: "label3" })).toHaveAttribute(
"tabindex",
"-1",
);
});

it("moves focus and selection with arrow keys", async () => {
const user = userEvent.setup();

render(
<SegmentedControl
segments={[
{
label: "label1",
content: <p>content1</p>,
},
{
label: "label2",
content: <p>content2</p>,
},
{
label: "label3",
content: <p>content3</p>,
},
]}
/>,
);

const firstTab = screen.getByRole("tab", { name: "label1" });
const secondTab = screen.getByRole("tab", { name: "label2" });
const thirdTab = screen.getByRole("tab", { name: "label3" });

firstTab.focus();
await user.keyboard("{ArrowRight}");

expect(secondTab).toHaveFocus();
expect(secondTab).toHaveAttribute("aria-selected", "true");
expect(secondTab).toHaveAttribute("tabindex", "0");
expect(firstTab).toHaveAttribute("tabindex", "-1");
expect(screen.getByRole("tabpanel", { name: "label2" })).toHaveTextContent(
"content2",
);

await user.keyboard("{ArrowLeft}");

expect(firstTab).toHaveFocus();
expect(firstTab).toHaveAttribute("aria-selected", "true");

await user.keyboard("{ArrowLeft}");

expect(thirdTab).toHaveFocus();
expect(thirdTab).toHaveAttribute("aria-selected", "true");
});

it("moves focus to first and last segment with home and end keys", async () => {
const user = userEvent.setup();

render(
<SegmentedControl
segments={[
{
label: "label1",
content: <p>content1</p>,
},
{
label: "label2",
content: <p>content2</p>,
},
{
label: "label3",
content: <p>content3</p>,
},
]}
/>,
);

const firstTab = screen.getByRole("tab", { name: "label1" });
const thirdTab = screen.getByRole("tab", { name: "label3" });

firstTab.focus();
await user.keyboard("{ArrowRight}");
await user.keyboard("{End}");

expect(thirdTab).toHaveFocus();
expect(thirdTab).toHaveAttribute("aria-selected", "true");

await user.keyboard("{Home}");

expect(firstTab).toHaveFocus();
expect(firstTab).toHaveAttribute("aria-selected", "true");
});

it("moves focus into the active tabpanel on tab", async () => {
const user = userEvent.setup();

render(
<SegmentedControl
segments={[
{
label: "label1",
content: (
<div>
<button type="button">panel action one</button>
</div>
),
},
{
label: "label2",
content: (
<div>
<button type="button">panel action two</button>
</div>
),
},
]}
/>,
);

const firstTab = screen.getByRole("tab", { name: "label1" });

firstTab.focus();
await user.keyboard("{ArrowRight}");

await user.keyboard("{Tab}");

expect(screen.getByRole("tabpanel", { name: "label2" })).toHaveFocus();
});

it("allows tabbing from the active tabpanel into its interactive content", async () => {
const user = userEvent.setup();

render(
<SegmentedControl
segments={[
{
label: "label1",
content: (
<div>
<button type="button">panel action one</button>
</div>
),
},
{
label: "label2",
content: (
<div>
<button type="button">panel action two</button>
</div>
),
},
]}
/>,
);

const firstTab = screen.getByRole("tab", { name: "label1" });

firstTab.focus();
await user.keyboard("{ArrowRight}");
await user.keyboard("{Tab}");
await user.keyboard("{Tab}");

expect(
screen.getByRole("button", { name: "panel action two" }),
).toHaveFocus();
});

it("focuses the tabpanel when tabbing from a segment", async () => {
const user = userEvent.setup();

render(
<SegmentedControl
segments={[
{
label: "label1",
content: <p>content1</p>,
},
]}
/>,
);

const tab = screen.getByRole("tab", { name: "label1" });
tab.focus();

await user.keyboard("{Tab}");

expect(screen.getByRole("tabpanel", { name: "label1" })).toHaveFocus();
});
});
92 changes: 87 additions & 5 deletions src/components/SegmentedControl/SegmentedControl.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import classNames from "classnames";
import Icon, { ICONS } from "components/Icon";
import React, { ReactNode, useState } from "react";
import React, {
KeyboardEvent,
ReactNode,
useId,
useRef,
useState,
} from "react";
import type { ClassName, ValueOf } from "types";

export type Segments = {
Expand All @@ -23,11 +29,16 @@ export type Props = {
* Optional classes applied to the parent element.
*/
className?: ClassName;
/**
* Label for the segmented control for accessibility purposes.
*/
controlLabel?: string;
Comment thread
Stefan3002 marked this conversation as resolved.
Resolved
/**
* List of segments present in the element.
*/
segments: Segments[];
};

/**
* This is the [React](https://reactjs.org/) component for Vanilla [SegmentedControl](https://vanillaframework.io/docs/patterns/segmented-control).
SegmentedControl organises and allows navigation between groups of content that are related and at the same level
Expand All @@ -36,20 +47,85 @@ of hierarchy.
const SegmentedControl = ({
className,
segments,
controlLabel = "Segmented Control",
}: Props): React.JSX.Element => {
const [activeIndex, setActiveIndex] = useState<number>(0);
const tabRefs = useRef<Array<HTMLButtonElement | null>>([]);
const panelRef = useRef<HTMLDivElement | null>(null);
const id = useId();

const focusSegment = (index: number) => {
setActiveIndex(index);
tabRefs.current[index]?.focus();
};

const focusPanelContent = () => {
const panel = panelRef.current;
if (!panel) {
return;
}

panel.focus();
};

const handleSegmentKeyDown = (
event: KeyboardEvent<HTMLButtonElement>,
index: number,
) => {
switch (event.key) {
case "ArrowRight":
event.preventDefault();
focusSegment((index + 1) % segments.length);
break;
case "ArrowLeft":
event.preventDefault();
focusSegment((index - 1 + segments.length) % segments.length);
break;
case "Home":
event.preventDefault();
focusSegment(0);
break;
case "End":
event.preventDefault();
focusSegment(segments.length - 1);
break;
case "Tab":
if (!event.shiftKey) {
event.preventDefault();
focusPanelContent();
}
break;
default:
break;
}
};

const activeSegment = segments[activeIndex];
const panelId = `${id}-panel`;

return (
<div className={classNames("p-segmented-control", className)}>
<div className={classNames("p-segmented-control__list")} role="tablist">
<div
className={classNames("p-segmented-control__list")}
aria-label={controlLabel}
Comment thread
Stefan3002 marked this conversation as resolved.
Resolved
role="tablist"
>
{segments.map((segment, i) => {
const tabId = `${id}-tab-${i}`;
return (
<button
aria-selected={activeIndex === i}
aria-controls={panelId}
className={classNames("p-segmented-control__button")}
role="tab"
key={segment.label}
id={segment.label}
id={tabId}
onClick={() => setActiveIndex(i)}
onKeyDown={(event) => handleSegmentKeyDown(event, i)}
ref={(element) => {
tabRefs.current[i] = element;
}}
tabIndex={activeIndex === i ? 0 : -1}
>
{segment.iconName ? (
<>
Expand All @@ -63,8 +139,14 @@ const SegmentedControl = ({
);
})}
</div>
<div role="tabpanel" aria-labelledby={segments[activeIndex].label}>
{segments[activeIndex].content}
<div
aria-labelledby={`${id}-tab-${activeIndex}`}
id={panelId}
ref={panelRef}
role="tabpanel"
tabIndex={0}
>
{activeSegment.content}
</div>
</div>
);
Expand Down
Loading
Loading