Standardize modal focus and keyboard behavior

This commit is contained in:
Shinuwa 2026-10-15 00:03:13 +02:00
parent e87edda5c7
commit 954240adf9
15 changed files with 331 additions and 139 deletions

View file

@ -2,10 +2,10 @@
import { useEffect, useRef, useState } from "react";
import { DrawingControls } from "../features/toolboxes/modules/DrawingControls.jsx";
import { DrawingOverlay } from "../features/toolboxes/modules/DrawingOverlay.jsx";
import { lockBodyScroll } from "../utils/bodyScrollLock.js";
import { DRAWING_COLORS, DRAWING_WIDTHS } from "../utils/drawingOptions.js";
import { Icon } from "./Icon.jsx";
import { ImageGallery } from "./ImageGallery.jsx";
import { Modal } from "./Modal.jsx";
import { Tooltip } from "./Tooltip.jsx";
const IMAGE_GALLERY_SIZE_STORAGE_KEY = "sokkog:image-gallery-thumbnail-width";
@ -71,7 +71,6 @@ function formatPositionLabel(template, current, total) {
}
export function ImageViewer({ image, onClose, createMarkerId = () => globalThis.crypto?.randomUUID?.() || `marker-${Date.now()}` }) {
useEffect(() => lockBodyScroll(), []);
const isCollection = image.kind === "collection" && Array.isArray(image.images) && image.images.length > 0;
const collection = isCollection ? image.images : [image];
const initialIndex = isCollection ? Math.min(collection.length - 1, Math.max(0, Number(image.activeIndex) || 0)) : 0;
@ -136,10 +135,6 @@ export function ImageViewer({ image, onClose, createMarkerId = () => globalThis.
useEffect(() => {
const onKeyDown = (event) => {
if (event.key === "Escape") {
onClose();
return;
}
if (!isCollection || view !== "detail") return;
if (event.key === "ArrowLeft" && activeIndex > 0) {
event.preventDefault();
@ -152,7 +147,7 @@ export function ImageViewer({ image, onClose, createMarkerId = () => globalThis.
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [activeIndex, collection.length, isCollection, onClose, view]);
}, [activeIndex, collection.length, isCollection, view]);
function updateViewerMarkers(nextMarkers) {
setViewerMarkers(nextMarkers);
@ -236,9 +231,7 @@ export function ImageViewer({ image, onClose, createMarkerId = () => globalThis.
}
return (
<div className="image-viewer-root">
<div className="image-viewer-backdrop" onClick={onClose} />
<section ref={viewerRef} className={`image-viewer ${view === "gallery" ? "is-gallery" : ""}`} role="dialog" aria-modal="true" aria-label={view === "gallery" ? textContent.galleryTitle || "Galerie d'images" : "Image"}>
<Modal rootClassName="image-viewer-root" backdropClassName="image-viewer-backdrop" dialogClassName={`image-viewer ${view === "gallery" ? "is-gallery" : ""}`} ariaLabel={view === "gallery" ? textContent.galleryTitle || "Galerie d'images" : "Image"} onRequestClose={onClose} dialogRef={viewerRef}>
<header>
<div className="image-viewer-heading">
{(view === "gallery" || isCollection || activeImage.label) && (
@ -361,7 +354,6 @@ export function ImageViewer({ image, onClose, createMarkerId = () => globalThis.
</aside>
)}
</div>}
</section>
</div>
</Modal>
);
}

View file

@ -0,0 +1,197 @@
// Rôle : fournit le comportement clavier, focus et empilement commun aux fenêtres modales.
import { useLayoutEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { lockBodyScroll } from "../utils/bodyScrollLock.js";
const FOCUSABLE_SELECTOR = [
"a[href]",
"button:not([disabled])",
"input:not([disabled]):not([type='hidden'])",
"select:not([disabled])",
"textarea:not([disabled])",
"[tabindex]:not([tabindex='-1'])",
"[contenteditable='true']"
].join(",");
const modalStack = [];
const backgroundStates = new Map();
function rememberElementState(element) {
if (backgroundStates.has(element)) return;
backgroundStates.set(element, {
inert: element.inert,
hasAriaHidden: element.hasAttribute("aria-hidden"),
ariaHidden: element.getAttribute("aria-hidden")
});
}
function restoreElementState(element) {
const state = backgroundStates.get(element);
if (!state) return;
element.inert = state.inert;
if (state.hasAriaHidden) element.setAttribute("aria-hidden", state.ariaHidden);
else element.removeAttribute("aria-hidden");
}
function syncModalLayers() {
const topModal = modalStack.at(-1);
if (!topModal) {
backgroundStates.forEach((_state, element) => restoreElementState(element));
backgroundStates.clear();
return;
}
Array.from(document.body.children).forEach((element) => {
rememberElementState(element);
const isActiveLayer = element === topModal.root;
if (isActiveLayer) {
restoreElementState(element);
return;
}
element.inert = true;
element.setAttribute("aria-hidden", "true");
});
}
function isTopModal(id) {
return modalStack.at(-1)?.id === id;
}
function getFocusableElements(dialog) {
return Array.from(dialog.querySelectorAll(FOCUSABLE_SELECTOR)).filter((element) => (
!element.hidden
&& element.getAttribute("aria-hidden") !== "true"
&& element.getClientRects().length > 0
));
}
function focusInitialElement(dialog, initialFocusRef) {
const requested = initialFocusRef.current?.current;
const target = requested && dialog.contains(requested)
? requested
: dialog.querySelector("[data-modal-initial-focus], [autofocus]") || getFocusableElements(dialog)[0] || dialog;
target.focus({ preventScroll: true });
}
function assignRef(ref, value) {
if (typeof ref === "function") ref(value);
else if (ref) ref.current = value;
}
export function Modal({
children,
rootClassName = "confirm-modal-root",
backdropClassName = "confirm-backdrop nds-modal-backdrop",
dialogClassName = "confirm-modal nds-modal",
labelledBy,
describedBy,
ariaLabel,
onRequestClose,
canClose = true,
closeOnBackdrop = true,
closeOnEscape = true,
initialFocusRef,
returnFocusRef,
dialogRef
}) {
const idRef = useRef(Symbol("modal"));
const rootRef = useRef(null);
const internalDialogRef = useRef(null);
const returnTargetRef = useRef(null);
const onRequestCloseRef = useRef(onRequestClose);
const canCloseRef = useRef(canClose);
const closeOnEscapeRef = useRef(closeOnEscape);
const initialFocusRefRef = useRef(initialFocusRef);
const returnFocusRefRef = useRef(returnFocusRef);
useLayoutEffect(() => {
onRequestCloseRef.current = onRequestClose;
canCloseRef.current = canClose;
closeOnEscapeRef.current = closeOnEscape;
initialFocusRefRef.current = initialFocusRef;
returnFocusRefRef.current = returnFocusRef;
}, [canClose, closeOnEscape, initialFocusRef, onRequestClose, returnFocusRef]);
useLayoutEffect(() => {
const id = idRef.current;
const root = rootRef.current;
const dialog = internalDialogRef.current;
if (!returnTargetRef.current?.isConnected) returnTargetRef.current = document.activeElement;
const unlockBodyScroll = lockBodyScroll();
modalStack.push({ id, root, dialog });
syncModalLayers();
focusInitialElement(dialog, initialFocusRefRef);
function handleKeyDown(event) {
if (!isTopModal(id)) return;
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
if (closeOnEscapeRef.current && canCloseRef.current) onRequestCloseRef.current?.();
return;
}
if (event.key !== "Tab") return;
const focusable = getFocusableElements(dialog);
if (!focusable.length) {
event.preventDefault();
dialog.focus({ preventScroll: true });
return;
}
const first = focusable[0];
const last = focusable.at(-1);
if (event.shiftKey && (document.activeElement === first || !dialog.contains(document.activeElement))) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (document.activeElement === last || !dialog.contains(document.activeElement))) {
event.preventDefault();
first.focus();
}
}
document.addEventListener("keydown", handleKeyDown, true);
return () => {
document.removeEventListener("keydown", handleKeyDown, true);
const index = modalStack.findIndex((entry) => entry.id === id);
if (index >= 0) modalStack.splice(index, 1);
syncModalLayers();
unlockBodyScroll();
queueMicrotask(() => {
if (modalStack.some((entry) => entry.id === id)) return;
const requested = returnFocusRefRef.current?.current;
const target = requested?.isConnected ? requested : returnTargetRef.current?.isConnected ? returnTargetRef.current : null;
if (target && typeof target.focus === "function") target.focus({ preventScroll: true });
else {
const topDialog = modalStack.at(-1)?.dialog;
if (topDialog) focusInitialElement(topDialog, { current: null });
}
});
};
}, []);
return createPortal(
<div className={rootClassName} data-modal-layer="" ref={rootRef}>
<div
className={backdropClassName}
onClick={() => {
if (closeOnBackdrop && canClose && isTopModal(idRef.current)) onRequestClose?.();
}}
/>
<section
className={dialogClassName}
ref={(element) => {
internalDialogRef.current = element;
assignRef(dialogRef, element);
}}
role="dialog"
aria-modal="true"
aria-labelledby={labelledBy}
aria-describedby={describedBy}
aria-label={ariaLabel}
tabIndex={-1}
>
{children}
</section>
</div>,
document.body
);
}

View file

@ -1,27 +1,21 @@
// Rôle : fournit les modales globales liées aux toolboxes et confirmations.
import { useEffect, useState } from "react";
import { useEffect, useId, useState } from "react";
import { flushSync } from "react-dom";
import { Icon } from "./Icon.jsx";
import { lockBodyScroll } from "../utils/bodyScrollLock.js";
function useModalScrollLock() {
useEffect(() => lockBodyScroll(), []);
}
import { Modal } from "./Modal.jsx";
export function ConfirmModal({ title, message, confirmLabel = "Confirmer", cancelLabel = "Annuler", danger = false, onClose }) {
useModalScrollLock();
const titleId = useId();
const messageId = useId();
return (
<div className="confirm-modal-root">
<div className="confirm-backdrop nds-modal-backdrop" onClick={() => onClose(false)} />
<section className="confirm-modal nds-modal" role="dialog" aria-modal="true" aria-labelledby="confirm-title" aria-describedby="confirm-message">
<header><h2 id="confirm-title">{title}</h2></header>
<p id="confirm-message">{message}</p>
<Modal labelledBy={titleId} describedBy={messageId} onRequestClose={() => onClose(false)}>
<header><h2 id={titleId}>{title}</h2></header>
<p id={messageId}>{message}</p>
<footer className="nds-modal-footer">
<button className="nds-button" data-size="sm" onClick={() => onClose(false)}>{cancelLabel}</button>
<button className="nds-button" data-size="sm" data-modal-initial-focus={danger ? "" : undefined} onClick={() => onClose(false)}>{cancelLabel}</button>
<button className="confirm-danger nds-button" data-size="sm" data-variant={danger ? "danger" : "primary"} onClick={() => onClose(true)}>{confirmLabel}</button>
</footer>
</section>
</div>
</Modal>
);
}
@ -47,62 +41,51 @@ export function NotificationToast({ id, message, durationMs = 6000, actionLabel
}
export function CreateToolboxModal({ gameId, initialName = "", onClose }) {
useModalScrollLock();
const [name, setName] = useState(initialName);
return (
<div className="confirm-modal-root">
<div className="confirm-backdrop nds-modal-backdrop" onClick={() => onClose("")} />
<section className="confirm-modal nds-modal toolbox-create-modal" role="dialog" aria-modal="true" aria-labelledby="toolbox-create-title">
<Modal dialogClassName="confirm-modal nds-modal toolbox-create-modal" labelledBy="toolbox-create-title" onRequestClose={() => onClose("")}>
<header><h2 id="toolbox-create-title">{gameId ? "Créer et associer une toolbox" : "Nouvelle toolbox"}</h2></header>
<form onSubmit={(event) => {
event.preventDefault();
if (name.trim()) onClose(name.trim());
}}>
<label className="field"><span>Nom</span><input className="nds-input" data-size="sm" name="name" type="text" autoComplete="off" placeholder="Nom de la toolbox" required value={name} onChange={(event) => setName(event.target.value)} autoFocus /></label>
<label className="field"><span>Nom</span><input className="nds-input" data-size="sm" name="name" type="text" autoComplete="off" placeholder="Nom de la toolbox" required value={name} onChange={(event) => setName(event.target.value)} data-modal-initial-focus="" /></label>
<footer className="nds-modal-footer"><button className="nds-button" data-size="sm" type="button" onClick={() => onClose("")}>Annuler</button><button className="nds-button" data-size="sm" data-variant="primary" type="submit">Créer</button></footer>
</form>
</section>
</div>
</Modal>
);
}
export function LinkToolboxModal({ toolboxes, selectedId, onClose }) {
useModalScrollLock();
const [toolboxId, setToolboxId] = useState(selectedId);
return (
<div className="confirm-modal-root">
<div className="confirm-backdrop nds-modal-backdrop" onClick={() => onClose(null)} />
<section className="confirm-modal nds-modal toolbox-link-modal" role="dialog" aria-modal="true" aria-labelledby="toolbox-link-title">
<Modal dialogClassName="confirm-modal nds-modal toolbox-link-modal" labelledBy="toolbox-link-title" onRequestClose={() => onClose(null)}>
<header><h2 id="toolbox-link-title">Lier une toolbox</h2></header>
<form onSubmit={(event) => {
event.preventDefault();
onClose(toolboxId);
}}>
<label className="field"><span>Toolbox associée</span><select className="nds-select" data-size="sm" value={toolboxId} onChange={(event) => setToolboxId(event.target.value)} autoFocus><option value="">Aucune</option>{toolboxes.map((toolbox) => <option key={toolbox.id} value={toolbox.id}>{toolbox.name}</option>)}</select></label>
<label className="field"><span>Toolbox associée</span><select className="nds-select" data-size="sm" value={toolboxId} onChange={(event) => setToolboxId(event.target.value)} data-modal-initial-focus=""><option value="">Aucune</option>{toolboxes.map((toolbox) => <option key={toolbox.id} value={toolbox.id}>{toolbox.name}</option>)}</select></label>
<footer className="nds-modal-footer"><button className="nds-button" data-size="sm" type="button" onClick={() => onClose(null)}>Annuler</button><button className="nds-button" data-size="sm" data-variant="primary" type="submit">Valider</button></footer>
</form>
</section>
</div>
</Modal>
);
}
export function AutoBackupModal({ backup, content, onClose }) {
useModalScrollLock();
const folderName = backup.config.directoryHandle?.name || content.noFolder;
const lastBackup = backup.config.lastBackup
? new Date(backup.config.lastBackup).toLocaleString()
: content.never;
return (
<div className="confirm-modal-root auto-backup-modal-root">
<div className="confirm-backdrop nds-modal-backdrop" onClick={onClose} />
<section className="confirm-modal nds-modal auto-backup-modal themed-scrollbar" role="dialog" aria-modal="true" aria-labelledby="auto-backup-title">
<Modal rootClassName="confirm-modal-root auto-backup-modal-root" dialogClassName="confirm-modal nds-modal auto-backup-modal themed-scrollbar" labelledBy="auto-backup-title" onRequestClose={onClose} canClose={!backup.busy}>
<header className="auto-backup-modal-header">
<div>
<p className="eyebrow">{content.eyebrow}</p>
<h2 id="auto-backup-title">{content.title}</h2>
</div>
<button className="nds-icon-button" data-size="sm" type="button" onClick={onClose} aria-label={content.close} title={content.close}><Icon name="close" /></button>
<button className="nds-icon-button" data-size="sm" type="button" disabled={backup.busy} onClick={onClose} aria-label={content.close} title={content.close}><Icon name="close" /></button>
</header>
<p className="auto-backup-description">{content.description}</p>
<div className="auto-backup-compatibility">
@ -138,9 +121,8 @@ export function AutoBackupModal({ backup, content, onClose }) {
</>
)}
<footer className="nds-modal-footer auto-backup-close-footer">
<button className="nds-button" data-size="sm" type="button" onClick={onClose}>{content.close}</button>
<button className="nds-button" data-size="sm" type="button" disabled={backup.busy} onClick={onClose}>{content.close}</button>
</footer>
</section>
</div>
</Modal>
);
}