Form primitives, keyboard-operable comboboxes, dialog focus, route states

Accessibility work on the UI layer, all of it rooted in one structural gap:
there were no form primitives, so every field was hand-assembled and every
field got the same details wrong.

Form primitives
- components/ui/Field.tsx (Field/TextField/SelectField/TextareaField) and
  Button.tsx. Field generates the control id with useId and derives htmlFor
  from it, which is what makes the association impossible to omit rather
  than merely conventional.
- 92 labels existed, 4 used htmlFor, and no input carried an id at all: a
  screen reader announced an unnamed edit box and clicking a label focused
  nothing. Now every label resolves to its control (0 unassociated), and the
  input class chain that appeared verbatim 85 times appears zero times.
- Field also takes a render prop, so Lookup, CountryPicker and Picklist get
  the same wiring instead of a second, partial solution.
- SearchInput replaces three hand-rolled copies of the icon-in-a-box search
  whose input had only a placeholder — not a label — and killed its own
  focus ring with outline-none and nothing in its place.
- Toggle groups (workdays, reorg change type) became fieldsets with
  aria-pressed; colour alone was carrying the selected state.

Comboboxes
- Lookup and CountryPicker were text inputs with a div of clickable buttons
  underneath: typeable, but no keyboard path to a result and nothing telling
  a screen reader a list had appeared. Both now carry role=combobox,
  aria-expanded/controls/activedescendant and listbox semantics, with arrow
  keys, Enter and Escape. Escape stops propagation, or it would close the
  surrounding dialog along with the dropdown.

Dialogs
- useDialogFocus centralises what Modal and SlideOver each owed the
  keyboard and neither provided beyond Escape: focus into the dialog on
  open, Tab and Shift+Tab cycling within it, focus restored to the trigger
  on close.
- SlideOver stays mounted for its transition, and aria-hidden does not
  remove anything from the tab order — so every closed panel was leaving
  invisible tab stops at the end of the page. `inert` fixes that.

Route states
- loading.tsx, error.tsx, not-found.tsx and global-error.tsx. Every page in
  the (app) group is server-rendered per request, so without loading.tsx a
  navigation showed nothing at all until the server answered, and a render
  error dropped the user on Next's own screen with no way back.

Tests
- 22 component tests (vitest jsdom project). Two of them found limits of the
  environment rather than of the code: jsdom implements neither `inert` nor
  scrollIntoView, so the inert test asserts the attribute and the missing
  scrollIntoView — which was taking the whole render down from inside an
  effect — is stubbed in the setup file.
This commit is contained in:
2026-07-25 13:10:52 +02:00
parent 4be5f2264e
commit d9367a8ce4
44 changed files with 1770 additions and 1127 deletions

74
components/ui/Button.tsx Normal file
View File

@@ -0,0 +1,74 @@
"use client";
import type { ButtonHTMLAttributes, ReactNode } from "react";
// The primary-button class chain was written out by hand at a dozen call
// sites and the ghost/secondary ones at many more, each drifting slightly in
// padding and hover colour. Collecting them here also gives every button a
// visible keyboard focus ring, which none of them had.
const BASE =
"inline-flex items-center justify-center gap-1.5 rounded font-semibold transition-colors " +
"focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-500 " +
"disabled:cursor-not-allowed disabled:opacity-50";
const VARIANTS = {
primary: "bg-brand-500 text-white hover:bg-brand-600",
secondary: "border border-border bg-white text-ink-body hover:bg-surface",
ghost: "text-ink-body hover:bg-surface",
danger: "bg-danger-solid text-white hover:brightness-110",
// Square icon-only button; pair with an aria-label.
icon: "text-ink-muted hover:bg-surface hover:text-ink",
} as const;
const SIZES = {
sm: "px-3 py-1.5 text-xs",
md: "px-4 py-2 text-sm",
// Meets the 44px touch target without looking oversized on desktop.
icon: "p-2",
} as const;
/**
* For anchors that read as buttons (download links, cross-page actions). A
* real <a> keeps middle-click and "open in new tab" working, which a button
* with an onClick would throw away — so those stay anchors and borrow the
* styling instead.
*/
export const LINK_BUTTON_CLASS = `${BASE} ${VARIANTS.secondary} ${SIZES.sm}`;
type ButtonProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "className"> & {
variant?: keyof typeof VARIANTS;
size?: keyof typeof SIZES;
/** Disables and shows the busy label; use for in-flight server actions. */
pending?: boolean;
pendingLabel?: string;
fullWidth?: boolean;
className?: string;
children?: ReactNode;
};
export function Button({
variant = "primary",
size,
pending = false,
pendingLabel,
fullWidth,
disabled,
className = "",
children,
type = "button",
...rest
}: ButtonProps) {
const resolvedSize = size ?? (variant === "icon" ? "icon" : "md");
return (
<button
{...rest}
type={type}
disabled={disabled || pending}
aria-busy={pending || undefined}
className={`${BASE} ${VARIANTS[variant]} ${SIZES[resolvedSize]} ${fullWidth ? "w-full" : ""} ${className}`}
>
{pending && pendingLabel ? pendingLabel : children}
</button>
);
}

View File

@@ -1,22 +1,43 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { CONTROL_CLASS } from "./Field";
type CountryPickerProps = {
value: string;
onChange: (value: string) => void;
countries: string[];
placeholder?: string;
id?: string;
"aria-describedby"?: string;
"aria-invalid"?: true;
};
const MAX_VISIBLE = 50;
// Searchable text combobox constrained to a fixed list (UN member states)
// rather than a Lookup-style "selected card" — a country is a single text
// value, not an object with its own detail fields.
export function CountryPicker({ value, onChange, countries, placeholder = "Land suchen…" }: CountryPickerProps) {
//
// Carries the full combobox contract: without role/aria-expanded/
// aria-activedescendant a screen reader announces a plain text box and never
// mentions that a list appeared, and without the key handling the list is
// reachable by mouse only.
export function CountryPicker({
value,
onChange,
countries,
placeholder = "Land suchen…",
id,
"aria-describedby": describedBy,
"aria-invalid": invalid,
}: CountryPickerProps) {
const [query, setQuery] = useState(value);
const [prevValue, setPrevValue] = useState(value);
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
// Re-sync the local draft text when `value` changes externally (e.g. the
// surrounding form loads a different employee). Adjusting state directly
@@ -38,33 +59,96 @@ export function CountryPicker({ value, onChange, countries, placeholder = "Land
return () => document.removeEventListener("mousedown", onClickOutside);
}, [value]);
const filtered = query.trim() ? countries.filter((c) => c.toLowerCase().includes(query.trim().toLowerCase())) : countries;
const filtered = (query.trim() ? countries.filter((c) => c.toLowerCase().includes(query.trim().toLowerCase())) : countries).slice(
0,
MAX_VISIBLE
);
const listId = id ? `${id}-listbox` : undefined;
const activeId = id && filtered[activeIndex] ? `${id}-option-${activeIndex}` : undefined;
function commit(country: string) {
onChange(country);
setQuery(country);
setOpen(false);
}
// Keeps the highlighted row inside the scroll container as it moves.
useEffect(() => {
if (!open) return;
listRef.current?.querySelector('[data-active="true"]')?.scrollIntoView({ block: "nearest" });
}, [activeIndex, open]);
function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
if (!open) {
setOpen(true);
setActiveIndex(0);
return;
}
const delta = e.key === "ArrowDown" ? 1 : -1;
setActiveIndex((i) => (filtered.length === 0 ? 0 : (i + delta + filtered.length) % filtered.length));
} else if (e.key === "Enter") {
if (open && filtered[activeIndex]) {
e.preventDefault();
commit(filtered[activeIndex]);
}
} else if (e.key === "Escape") {
if (open) {
// Stop here rather than letting it bubble — otherwise the dialog
// containing this field closes along with the dropdown.
e.stopPropagation();
setOpen(false);
setQuery(value);
}
}
}
return (
<div ref={containerRef} className="relative">
<input
id={id}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-activedescendant={open ? activeId : undefined}
aria-autocomplete="list"
aria-describedby={describedBy}
aria-invalid={invalid}
autoComplete="off"
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActiveIndex(0);
setOpen(true);
}}
onFocus={() => setOpen(true)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className="w-full rounded border border-border px-3 py-2 text-sm"
className={CONTROL_CLASS}
/>
{open && (
<div className="absolute z-20 mt-1 max-h-56 w-full overflow-y-auto rounded border border-border bg-white shadow-lg">
<div
ref={listRef}
id={listId}
role="listbox"
className="absolute z-20 mt-1 max-h-56 w-full overflow-y-auto rounded border border-border bg-white shadow-lg"
>
{filtered.length === 0 && <div className="px-3 py-2 text-sm text-ink-muted">Keine Treffer</div>}
{filtered.slice(0, 50).map((c) => (
{filtered.map((c, i) => (
<button
key={c}
id={id ? `${id}-option-${i}` : undefined}
role="option"
aria-selected={i === activeIndex}
data-active={i === activeIndex}
type="button"
onClick={() => {
onChange(c);
setQuery(c);
setOpen(false);
}}
className="block w-full px-3 py-2 text-left text-sm hover:bg-surface"
// Mouse down would blur the input and close the list before
// the click landed.
onMouseDown={(e) => e.preventDefault()}
onMouseEnter={() => setActiveIndex(i)}
onClick={() => commit(c)}
className={`block w-full px-3 py-2 text-left text-sm ${i === activeIndex ? "bg-brand-100 text-brand-700" : "hover:bg-surface"}`}
>
{c}
</button>

182
components/ui/Field.tsx Normal file
View File

@@ -0,0 +1,182 @@
"use client";
import { useId, type ReactNode, type SelectHTMLAttributes, type InputHTMLAttributes, type TextareaHTMLAttributes } from "react";
// Form primitives.
//
// Before these existed the same class chain was written out by hand at 85
// call sites, each with a bare `<label>` next to a bare `<input>` and no
// connection between them — 92 labels, 4 of which used htmlFor, and not a
// single input carried an id. Screen readers announced an unnamed edit box
// and clicking a label focused nothing. Generating the id here makes that
// impossible to get wrong, and gives every field one place to fix focus
// styling, error display and sizing.
export const CONTROL_CLASS =
"w-full rounded border border-border bg-white px-3 py-2 text-sm text-ink " +
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-brand-500 " +
"disabled:cursor-not-allowed disabled:bg-surface disabled:text-ink-muted";
const INVALID_CLASS = "border-danger-solid";
/** Auto-width select for filter bars, where the label is an aria-label. */
export const FILTER_SELECT_CLASS =
"rounded border border-border bg-white px-3 py-2 text-sm text-ink " +
"focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-brand-500";
type FieldChildProps = {
id: string;
"aria-describedby": string | undefined;
"aria-invalid": true | undefined;
};
type FieldShellProps = {
label: string;
/** Marks the label and sets required on the control. */
required?: boolean;
/** Helper text below the control; announced with the field. */
hint?: string;
/** Replaces the hint when set and marks the control invalid. */
error?: string | null;
/** Smaller label, used inside dense side panels. */
dense?: boolean;
className?: string;
};
/**
* Escape hatch for controls this module does not wrap (Lookup, CountryPicker,
* Picklist). Hands the wiring to the caller instead of guessing at it:
*
* <Field label="Land">{(p) => <CountryPicker {...p} … />}</Field>
*/
export function Field({
label,
required,
hint,
error,
dense,
className,
children,
}: FieldShellProps & { children: (props: FieldChildProps) => ReactNode }) {
const id = useId();
const messageId = `${id}-message`;
const message = error ?? hint;
return (
<div className={className}>
<label htmlFor={id} className={dense ? "mb-1 block text-xs font-semibold text-ink-muted" : "mb-1 block text-sm font-semibold text-ink"}>
{label}
{required && <span aria-hidden> *</span>}
{required && <span className="sr-only"> (Pflichtfeld)</span>}
</label>
{children({
id,
"aria-describedby": message ? messageId : undefined,
"aria-invalid": error ? true : undefined,
})}
{message && (
<p id={messageId} className={`mt-1 text-xs ${error ? "font-semibold text-danger-text" : "text-ink-muted"}`}>
{message}
</p>
)}
</div>
);
}
type TextFieldProps = FieldShellProps &
Omit<InputHTMLAttributes<HTMLInputElement>, "onChange" | "id" | "className"> & {
value: string;
/** Receives the value directly — every call site wanted e.target.value. */
onChange: (value: string) => void;
};
export function TextField({ label, required, hint, error, dense, className, value, onChange, ...rest }: TextFieldProps) {
return (
<Field label={label} required={required} hint={hint} error={error} dense={dense} className={className}>
{(p) => (
<input
{...p}
{...rest}
required={required}
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${CONTROL_CLASS} ${error ? INVALID_CLASS : ""}`}
/>
)}
</Field>
);
}
type Option = { value: string; label: string; disabled?: boolean };
type SelectFieldProps = FieldShellProps &
Omit<SelectHTMLAttributes<HTMLSelectElement>, "onChange" | "id" | "className" | "children"> & {
value: string;
onChange: (value: string) => void;
options: readonly Option[];
/** Prepends a disabled placeholder, for "Bitte wählen…" selects. */
placeholder?: string;
};
export function SelectField({
label,
required,
hint,
error,
dense,
className,
value,
onChange,
options,
placeholder,
...rest
}: SelectFieldProps) {
return (
<Field label={label} required={required} hint={hint} error={error} dense={dense} className={className}>
{(p) => (
<select
{...p}
{...rest}
required={required}
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${CONTROL_CLASS} ${error ? INVALID_CLASS : ""}`}
>
{placeholder && (
<option value="" disabled>
{placeholder}
</option>
)}
{options.map((o) => (
<option key={o.value} value={o.value} disabled={o.disabled}>
{o.label}
</option>
))}
</select>
)}
</Field>
);
}
type TextareaFieldProps = FieldShellProps &
Omit<TextareaHTMLAttributes<HTMLTextAreaElement>, "onChange" | "id" | "className"> & {
value: string;
onChange: (value: string) => void;
};
export function TextareaField({ label, required, hint, error, dense, className, value, onChange, ...rest }: TextareaFieldProps) {
return (
<Field label={label} required={required} hint={hint} error={error} dense={dense} className={className}>
{(p) => (
<textarea
{...p}
{...rest}
required={required}
value={value}
onChange={(e) => onChange(e.target.value)}
className={`${CONTROL_CLASS} ${error ? INVALID_CLASS : ""}`}
/>
)}
</Field>
);
}

View File

@@ -1,7 +1,7 @@
"use client";
import { Search, X } from "lucide-react";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
type LookupProps<T> = {
placeholder?: string;
@@ -9,21 +9,42 @@ type LookupProps<T> = {
renderResult: (item: T) => ReactNode;
onSelect: (item: T) => void;
minChars?: number;
id?: string;
"aria-describedby"?: string;
"aria-invalid"?: true;
};
// Generic async search-select used by the position lookup (hire wizard),
// manager/superior lookup (create position), and employee multi-select
// (reorg workbench) in later phases.
export function Lookup<T>({ placeholder = "Suchen…", onSearch, renderResult, onSelect, minChars = 2 }: LookupProps<T>) {
// manager/superior lookup (create position), and the reorg workbench.
//
// Implements the combobox contract rather than just looking like one: it was
// a plain text input with a div of clickable buttons underneath, so a
// keyboard user could type but never reach a result, and a screen reader was
// never told a list had appeared. Arrow keys move the selection, Enter takes
// it, Escape closes without also closing the surrounding dialog.
export function Lookup<T>({
placeholder = "Suchen…",
onSearch,
renderResult,
onSelect,
minChars = 2,
id: idProp,
"aria-describedby": describedBy,
"aria-invalid": invalid,
}: LookupProps<T>) {
const generatedId = useId();
const id = idProp ?? generatedId;
const [query, setQuery] = useState("");
const [results, setResults] = useState<T[]>([]);
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(0);
// Derived from "have we finished searching for the current query yet",
// rather than a separate state flag flipped synchronously at the top of
// the effect below — the effect only ever sets state from the async
// search's own completion callback now.
const [lastSearchedQuery, setLastSearchedQuery] = useState<string | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const tooShort = query.trim().length < minChars;
const loading = !tooShort && lastSearchedQuery !== query.trim();
@@ -35,6 +56,7 @@ export function Lookup<T>({ placeholder = "Suchen…", onSearch, renderResult, o
onSearch(query.trim()).then((res) => {
if (cancelled) return;
setResults(res);
setActiveIndex(0);
setOpen(true);
setLastSearchedQuery(query.trim());
});
@@ -50,6 +72,7 @@ export function Lookup<T>({ placeholder = "Suchen…", onSearch, renderResult, o
// needing a synchronous setState inside the effect above.
const showDropdown = open && !tooShort;
const visibleResults = tooShort ? [] : results;
const selectable = loading ? [] : visibleResults;
useEffect(() => {
function onClickOutside(e: MouseEvent) {
@@ -61,46 +84,100 @@ export function Lookup<T>({ placeholder = "Suchen…", onSearch, renderResult, o
return () => document.removeEventListener("mousedown", onClickOutside);
}, []);
useEffect(() => {
if (!showDropdown) return;
listRef.current?.querySelector('[data-active="true"]')?.scrollIntoView({ block: "nearest" });
}, [activeIndex, showDropdown]);
function reset() {
setQuery("");
setResults([]);
setOpen(false);
setActiveIndex(0);
}
function choose(item: T) {
onSelect(item);
reset();
}
function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
if (selectable.length === 0) return;
e.preventDefault();
const delta = e.key === "ArrowDown" ? 1 : -1;
setActiveIndex((i) => (i + delta + selectable.length) % selectable.length);
} else if (e.key === "Enter") {
if (showDropdown && selectable[activeIndex]) {
e.preventDefault();
choose(selectable[activeIndex]);
}
} else if (e.key === "Escape") {
if (showDropdown) {
// Without this the Escape also reaches Modal/SlideOver and closes
// the whole dialog behind the dropdown.
e.stopPropagation();
setOpen(false);
}
}
}
const listId = `${id}-listbox`;
return (
<div ref={containerRef} className="relative">
<div className="flex items-center gap-2 rounded border border-border bg-white px-3 py-2">
<Search className="h-4 w-4 shrink-0 text-ink-muted" />
<div className="flex items-center gap-2 rounded border border-border bg-white px-3 py-2 focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-brand-500">
<Search className="h-4 w-4 shrink-0 text-ink-muted" aria-hidden />
<input
id={id}
role="combobox"
aria-expanded={showDropdown}
aria-controls={listId}
aria-activedescendant={showDropdown && selectable[activeIndex] ? `${id}-option-${activeIndex}` : undefined}
aria-autocomplete="list"
aria-describedby={describedBy}
aria-invalid={invalid}
autoComplete="off"
value={query}
onChange={(e) => setQuery(e.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className="w-full text-sm outline-none placeholder:text-ink-muted"
/>
{query && (
<button
type="button"
onClick={() => {
setQuery("");
setResults([]);
setOpen(false);
}}
aria-label="Zurücksetzen"
>
<button type="button" onClick={reset} aria-label="Zurücksetzen" className="rounded p-0.5 hover:bg-surface">
<X className="h-4 w-4 text-ink-muted" />
</button>
)}
</div>
{/* Announces "Suche…" / result count without stealing focus. */}
<span aria-live="polite" className="sr-only">
{showDropdown ? (loading ? "Suche läuft" : `${visibleResults.length} Treffer`) : ""}
</span>
{showDropdown && (
<div className="absolute z-20 mt-1 max-h-64 w-full overflow-y-auto rounded border border-border bg-white shadow-lg">
<div
ref={listRef}
id={listId}
role="listbox"
className="absolute z-20 mt-1 max-h-64 w-full overflow-y-auto rounded border border-border bg-white shadow-lg"
>
{loading && <div className="px-3 py-2 text-sm text-ink-muted">Suche</div>}
{!loading && visibleResults.length === 0 && <div className="px-3 py-2 text-sm text-ink-muted">Keine Treffer</div>}
{!loading &&
visibleResults.map((item, i) => (
<button
key={i}
id={`${id}-option-${i}`}
role="option"
aria-selected={i === activeIndex}
data-active={i === activeIndex}
type="button"
onClick={() => {
onSelect(item);
setQuery("");
setResults([]);
setOpen(false);
}}
className="block w-full px-3 py-2 text-left text-sm hover:bg-surface"
// Mouse down would blur the input and close the list before
// the click landed.
onMouseDown={(e) => e.preventDefault()}
onMouseEnter={() => setActiveIndex(i)}
onClick={() => choose(item)}
className={`block w-full px-3 py-2 text-left text-sm ${i === activeIndex ? "bg-brand-100" : "hover:bg-surface"}`}
>
{renderResult(item)}
</button>

View File

@@ -1,7 +1,9 @@
"use client";
import { X } from "lucide-react";
import { useEffect, type ReactNode } from "react";
import { useId, useRef, type ReactNode } from "react";
import { Button } from "./Button";
import { useDialogFocus } from "./useDialogFocus";
type ModalProps = {
open: boolean;
@@ -13,14 +15,9 @@ type ModalProps = {
};
export function Modal({ open, onClose, title, children, footer, widthClassName = "max-w-lg" }: ModalProps) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onClose]);
const dialogRef = useRef<HTMLDivElement>(null);
const titleId = useId();
useDialogFocus(open, onClose, dialogRef);
if (!open) return null;
@@ -29,16 +26,22 @@ export function Modal({ open, onClose, title, children, footer, widthClassName =
// a field is focused), centred from sm up.
<div className="fixed inset-0 z-50 flex items-end justify-center bg-black/40 p-0 sm:items-center sm:p-4">
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label={title}
className={`flex max-h-[92dvh] w-full flex-col rounded-t-xl bg-white shadow-xl sm:max-h-[85dvh] sm:rounded ${widthClassName}`}
// Points at the real heading rather than duplicating the string, so
// the accessible name cannot drift from what is on screen.
aria-labelledby={titleId}
tabIndex={-1}
className={`flex max-h-[92dvh] w-full flex-col rounded-t-xl bg-white shadow-xl outline-none sm:max-h-[85dvh] sm:rounded ${widthClassName}`}
>
<div className="flex shrink-0 items-center justify-between border-b border-border px-4 py-3 sm:px-6 sm:py-4">
<h2 className="text-lg font-bold text-ink">{title}</h2>
<button type="button" onClick={onClose} aria-label="Schließen" className="-mr-1 rounded p-2 text-ink-muted hover:bg-surface">
<h2 id={titleId} className="text-lg font-bold text-ink">
{title}
</h2>
<Button variant="icon" onClick={onClose} aria-label="Schließen" className="-mr-1">
<X className="h-5 w-5" />
</button>
</Button>
</div>
<div className="flex-1 overflow-y-auto overscroll-contain px-4 py-4 sm:px-6">{children}</div>
{footer && (

View File

@@ -1,6 +1,7 @@
"use client";
import { X } from "lucide-react";
import { CONTROL_CLASS } from "./Field";
// Dropdown-to-add, chip-to-remove multi-select for short, fixed option
// lists (no search needed) — e.g. academic titles. The dropdown only offers
@@ -11,11 +12,16 @@ export function Picklist({
value,
onChange,
placeholder = "Hinzufügen…",
// Forwarded onto the <select> so a surrounding <Field> can label it.
id,
"aria-describedby": describedBy,
}: {
options: string[];
value: string[];
onChange: (value: string[]) => void;
placeholder?: string;
id?: string;
"aria-describedby"?: string;
}) {
const available = options.filter((o) => !value.includes(o));
@@ -27,12 +33,14 @@ export function Picklist({
<div className="flex flex-col gap-2">
<select
key={value.length}
id={id}
aria-describedby={describedBy}
defaultValue=""
onChange={(e) => {
if (e.target.value) onChange([...value, e.target.value]);
}}
disabled={available.length === 0}
className="w-full rounded border border-border px-3 py-2 text-sm disabled:bg-surface disabled:text-ink-muted"
className={CONTROL_CLASS}
>
<option value="" disabled>
{available.length > 0 ? placeholder : "Alle Optionen ausgewählt"}

View File

@@ -0,0 +1,45 @@
"use client";
import { Search } from "lucide-react";
import { useId } from "react";
// The icon-in-a-box search field used by the employee list, the audit log and
// the org chart. Each was a hand-rolled copy whose <input> carried only a
// placeholder — no label at all — and killed its own focus ring with
// outline-none. A placeholder is not a label: it disappears on the first
// keystroke and is not reliably announced.
export function SearchInput({
value,
onChange,
placeholder,
label,
className = "",
}: {
value: string;
onChange: (value: string) => void;
placeholder: string;
/** Visually hidden; this is what a screen reader announces. */
label: string;
className?: string;
}) {
const id = useId();
return (
<div
className={`flex min-w-[240px] flex-1 items-center gap-2 rounded border border-border bg-white px-3 py-2 focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-brand-500 ${className}`}
>
<Search className="h-4 w-4 shrink-0 text-ink-muted" aria-hidden />
<label htmlFor={id} className="sr-only">
{label}
</label>
<input
id={id}
type="search"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
// The ring lives on the wrapper so it encloses the icon too.
className="w-full text-sm text-ink outline-none placeholder:text-ink-muted"
/>
</div>
);
}

View File

@@ -1,7 +1,9 @@
"use client";
import { X } from "lucide-react";
import { useEffect, type ReactNode } from "react";
import { useId, useRef, type ReactNode } from "react";
import { Button } from "./Button";
import { useDialogFocus } from "./useDialogFocus";
type SlideOverProps = {
open: boolean;
@@ -13,37 +15,41 @@ type SlideOverProps = {
};
export function SlideOver({ open, onClose, title, subtitle, children, footer }: SlideOverProps) {
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onClose]);
const dialogRef = useRef<HTMLDivElement>(null);
const titleId = useId();
useDialogFocus(open, onClose, dialogRef);
return (
<div className={`fixed inset-0 z-50 ${open ? "pointer-events-auto" : "pointer-events-none"}`} aria-hidden={!open}>
// Stays mounted so the slide transition can run, which means a closed
// panel's fields are still in the tab order — aria-hidden does not remove
// them. `inert` does, and also blocks clicks, so several closed panels no
// longer pile up invisible tab stops at the end of the page.
<div className="fixed inset-0 z-50" inert={!open}>
<div
className={`absolute inset-0 bg-black/40 transition-opacity ${open ? "opacity-100" : "opacity-0"}`}
onClick={onClose}
aria-hidden
/>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label={title}
className={`absolute right-0 top-0 flex h-dvh w-full max-w-md flex-col bg-white shadow-xl transition-transform duration-200 ${
aria-labelledby={titleId}
tabIndex={-1}
className={`absolute right-0 top-0 flex h-dvh w-full max-w-md flex-col bg-white shadow-xl outline-none transition-transform duration-200 ${
open ? "translate-x-0" : "translate-x-full"
}`}
>
<div className="flex shrink-0 items-start justify-between border-b border-border px-4 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] sm:px-6 sm:py-4">
<div className="min-w-0">
<h2 className="text-lg font-bold text-ink">{title}</h2>
<h2 id={titleId} className="text-lg font-bold text-ink">
{title}
</h2>
{subtitle && <p className="truncate text-sm text-ink-muted">{subtitle}</p>}
</div>
<button type="button" onClick={onClose} aria-label="Schließen" className="-mr-1 rounded p-2 text-ink-muted hover:bg-surface">
<Button variant="icon" onClick={onClose} aria-label="Schließen" className="-mr-1">
<X className="h-5 w-5" />
</button>
</Button>
</div>
<div className="flex-1 overflow-y-auto overscroll-contain px-4 py-4 sm:px-6">{children}</div>
{footer && (

View File

@@ -0,0 +1,78 @@
"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. Both previously handled only Escape: focus stayed on
// whatever was behind the overlay, Tab walked straight out of the dialog into
// the page underneath, and closing left focus on <body> — so the next Tab
// started 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);
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") {
onClose();
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, onClose, containerRef]);
}