Improve Forward Dialog a11y by switching to roving tab index interactions (#12306)

* Improve Forward Dialog a11y by switching to roving tab index interactions

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Improve screen reader readout

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Improve screen reader readout

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

* Add tests

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>

---------

Signed-off-by: Michael Telatynski <7t3chguy@gmail.com>
pull/28217/head
Michael Telatynski 2024-03-08 14:45:15 +00:00 committed by GitHub
parent e807457276
commit 8e68d5d6be
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 235 additions and 44 deletions

View File

@ -96,7 +96,8 @@ limitations under the License.
padding: 6px;
border-radius: 8px;
&:hover {
&:hover,
&.mx_ForwardList_entry_active {
background-color: $spacePanel-bg-color;
}

View File

@ -175,6 +175,8 @@ interface IProps {
handleHomeEnd?: boolean;
handleUpDown?: boolean;
handleLeftRight?: boolean;
handleInputFields?: boolean;
scrollIntoView?: boolean | ScrollIntoViewOptions;
children(renderProps: { onKeyDownHandler(ev: React.KeyboardEvent): void; onDragEndHandler(): void }): ReactNode;
onKeyDown?(ev: React.KeyboardEvent, state: IState, dispatch: Dispatch<IAction>): void;
}
@ -212,6 +214,8 @@ export const RovingTabIndexProvider: React.FC<IProps> = ({
handleUpDown,
handleLeftRight,
handleLoop,
handleInputFields,
scrollIntoView,
onKeyDown,
}) => {
const [state, dispatch] = useReducer<Reducer<IState, Action>>(reducer, {
@ -234,7 +238,7 @@ export const RovingTabIndexProvider: React.FC<IProps> = ({
let focusRef: RefObject<HTMLElement> | undefined;
// Don't interfere with input default keydown behaviour
// but allow people to move focus from it with Tab.
if (checkInputableElement(ev.target as HTMLElement)) {
if (!handleInputFields && checkInputableElement(ev.target as HTMLElement)) {
switch (action) {
case KeyBindingAction.Tab:
handled = true;
@ -311,9 +315,21 @@ export const RovingTabIndexProvider: React.FC<IProps> = ({
ref: focusRef,
},
});
if (scrollIntoView) {
focusRef.current?.scrollIntoView(scrollIntoView);
}
}
},
[context, onKeyDown, handleHomeEnd, handleUpDown, handleLeftRight, handleLoop],
[
context,
onKeyDown,
handleHomeEnd,
handleUpDown,
handleLeftRight,
handleLoop,
handleInputFields,
scrollIntoView,
],
);
const onDragEndHandler = useCallback(() => {

View File

@ -57,6 +57,15 @@ import { isLocationEvent } from "../../../utils/EventUtils";
import { isSelfLocation, locationEventGeoUri } from "../../../utils/location";
import { RoomContextDetails } from "../rooms/RoomContextDetails";
import { filterBoolean } from "../../../utils/arrays";
import {
IState,
RovingTabIndexContext,
RovingTabIndexProvider,
Type,
useRovingTabIndex,
} from "../../../accessibility/RovingTabIndex";
import { getKeyBindingsManager } from "../../../KeyBindingsManager";
import { KeyBindingAction } from "../../../accessibility/KeyboardShortcuts";
const AVATAR_SIZE = 30;
@ -87,6 +96,7 @@ enum SendState {
const Entry: React.FC<IEntryProps> = ({ room, type, content, matrixClient: cli, onFinished }) => {
const [sendState, setSendState] = useState<SendState>(SendState.CanSend);
const [onFocus, isActive, ref] = useRovingTabIndex<HTMLDivElement>();
const jumpToRoom = (ev: ButtonEvent): void => {
dis.dispatch<ViewRoomPayload>({
@ -134,16 +144,30 @@ const Entry: React.FC<IEntryProps> = ({ room, type, content, matrixClient: cli,
icon = <NotificationBadge notification={StaticNotificationState.RED_EXCLAMATION} />;
}
const id = `mx_ForwardDialog_entry_${room.roomId}`;
return (
<div className="mx_ForwardList_entry">
<div
className={classnames("mx_ForwardList_entry", {
mx_ForwardList_entry_active: isActive,
})}
aria-labelledby={`${id}_name`}
aria-describedby={`${id}_send`}
role="listitem"
ref={ref}
onFocus={onFocus}
id={id}
>
<AccessibleTooltipButton
className="mx_ForwardList_roomButton"
onClick={jumpToRoom}
title={_t("forward|open_room")}
alignment={Alignment.Top}
tabIndex={isActive ? 0 : -1}
>
<DecoratedRoomAvatar room={room} size="32px" />
<span className="mx_ForwardList_entry_name">{room.name}</span>
<DecoratedRoomAvatar room={room} size="32px" tooltipProps={{ tabIndex: isActive ? 0 : -1 }} />
<span className="mx_ForwardList_entry_name" id={`${id}_name`}>
{room.name}
</span>
<RoomContextDetails component="span" className="mx_ForwardList_entry_detail" room={room} />
</AccessibleTooltipButton>
<AccessibleTooltipButton
@ -153,6 +177,8 @@ const Entry: React.FC<IEntryProps> = ({ room, type, content, matrixClient: cli,
disabled={disabled}
title={title}
alignment={Alignment.Top}
tabIndex={isActive ? 0 : -1}
id={`${id}_send`}
>
<div className="mx_ForwardList_sendLabel">{_t("forward|send_label")}</div>
{icon}
@ -270,6 +296,26 @@ const ForwardDialog: React.FC<IProps> = ({ matrixClient: cli, event, permalinkCr
);
}
const onKeyDown = (ev: React.KeyboardEvent, state: IState): void => {
let handled = true;
const action = getKeyBindingsManager().getAccessibilityAction(ev);
switch (action) {
case KeyBindingAction.Enter: {
state.activeRef?.current?.querySelector<HTMLButtonElement>(".mx_ForwardList_sendButton")?.click();
break;
}
default:
handled = false;
}
if (handled) {
ev.preventDefault();
ev.stopPropagation();
}
};
return (
<BaseDialog
title={_t("common|forward_message")}
@ -293,42 +339,73 @@ const ForwardDialog: React.FC<IProps> = ({ matrixClient: cli, event, permalinkCr
/>
</div>
<hr />
<div className="mx_ForwardList" id="mx_ForwardList">
<SearchBox
className="mx_textinput_icon mx_textinput_search"
placeholder={_t("forward|filter_placeholder")}
onSearch={setQuery}
autoFocus={true}
/>
<AutoHideScrollbar className="mx_ForwardList_content">
{rooms.length > 0 ? (
<div className="mx_ForwardList_results">
<TruncatedList
className="mx_ForwardList_resultsList"
truncateAt={truncateAt}
createOverflowElement={overflowTile}
getChildren={(start, end) =>
rooms
.slice(start, end)
.map((room) => (
<Entry
key={room.roomId}
room={room}
type={type}
content={content}
matrixClient={cli}
onFinished={onFinished}
/>
))
}
getChildCount={() => rooms.length}
/>
</div>
) : (
<span className="mx_ForwardList_noResults">{_t("common|no_results")}</span>
)}
</AutoHideScrollbar>
</div>
<RovingTabIndexProvider
handleUpDown
handleInputFields
onKeyDown={onKeyDown}
scrollIntoView={{ block: "center" }}
>
{({ onKeyDownHandler }) => (
<div className="mx_ForwardList" id="mx_ForwardList">
<RovingTabIndexContext.Consumer>
{(context) => (
<SearchBox
className="mx_textinput_icon mx_textinput_search"
placeholder={_t("forward|filter_placeholder")}
onSearch={(query: string): void => {
setQuery(query);
setImmediate(() => {
const ref = context.state.refs[0];
if (ref) {
context.dispatch({
type: Type.SetFocus,
payload: { ref },
});
ref.current?.scrollIntoView?.({
block: "nearest",
});
}
});
}}
autoFocus={true}
onKeyDown={onKeyDownHandler}
aria-activedescendant={context.state.activeRef?.current?.id}
aria-owns="mx_ForwardDialog_resultsList"
/>
)}
</RovingTabIndexContext.Consumer>
<AutoHideScrollbar className="mx_ForwardList_content">
{rooms.length > 0 ? (
<div className="mx_ForwardList_results">
<TruncatedList
id="mx_ForwardDialog_resultsList"
className="mx_ForwardList_resultsList"
truncateAt={truncateAt}
createOverflowElement={overflowTile}
getChildren={(start, end) =>
rooms
.slice(start, end)
.map((room) => (
<Entry
key={room.roomId}
room={room}
type={type}
content={content}
matrixClient={cli}
onFinished={onFinished}
/>
))
}
getChildCount={() => rooms.length}
/>
</div>
) : (
<span className="mx_ForwardList_noResults">{_t("common|no_results")}</span>
)}
</AutoHideScrollbar>
</div>
)}
</RovingTabIndexProvider>
</BaseDialog>
);
};

View File

@ -36,6 +36,7 @@ interface IProps {
// This will be inserted after the children.
createOverflowElement: (overflowCount: number, totalCount: number) => React.ReactNode;
children?: ReactNode;
id?: string;
}
export default class TruncatedList extends React.Component<IProps> {
@ -86,7 +87,7 @@ export default class TruncatedList extends React.Component<IProps> {
const childNodes = this.getChildren(0, upperBound);
return (
<div className={this.props.className}>
<div className={this.props.className} role="list" id={this.props.id}>
{childNodes}
{overflowNode}
</div>

View File

@ -16,6 +16,7 @@ limitations under the License.
import React, { HTMLAttributes } from "react";
import { render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import {
IState,
@ -364,4 +365,61 @@ describe("RovingTabIndex", () => {
});
});
});
describe("handles arrow keys", () => {
it("should handle up/down arrow keys work when handleUpDown=true", async () => {
const { container } = render(
<RovingTabIndexProvider handleUpDown>
{({ onKeyDownHandler }) => (
<div onKeyDown={onKeyDownHandler}>
{button1}
{button2}
{button3}
</div>
)}
</RovingTabIndexProvider>,
);
container.querySelectorAll("button")[0].focus();
checkTabIndexes(container.querySelectorAll("button"), [0, -1, -1]);
await userEvent.keyboard("[ArrowDown]");
checkTabIndexes(container.querySelectorAll("button"), [-1, 0, -1]);
await userEvent.keyboard("[ArrowDown]");
checkTabIndexes(container.querySelectorAll("button"), [-1, -1, 0]);
await userEvent.keyboard("[ArrowUp]");
checkTabIndexes(container.querySelectorAll("button"), [-1, 0, -1]);
await userEvent.keyboard("[ArrowUp]");
checkTabIndexes(container.querySelectorAll("button"), [0, -1, -1]);
// Does not loop without
await userEvent.keyboard("[ArrowUp]");
checkTabIndexes(container.querySelectorAll("button"), [0, -1, -1]);
});
it("should call scrollIntoView if specified", async () => {
const { container } = render(
<RovingTabIndexProvider handleUpDown scrollIntoView>
{({ onKeyDownHandler }) => (
<div onKeyDown={onKeyDownHandler}>
{button1}
{button2}
{button3}
</div>
)}
</RovingTabIndexProvider>,
);
container.querySelectorAll("button")[0].focus();
checkTabIndexes(container.querySelectorAll("button"), [0, -1, -1]);
const button = container.querySelectorAll("button")[1];
const mock = jest.spyOn(button, "scrollIntoView");
await userEvent.keyboard("[ArrowDown]");
expect(mock).toHaveBeenCalled();
});
});
});

View File

@ -24,7 +24,7 @@ import {
M_TIMESTAMP,
M_TEXT,
} from "matrix-js-sdk/src/matrix";
import { act, fireEvent, getByTestId, render, RenderResult, screen } from "@testing-library/react";
import { act, fireEvent, getByTestId, render, RenderResult, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MatrixClientPeg } from "../../../../src/MatrixClientPeg";
@ -44,6 +44,13 @@ import {
import { TILE_SERVER_WK_KEY } from "../../../../src/utils/WellKnownUtils";
import SettingsStore from "../../../../src/settings/SettingsStore";
// mock offsetParent
Object.defineProperty(HTMLElement.prototype, "offsetParent", {
get() {
return this.parentNode;
},
});
describe("ForwardDialog", () => {
const sourceRoom = "!111111111111111111:example.org";
const aliceId = "@alice:example.org";
@ -128,6 +135,37 @@ describe("ForwardDialog", () => {
expect(container.querySelectorAll(".mx_ForwardList_entry")).toHaveLength(3);
});
it("should be navigable using arrow keys", async () => {
const { container } = mountForwardDialog();
const searchBox = getByTestId(container, "searchbox-input");
searchBox.focus();
await waitFor(() =>
expect(container.querySelectorAll(".mx_ForwardList_entry")[0]).toHaveClass("mx_ForwardList_entry_active"),
);
await userEvent.keyboard("[ArrowDown]");
await waitFor(() =>
expect(container.querySelectorAll(".mx_ForwardList_entry")[1]).toHaveClass("mx_ForwardList_entry_active"),
);
await userEvent.keyboard("[ArrowDown]");
await waitFor(() =>
expect(container.querySelectorAll(".mx_ForwardList_entry")[2]).toHaveClass("mx_ForwardList_entry_active"),
);
await userEvent.keyboard("[ArrowUp]");
await waitFor(() =>
expect(container.querySelectorAll(".mx_ForwardList_entry")[1]).toHaveClass("mx_ForwardList_entry_active"),
);
await userEvent.keyboard("[Enter]");
expect(mockClient.sendEvent).toHaveBeenCalledWith("A", "m.room.message", {
body: "Hello world!",
msgtype: "m.text",
});
});
it("tracks message sending progress across multiple rooms", async () => {
mockPlatformPeg();
const { container } = mountForwardDialog();