Files
alpenwerk-hr/components/ui/useDialogFocus.ts
Raphael Müllner b47dec6387 Übergabestand 2026-10-14
Alpenwerk HR — HR-Stammdatenverwaltung

Mitarbeiter:innen, Organisationsstruktur, Planstellen, Eintritt, Austritt,
Versetzung, Beförderung, Karenz, On- und Offboarding, Berichte, Exporte,
Massenimport und ein lückenloser Nachweis jeder Änderung.

Next.js 16, React 19 und TypeScript; PostgreSQL über Kysely; Anmeldung
ausschliesslich über Microsoft Entra ID. Die Fachlogik liegt in der
Datenbank, die Zugriffsschranke ist Row Level Security.

Betrieb auf Windows Server: siehe deploy/windows/README.md.
Sicherheitskonzept: docs/sicherheitskonzept.md.
2026-10-14 10:12:22 +02:00

91 lines
3.3 KiB
TypeScript

"use client";
import { useEffect, useRef, type RefObject } from "react";
// Everything a dialog owes the keyboard, in one place so Modal and SlideOver
// cannot drift apart: focus moves into the dialog, Tab stays inside it,
// Escape closes it, and closing returns focus to whatever opened it —
// otherwise focus would land on <body> and the next Tab would start again
// from the top of the document.
const FOCUSABLE = [
"a[href]",
"button:not([disabled])",
"input:not([disabled]):not([type='hidden'])",
"select:not([disabled])",
"textarea:not([disabled])",
"[tabindex]:not([tabindex='-1'])",
].join(",");
function focusableWithin(container: HTMLElement): HTMLElement[] {
return [...container.querySelectorAll<HTMLElement>(FOCUSABLE)].filter(
(el) => el.offsetParent !== null || el.getClientRects().length > 0
);
}
export function useDialogFocus(open: boolean, onClose: () => void, containerRef: RefObject<HTMLElement | null>) {
const restoreToRef = useRef<HTMLElement | null>(null);
// onClose wird von den meisten Aufrufern bei jedem Rendern neu erzeugt.
// Stünde es in den Abhängigkeiten, liefe dieser Effekt nach jedem Rendern
// erneut — und sein Aufräumen holt den Fokus dorthin zurück, wo er vor dem
// Öffnen war. In einem Dialog mit Eingabefeldern hiesse das: nach dem
// ersten Zeichen springt der Fokus auf den Knopf, der ihn geöffnet hat, und
// der Rest der Eingabe geht ins Leere. Über eine Referenz bleibt der
// aktuelle Rückruf erreichbar, ohne dass der Effekt daran hängt.
const schliessen = useRef(onClose);
useEffect(() => {
schliessen.current = onClose;
});
useEffect(() => {
if (!open) return;
const container = containerRef.current;
restoreToRef.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
// First field rather than the close button: the point of opening these is
// to fill them in. autoFocus on a child wins, since it has already run.
if (container && !container.contains(document.activeElement)) {
const [first] = focusableWithin(container);
(first ?? container).focus();
}
function onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") {
schliessen.current();
return;
}
if (e.key !== "Tab" || !container) return;
const focusable = focusableWithin(container);
if (focusable.length === 0) {
e.preventDefault();
return;
}
const first = focusable[0];
const last = focusable[focusable.length - 1];
const active = document.activeElement;
// Wrap around at both ends, and pull focus back in if it somehow
// escaped (a click on the backdrop, say).
if (!container.contains(active)) {
e.preventDefault();
(e.shiftKey ? last : first).focus();
} else if (e.shiftKey && active === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && active === last) {
e.preventDefault();
first.focus();
}
}
window.addEventListener("keydown", onKeyDown);
return () => {
window.removeEventListener("keydown", onKeyDown);
// Back to whatever opened the dialog, so the next Tab continues from
// there instead of restarting at the top of the page.
restoreToRef.current?.focus();
};
}, [open, containerRef]);
}