Accessible modals ()

Improve the accessibility of our modals (the color picker and the export dialog)

Implement a focus trap so that tapping through the controls inside them don't escape to outer elements, it also allows to close the modals with the "Escape" key.
This commit is contained in:
Guillermo Peralta Scura 2020-01-25 19:37:58 -03:00 committed by GitHub
parent ba13f88924
commit e4ff408f23
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 207 additions and 58 deletions

@ -92,7 +92,11 @@
viewBox="0 0 250 250" viewBox="0 0 250 250"
style="position: absolute; top: 0; right: 0" style="position: absolute; top: 0; right: 0"
> >
<a href="https://github.com/excalidraw/excalidraw" target="_blank"> <a
href="https://github.com/excalidraw/excalidraw"
target="_blank"
aria-label="GitHub repository"
>
<path d="M0 0l115 115h15l12 27 108 108V0z" fill="#6c6c6c" /> <path d="M0 0l115 115h15l12 27 108 108V0z" fill="#6c6c6c" />
<path <path
class="octo-arm" class="octo-arm"

@ -35,7 +35,10 @@
"extraBold": "Extra Bold", "extraBold": "Extra Bold",
"architect": "Architect", "architect": "Architect",
"artist": "Artist", "artist": "Artist",
"cartoonist": "Cartoonist" "cartoonist": "Cartoonist",
"fileTitle": "File title",
"colorPicker": "Color picker",
"canvasBackground": "Canvas background"
}, },
"buttons": { "buttons": {
"clearReset": "Clear the canvas & reset background color", "clearReset": "Clear the canvas & reset background color",
@ -44,7 +47,8 @@
"copyToClipboard": "Copy to clipboard", "copyToClipboard": "Copy to clipboard",
"save": "Save", "save": "Save",
"load": "Load", "load": "Load",
"getShareableLink": "Get shareable link" "getShareableLink": "Get shareable link",
"close": "Close"
}, },
"alerts": { "alerts": {
"clearReset": "This will clear the whole canvas. Are you sure?", "clearReset": "This will clear the whole canvas. Are you sure?",

@ -35,7 +35,10 @@
"extraBold": "Extra Grueso", "extraBold": "Extra Grueso",
"architect": "Arquitecto", "architect": "Arquitecto",
"artist": "Artista", "artist": "Artista",
"cartoonist": "Caricatura" "cartoonist": "Caricatura",
"fileTitle": "Título del archivo",
"colorPicker": "Selector de color",
"canvasBackground": "Fondo del lienzo"
}, },
"buttons": { "buttons": {
"clearReset": "Limpiar lienzo y reiniciar el color de fondo", "clearReset": "Limpiar lienzo y reiniciar el color de fondo",
@ -44,7 +47,9 @@
"copyToClipboard": "Copiar al portapapeles", "copyToClipboard": "Copiar al portapapeles",
"save": "Guardar", "save": "Guardar",
"load": "Cargar", "load": "Cargar",
"getShareableLink": "Obtener enlace para compartir" "getShareableLink": "Obtener enlace para compartir",
"showExportDialog": "Mostrar diálogo para exportar",
"close": "Cerrar"
}, },
"alerts": { "alerts": {
"clearReset": "Esto limpiará todo el lienzo. Estás seguro?", "clearReset": "Esto limpiará todo el lienzo. Estás seguro?",

@ -10,11 +10,11 @@ export const actionChangeViewBackgroundColor: Action = {
perform: (elements, appState, value) => { perform: (elements, appState, value) => {
return { appState: { ...appState, viewBackgroundColor: value } }; return { appState: { ...appState, viewBackgroundColor: value } };
}, },
PanelComponent: ({ appState, updateData }) => { PanelComponent: ({ appState, updateData, t }) => {
return ( return (
<div style={{ position: "relative" }}> <div style={{ position: "relative" }}>
<ColorPicker <ColorPicker
label="Canvas Background" label={t("labels.canvasBackground")}
type="canvasBackground" type="canvasBackground"
color={appState.viewBackgroundColor} color={appState.viewBackgroundColor}
onChange={color => updateData(color)} onChange={color => updateData(color)}

@ -10,8 +10,9 @@ export const actionChangeProjectName: Action = {
perform: (elements, appState, value) => { perform: (elements, appState, value) => {
return { appState: { ...appState, name: value } }; return { appState: { ...appState, name: value } };
}, },
PanelComponent: ({ appState, updateData }) => ( PanelComponent: ({ appState, updateData, t }) => (
<EditableText <EditableText
label={t("labels.fileTitle")}
value={appState.name || "Unnamed"} value={appState.name || "Unnamed"}
onChange={(name: string) => updateData(name)} onChange={(name: string) => updateData(name)}
/> />

@ -48,7 +48,6 @@
height: 1.875rem; height: 1.875rem;
width: 1.875rem; width: 1.875rem;
cursor: pointer; cursor: pointer;
outline: none;
border-radius: 4px; border-radius: 4px;
margin: 0px 0.375rem 0.375rem 0px; margin: 0px 0.375rem 0.375rem 0px;
box-sizing: border-box; box-sizing: border-box;

@ -2,6 +2,9 @@ import React from "react";
import { Popover } from "./Popover"; import { Popover } from "./Popover";
import "./ColorPicker.css"; import "./ColorPicker.css";
import { KEYS } from "../keys";
import { useTranslation } from "react-i18next";
import { TFunction } from "i18next";
// This is a narrow reimplementation of the awesome react-color Twitter component // This is a narrow reimplementation of the awesome react-color Twitter component
// https://github.com/casesandberg/react-color/blob/master/src/components/twitter/Twitter.js // https://github.com/casesandberg/react-color/blob/master/src/components/twitter/Twitter.js
@ -10,29 +13,71 @@ const Picker = function({
colors, colors,
color, color,
onChange, onChange,
onClose,
label, label,
t,
}: { }: {
colors: string[]; colors: string[];
color: string | null; color: string | null;
onChange: (color: string) => void; onChange: (color: string) => void;
onClose: () => void;
label: string; label: string;
t: TFunction;
}) { }) {
const firstItem = React.useRef<HTMLButtonElement>();
const colorInput = React.useRef<HTMLInputElement>();
React.useEffect(() => {
// After the component is first mounted
// focus on first input
if (firstItem.current) firstItem.current.focus();
}, []);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === KEYS.TAB) {
const { activeElement } = document;
if (e.shiftKey) {
if (activeElement === firstItem.current) {
colorInput.current?.focus();
e.preventDefault();
}
} else {
if (activeElement === colorInput.current) {
firstItem.current?.focus();
e.preventDefault();
}
}
} else if (e.key === KEYS.ESCAPE) {
onClose();
e.nativeEvent.stopImmediatePropagation();
}
};
return ( return (
<div className="color-picker"> <div
className="color-picker"
role="dialog"
aria-modal="true"
aria-label={t("labels.colorPicker")}
onKeyDown={handleKeyDown}
>
<div className="color-picker-triangle-shadow"></div> <div className="color-picker-triangle-shadow"></div>
<div className="color-picker-triangle"></div> <div className="color-picker-triangle"></div>
<div className="color-picker-content"> <div className="color-picker-content">
<div className="colors-gallery"> <div className="colors-gallery">
{colors.map(color => ( {colors.map((color, i) => (
<button <button
className="color-picker-swatch" className="color-picker-swatch"
onClick={() => { onClick={() => {
onChange(color); onChange(color);
}} }}
title={color} title={color}
tabIndex={0} aria-label={color}
style={{ backgroundColor: color }} style={{ backgroundColor: color }}
key={color} key={color}
ref={el => {
if (i === 0 && el) firstItem.current = el;
}}
> >
{color === "transparent" ? ( {color === "transparent" ? (
<div className="color-picker-transparent"></div> <div className="color-picker-transparent"></div>
@ -48,28 +93,36 @@ const Picker = function({
onChange={color => { onChange={color => {
onChange(color); onChange(color);
}} }}
ref={colorInput}
/> />
</div> </div>
</div> </div>
); );
}; };
function ColorInput({ const ColorInput = React.forwardRef(
(
{
color, color,
onChange, onChange,
label, label,
}: { }: {
color: string | null; color: string | null;
onChange: (color: string) => void; onChange: (color: string) => void;
label: string; label: string;
}) { },
ref,
) => {
const colorRegex = /^([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8}|transparent)$/; const colorRegex = /^([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8}|transparent)$/;
const [innerValue, setInnerValue] = React.useState(color); const [innerValue, setInnerValue] = React.useState(color);
const inputRef = React.useRef(null);
React.useEffect(() => { React.useEffect(() => {
setInnerValue(color); setInnerValue(color);
}, [color]); }, [color]);
React.useImperativeHandle(ref, () => inputRef.current);
return ( return (
<div className="color-input-container"> <div className="color-input-container">
<div className="color-picker-hash">#</div> <div className="color-picker-hash">#</div>
@ -87,10 +140,12 @@ function ColorInput({
value={(innerValue || "").replace(/^#/, "")} value={(innerValue || "").replace(/^#/, "")}
onPaste={e => onChange(e.clipboardData.getData("text"))} onPaste={e => onChange(e.clipboardData.getData("text"))}
onBlur={() => setInnerValue(color)} onBlur={() => setInnerValue(color)}
ref={inputRef}
/> />
</div> </div>
); );
} },
);
export function ColorPicker({ export function ColorPicker({
type, type,
@ -103,7 +158,10 @@ export function ColorPicker({
onChange: (color: string) => void; onChange: (color: string) => void;
label: string; label: string;
}) { }) {
const { t } = useTranslation();
const [isActive, setActive] = React.useState(false); const [isActive, setActive] = React.useState(false);
const pickerButton = React.useRef<HTMLButtonElement>(null);
return ( return (
<div> <div>
@ -113,6 +171,7 @@ export function ColorPicker({
aria-label={label} aria-label={label}
style={color ? { backgroundColor: color } : undefined} style={color ? { backgroundColor: color } : undefined}
onClick={() => setActive(!isActive)} onClick={() => setActive(!isActive)}
ref={pickerButton}
/> />
<ColorInput <ColorInput
color={color} color={color}
@ -131,7 +190,12 @@ export function ColorPicker({
onChange={changedColor => { onChange={changedColor => {
onChange(changedColor); onChange(changedColor);
}} }}
onClose={() => {
setActive(false);
pickerButton.current?.focus();
}}
label={label} label={label}
t={t}
/> />
</Popover> </Popover>
) : null} ) : null}

@ -6,6 +6,7 @@ import { selectNode, removeSelection } from "../utils";
type Props = { type Props = {
value: string; value: string;
onChange: (value: string) => void; onChange: (value: string) => void;
label: string;
}; };
export class EditableText extends Component<Props> { export class EditableText extends Component<Props> {
@ -33,6 +34,8 @@ export class EditableText extends Component<Props> {
contentEditable="true" contentEditable="true"
data-type="wysiwyg" data-type="wysiwyg"
className="project-name" className="project-name"
role="textbox"
aria-label={this.props.label}
onBlur={this.handleBlur} onBlur={this.handleBlur}
onKeyDown={this.handleKeyDown} onKeyDown={this.handleKeyDown}
onFocus={this.handleFocus} onFocus={this.handleFocus}

@ -13,6 +13,7 @@ import { ActionsManagerInterface, UpdaterFn } from "../actions/types";
import Stack from "./Stack"; import Stack from "./Stack";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { KEYS } from "../keys";
const probablySupportsClipboard = const probablySupportsClipboard =
"toBlob" in HTMLCanvasElement.prototype && "toBlob" in HTMLCanvasElement.prototype &&
@ -55,6 +56,9 @@ function ExportModal({
const [exportSelected, setExportSelected] = useState(someElementIsSelected); const [exportSelected, setExportSelected] = useState(someElementIsSelected);
const previewRef = useRef<HTMLDivElement>(null); const previewRef = useRef<HTMLDivElement>(null);
const { exportBackground, viewBackgroundColor } = appState; const { exportBackground, viewBackgroundColor } = appState;
const pngButton = useRef<HTMLButtonElement>(null);
const closeButton = useRef<HTMLButtonElement>(null);
const onlySelectedInput = useRef<HTMLInputElement>(null);
const exportedElements = exportSelected const exportedElements = exportSelected
? elements.filter(element => element.isSelected) ? elements.filter(element => element.isSelected)
@ -84,13 +88,43 @@ function ExportModal({
scale, scale,
]); ]);
useEffect(() => {
pngButton.current?.focus();
}, []);
function handleKeyDown(e: React.KeyboardEvent) {
if (e.key === KEYS.TAB) {
const { activeElement } = document;
if (e.shiftKey) {
if (activeElement === pngButton.current) {
closeButton.current?.focus();
e.preventDefault();
}
} else {
if (activeElement === closeButton.current) {
pngButton.current?.focus();
e.preventDefault();
}
if (activeElement === onlySelectedInput.current) {
closeButton.current?.focus();
e.preventDefault();
}
}
}
}
return ( return (
<div className="ExportDialog__dialog"> <div className="ExportDialog__dialog" onKeyDown={handleKeyDown}>
<Island padding={4}> <Island padding={4}>
<button className="ExportDialog__close" onClick={onCloseRequest}> <button
className="ExportDialog__close"
onClick={onCloseRequest}
aria-label={t("buttons.close")}
ref={closeButton}
>
</button> </button>
<h2>{t("buttons.export")}</h2> <h2 id="export-title">{t("buttons.export")}</h2>
<div className="ExportDialog__preview" ref={previewRef}></div> <div className="ExportDialog__preview" ref={previewRef}></div>
<div className="ExportDialog__actions"> <div className="ExportDialog__actions">
<Stack.Row gap={2}> <Stack.Row gap={2}>
@ -100,6 +134,7 @@ function ExportModal({
title={t("buttons.exportToPng")} title={t("buttons.exportToPng")}
aria-label={t("buttons.exportToPng")} aria-label={t("buttons.exportToPng")}
onClick={() => onExportToPng(exportedElements, scale)} onClick={() => onExportToPng(exportedElements, scale)}
ref={pngButton}
/> />
{probablySupportsClipboard && ( {probablySupportsClipboard && (
<ToolButton <ToolButton
@ -136,7 +171,7 @@ function ExportModal({
type="radio" type="radio"
icon={"x" + s} icon={"x" + s}
name="export-canvas-scale" name="export-canvas-scale"
aria-label="Export" aria-label={`Scale ${s} x`}
id="export-canvas-scale" id="export-canvas-scale"
checked={scale === s} checked={scale === s}
onChange={() => setScale(s)} onChange={() => setScale(s)}
@ -158,6 +193,7 @@ function ExportModal({
type="checkbox" type="checkbox"
checked={exportSelected} checked={exportSelected}
onChange={e => setExportSelected(e.currentTarget.checked)} onChange={e => setExportSelected(e.currentTarget.checked)}
ref={onlySelectedInput}
/>{" "} />{" "}
{t("labels.onlySelected")} {t("labels.onlySelected")}
</label> </label>
@ -191,6 +227,12 @@ export function ExportDialog({
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const [modalIsShown, setModalIsShown] = useState(false); const [modalIsShown, setModalIsShown] = useState(false);
const triggerButton = useRef<HTMLButtonElement>(null);
const handleClose = React.useCallback(() => {
setModalIsShown(false);
triggerButton.current?.focus();
}, []);
return ( return (
<> <>
@ -198,11 +240,16 @@ export function ExportDialog({
onClick={() => setModalIsShown(true)} onClick={() => setModalIsShown(true)}
icon={exportFile} icon={exportFile}
type="button" type="button"
aria-label="Show export dialog" aria-label={t("buttons.export")}
title={t("buttons.export")} title={t("buttons.export")}
ref={triggerButton}
/> />
{modalIsShown && ( {modalIsShown && (
<Modal maxWidth={640} onCloseRequest={() => setModalIsShown(false)}> <Modal
maxWidth={640}
onCloseRequest={handleClose}
labelledBy="export-title"
>
<ExportModal <ExportModal
elements={elements} elements={elements}
appState={appState} appState={appState}
@ -212,7 +259,7 @@ export function ExportDialog({
onExportToPng={onExportToPng} onExportToPng={onExportToPng}
onExportToClipboard={onExportToClipboard} onExportToClipboard={onExportToClipboard}
onExportToBackend={onExportToBackend} onExportToBackend={onExportToBackend}
onCloseRequest={() => setModalIsShown(false)} onCloseRequest={handleClose}
/> />
</Modal> </Modal>
)} )}

@ -2,15 +2,30 @@ import "./Modal.css";
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import { createPortal } from "react-dom"; import { createPortal } from "react-dom";
import { KEYS } from "../keys";
export function Modal(props: { export function Modal(props: {
children: React.ReactNode; children: React.ReactNode;
maxWidth?: number; maxWidth?: number;
onCloseRequest(): void; onCloseRequest(): void;
labelledBy: string;
}) { }) {
const modalRoot = useBodyRoot(); const modalRoot = useBodyRoot();
const handleKeydown = (e: React.KeyboardEvent) => {
if (e.key === KEYS.ESCAPE) {
e.nativeEvent.stopImmediatePropagation();
props.onCloseRequest();
}
};
return createPortal( return createPortal(
<div className="Modal"> <div
className="Modal"
role="dialog"
aria-modal="true"
onKeyDown={handleKeydown}
aria-labelledby={props.labelledBy}
>
<div className="Modal__background" onClick={props.onCloseRequest}></div> <div className="Modal__background" onClick={props.onCloseRequest}></div>
<div className="Modal__content" style={{ maxWidth: props.maxWidth }}> <div className="Modal__content" style={{ maxWidth: props.maxWidth }}>
{props.children} {props.children}

@ -25,7 +25,12 @@ type ToolButtonProps =
const DEFAULT_SIZE: ToolIconSize = "m"; const DEFAULT_SIZE: ToolIconSize = "m";
export function ToolButton(props: ToolButtonProps) { export const ToolButton = React.forwardRef(function(
props: ToolButtonProps,
ref,
) {
const innerRef = React.useRef(null);
React.useImperativeHandle(ref, () => innerRef.current);
const sizeCn = `ToolIcon_size_${props.size || DEFAULT_SIZE}`; const sizeCn = `ToolIcon_size_${props.size || DEFAULT_SIZE}`;
if (props.type === "button") if (props.type === "button")
@ -36,6 +41,7 @@ export function ToolButton(props: ToolButtonProps) {
aria-label={props["aria-label"]} aria-label={props["aria-label"]}
type="button" type="button"
onClick={props.onClick} onClick={props.onClick}
ref={innerRef}
> >
<div className="ToolIcon__icon" aria-hidden="true"> <div className="ToolIcon__icon" aria-hidden="true">
{props.icon} {props.icon}
@ -55,8 +61,9 @@ export function ToolButton(props: ToolButtonProps) {
id={props.id} id={props.id}
onChange={props.onChange} onChange={props.onChange}
checked={props.checked} checked={props.checked}
ref={innerRef}
/> />
<div className="ToolIcon__icon">{props.icon}</div> <div className="ToolIcon__icon">{props.icon}</div>
</label> </label>
); );
} });

@ -12,6 +12,7 @@ export const KEYS = {
? "metaKey" ? "metaKey"
: "ctrlKey"; : "ctrlKey";
}, },
TAB: "Tab",
}; };
export function isArrowKey(keyCode: string) { export function isArrowKey(keyCode: string) {

@ -100,7 +100,6 @@ button,
border-radius: 4px; border-radius: 4px;
margin: 0.125rem 0; margin: 0.125rem 0;
padding: 0.25rem; padding: 0.25rem;
outline: transparent;
cursor: pointer; cursor: pointer;