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

Доступность для компонентов Tabs и TabsItem #3337

Merged
merged 9 commits into from
Oct 7, 2022
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
1 change: 0 additions & 1 deletion src/components/FocusTrap/FocusTrap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { HasComponent, HasRootRef } from "../../types";
import { AppRootContext } from "../AppRoot/AppRootContext";

const FOCUSABLE_ELEMENTS: string = FOCUSABLE_ELEMENTS_LIST.join();

export interface FocusTrapProps
extends React.AllHTMLAttributes<HTMLElement>,
HasRootRef<HTMLElement>,
Expand Down
19 changes: 19 additions & 0 deletions src/components/Group/Group.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Spacing } from "../Spacing/Spacing";
import { Separator } from "../Separator/Separator";
import { hasReactNode } from "../../lib/utils";
import { Caption } from "../Typography/Caption/Caption";
import { warnOnce } from "../../lib/warnOnce";
import {
withAdaptivity,
AdaptivityProps,
Expand Down Expand Up @@ -41,6 +42,8 @@ export interface GroupProps
children?: React.ReactNode;
}

const warn = warnOnce("TabsItem");

const GroupComponent = ({
header,
description,
Expand All @@ -50,6 +53,7 @@ const GroupComponent = ({
mode,
padding = "m",
sizeX,
tabIndex: tabIndexProp,
...restProps
}: GroupProps) => {
const { isInsideModal } = React.useContext(ModalRootContext);
Expand All @@ -62,6 +66,20 @@ const GroupComponent = ({
sizeX === SizeType.COMPACT || isInsideModal ? "plain" : "card";
}

const isTabPanel = restProps.role === "tabpanel";

if (
process.env.NODE_ENV === "development" &&
isTabPanel &&
(!restProps["aria-controls"] || !restProps["id"])
) {
warn(
'При использовании роли "tabpanel" необходимо задать значение свойств "aria-controls" и "id"'
);
}

const tabIndex = isTabPanel && tabIndexProp === undefined ? 0 : tabIndexProp;

let separatorElement = null;

if (separator !== "hide") {
Expand All @@ -80,6 +98,7 @@ const GroupComponent = ({
return (
<section
{...restProps}
tabIndex={tabIndex}
ref={getRootRef}
vkuiClass={classNames(
"Group",
Expand Down
37 changes: 34 additions & 3 deletions src/components/Tabs/Readme.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## Доступность

Для корректной работы скринридеров необходимо вручную передавать некоторые параметры:
<br />

- В компонент вкладки (`TabsItem`) нужно передать `id` и `aria-controls`, указывающий на id области с его контентом. <br />
- В область контента необходимо передать параметры `id`, `tabIndex = 0` и `aria-labelledby`, ссылающийся на компонент таба

```jsx
const Example = ({ sizeX }) => {
const [mode, setMode] = React.useState("all");
Expand All @@ -22,13 +30,34 @@ const Example = ({ sizeX }) => {
separator={sizeX === SizeType.REGULAR}
>
<DefaultInPanel
selected={selected}
setSelected={setSelected}
menuOpened={menuOpened}
onMenuClick={(opened) => {
setMenuOpened((prevState) => (opened ? !prevState : false));
}}
/>
</PanelHeader>

{selected === "news" && (
<Group
id="tab-content-news"
aria-labelledby="tab-news"
role="tabpanel"
>
<Div>Контент новостей</Div>
</Group>
)}
{selected === "recommendations" && (
<Group
id="tab-content-recommendations"
aria-labelledby="tab-recommendations"
role="tabpanel"
>
<Div>Контент рекомендаций</Div>
</Group>
)}

<Scrollable />

<PanelHeaderContext
Expand Down Expand Up @@ -65,9 +94,7 @@ const Example = ({ sizeX }) => {
);
};

const DefaultInPanel = ({ menuOpened, onMenuClick }) => {
const [selected, setSelected] = React.useState("news");

const DefaultInPanel = ({ menuOpened, onMenuClick, selected, setSelected }) => {
return (
<Tabs>
<TabsItem
Expand All @@ -85,6 +112,8 @@ const DefaultInPanel = ({ menuOpened, onMenuClick }) => {
}
setSelected("news");
}}
id="tab-news"
aria-controls="tab-content-news"
>
Новости
</TabsItem>
Expand All @@ -94,6 +123,8 @@ const DefaultInPanel = ({ menuOpened, onMenuClick }) => {
onMenuClick(false);
setSelected("recommendations");
}}
id="tab-recommendations"
aria-controls="tab-content-recommendations"
>
Интересное
</TabsItem>
Expand Down
184 changes: 184 additions & 0 deletions src/components/Tabs/Tabs.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,190 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { TabsItem } from "../TabsItem/TabsItem";
import { baselineComponent } from "../../testing/utils";
import { Tabs } from "./Tabs";
import { Group } from "../Group/Group";
import { ComponentProps, useState } from "react";

function TestTabs(props: { disabledKeys?: string[] }) {
const [currentTab, setCurrentTab] = useState("first");

return (
<div>
<Tabs>
<TabsItem
id="tab-first"
data-testid="first"
selected={currentTab === "first"}
onClick={() => setCurrentTab("first")}
aria-controls="tab-content-first"
disabled={props.disabledKeys?.includes("first")}
>
First
</TabsItem>
<TabsItem
id="tab-second"
data-testid="second"
aria-controls="tab-content-second"
onClick={() => setCurrentTab("second")}
selected={currentTab === "second"}
disabled={props.disabledKeys?.includes("second")}
>
Second
</TabsItem>
<TabsItem
id="tab-third"
data-testid="third"
aria-controls="tab-content-third"
onClick={() => setCurrentTab("third")}
selected={currentTab === "third"}
disabled={props.disabledKeys?.includes("third")}
>
Third
</TabsItem>
</Tabs>
{currentTab === "first" && (
<Group
role="tabpanel"
data-testid="content-first"
id="tab-content-first"
aria-labelledby="tab-first"
></Group>
)}
{currentTab === "second" && (
<Group
role="tabpanel"
data-testid="content-second"
id="tab-content-second"
aria-labelledby="tab-second"
></Group>
)}
{currentTab === "third" && (
<Group
role="tabpanel"
data-testid="content-third"
id="tab-content-third"
aria-labelledby="tab-third"
></Group>
)}
</div>
);
}

function isTabSelected(el: HTMLElement) {
return el.getAttribute("aria-selected") === "true";
}

function isTabFocused(el: HTMLElement) {
return document.activeElement === el;
}

function renderTestTabs(props: ComponentProps<typeof TestTabs> = {}) {
render(<TestTabs {...props} />);
screen.getByTestId("first").focus();
screen.getByTestId("first").click();
}

function pressKey(key: string) {
if (!document.activeElement) {
return;
}

fireEvent.keyDown(document.activeElement, {
key,
});
}

describe("Tabs", () => {
baselineComponent(Tabs);

describe("Mouse handlers", () => {
it("select element on click", () => {
renderTestTabs();

fireEvent.click(screen.getByTestId("third"));

expect(isTabSelected(screen.getByTestId("third"))).toBeTruthy();
});
it("doesn't select disabled element on click", () => {
renderTestTabs({ disabledKeys: ["third"] });

fireEvent.click(screen.getByTestId("third"));

expect(isTabSelected(screen.getByTestId("third"))).toBeFalsy();
});
});

describe("Keyboard handlers", () => {
it("doesn't focus previous element when first focused", () => {
renderTestTabs();
screen.getByTestId("first").focus();
pressKey("ArrowLeft");
expect(isTabFocused(screen.getByTestId("first"))).toBeTruthy();
});
it("doesn't focus next element when last focused", () => {
renderTestTabs();
screen.getByTestId("third").focus();
pressKey("ArrowRight");
expect(isTabFocused(screen.getByTestId("third"))).toBeTruthy();
});
it("focus next element with ArrowRight key", () => {
renderTestTabs();
screen.getByTestId("second").focus();
pressKey("ArrowRight");
expect(isTabFocused(screen.getByTestId("third"))).toBeTruthy();
});
it("focus previuos element with ArrowLeft key", () => {
renderTestTabs();
screen.getByTestId("second").focus();
pressKey("ArrowLeft");
expect(isTabFocused(screen.getByTestId("first"))).toBeTruthy();
});
it("focus first element with Home key", () => {
renderTestTabs();
screen.getByTestId("third").focus();
pressKey("Home");
expect(isTabFocused(screen.getByTestId("first"))).toBeTruthy();
});
it("focus last element with End key", () => {
renderTestTabs();
screen.getByTestId("first").focus();
pressKey("End");
expect(isTabFocused(screen.getByTestId("third"))).toBeTruthy();
});
it("select element with Space key", () => {
renderTestTabs();
screen.getByTestId("first").focus();
pressKey("ArrowRight");
pressKey("Space");
expect(isTabFocused(screen.getByTestId("second"))).toBeTruthy();
expect(isTabSelected(screen.getByTestId("second"))).toBeTruthy();
});
it("select element with Enter key", () => {
renderTestTabs();
screen.getByTestId("first").focus();
pressKey("ArrowRight");
pressKey("Enter");
expect(isTabFocused(screen.getByTestId("second"))).toBeTruthy();
expect(isTabSelected(screen.getByTestId("second"))).toBeTruthy();
});
it("skip disabled elements", () => {
renderTestTabs({ disabledKeys: ["second"] });
screen.getByTestId("first").focus();
pressKey("ArrowRight");
pressKey("Enter");
expect(isTabFocused(screen.getByTestId("third"))).toBeTruthy();
expect(isTabSelected(screen.getByTestId("second"))).toBeFalsy();
expect(isTabSelected(screen.getByTestId("third"))).toBeTruthy();
});
it("focus content with Down key", () => {
renderTestTabs();
screen.getByTestId("second").focus();
pressKey("Enter");
pressKey("ArrowDown");
expect(isTabSelected(screen.getByTestId("second"))).toBeTruthy();
expect(document.activeElement).toEqual(
screen.getByTestId("content-second")
);
});
});
});
Loading