Files
alpenwerk-hr/components/ui/Lookup.tsx
Raphael Müllner 643fd79f88 Übergabestand 2026-10-29
Alpenwerk HR 0.1.0

Betrieb auf Windows Server
- Die Anwendung läuft im IIS (HttpPlatformHandler) unter dem Konto des Anwendungspools, ohne Administratorrechte und ohne eigenen Windows-Dienst
- Das Zertifikat kommt aus dem Zertifikatsspeicher; die Bindung folgt jeder Erneuerung automatisch
- Neue Versionen mit aktualisieren.ps1 -Paket <zip>, mit Sicherung vorab; Rückstieg mit zuruecksetzen.ps1
- HR-Zugang für ganze Domains mit freischalten.ps1 -Domain; Einzelsperren haben Vorrang
- Anmeldung ausschließlich über Microsoft Entra ID
- Das Windows-Paket hängt an jedem Release

Fachliche Erweiterungen
- Änderungen per Austauschdatei importieren, mit Vorschau, Prüfung und Fehlerdatei
- Einstellung: eigene Maske für externe Personen, Übernahme von Leiharbeitskräften, Planstellen zum Eintrittstag
- Organisationsstruktur: Einheiten und Kostenstellen anlegen, umbenennen und abschließen; Suche nach Planstelle, Einheit und Kostenstelle
- Historie: Austritt, Versetzung und Eintritt berichtigen oder zurücknehmen; Planstelle mit Bezeichnung
- Abwesenheiten ohne Ende, geplante Abwesenheiten mit Art, Checklisten mit Anlass, auch zur Rückkehr
- Berichte mit Mehrfachauswahl in allen Kriterien; Kostenstelle als Filter und Gruppierung
- Stammdaten: mehrere Notfallkontakte, Lehrzeit, Ferialkraft, Altersteilzeit, erweiterte Beschäftigtengruppen und Geschlechtsangaben
2026-10-29 19:21:21 +01:00

232 lines
8.3 KiB
TypeScript

"use client";
import { Search, X } from "lucide-react";
import { useEffect, useId, useRef, useState, type KeyboardEvent, type ReactNode } from "react";
type LookupProps<T> = {
placeholder?: string;
onSearch: (query: string) => Promise<T[]>;
renderResult: (item: T) => ReactNode;
onSelect: (item: T) => void;
minChars?: number;
/**
* Die Lupe öffnet die ganze Liste: onSearch("") liefert dann alles, und
* Tippen grenzt weiter ein. Für Auswahlen, deren Bestand überschaubar ist
* und die man durchsehen statt erraten will — die offenen Planstellen.
*/
alleAnzeigen?: boolean;
id?: string;
"aria-describedby"?: string;
"aria-invalid"?: true;
};
// Generic async search-select used by the Planstelle, Einheit and
// Kostenstelle pickers (components/positions).
//
// Implements the combobox contract rather than just looking like one:
// without it a keyboard user could type but never reach a result, and a
// screen reader would never be 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,
alleAnzeigen = false,
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.
const [lastSearchedQuery, setLastSearchedQuery] = useState<string | null>(null);
// Ob die Liste über die Lupe geöffnet wurde. Solange das gilt, ist auch
// eine leere oder kurze Eingabe eine Suche — sie zeigt alles.
const [durchsehen, setDurchsehen] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const listRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const tooShort = !durchsehen && query.trim().length < minChars;
const loading = !tooShort && lastSearchedQuery !== query.trim();
useEffect(() => {
if (tooShort) return;
let cancelled = false;
const timeout = setTimeout(() => {
onSearch(query.trim()).then((res) => {
if (cancelled) return;
setResults(res);
setActiveIndex(0);
setOpen(true);
setLastSearchedQuery(query.trim());
});
}, 200);
return () => {
cancelled = true;
clearTimeout(timeout);
};
}, [query, minChars, onSearch, tooShort]);
// Derived rather than reset via effect: once the query drops below
// minChars, hide the dropdown and any stale results immediately without
// 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) {
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
setOpen(false);
}
}
document.addEventListener("mousedown", onClickOutside);
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);
setDurchsehen(false);
}
function allesZeigen() {
if (durchsehen && lastSearchedQuery === query.trim()) {
// Liegt das Ergebnis schon vor, löst die Lupe keine neue Suche aus —
// sie öffnet nur wieder, was ein Klick daneben geschlossen hat.
setOpen(true);
}
setDurchsehen(true);
inputRef.current?.focus();
}
function choose(item: T) {
onSelect(item);
reset();
}
function onKeyDown(e: KeyboardEvent<HTMLInputElement>) {
if (e.key === "ArrowDown" && alleAnzeigen && !showDropdown) {
// Pfeil nach unten öffnet die Liste — dieselbe Wirkung wie die Lupe,
// für die Arbeit mit der Tastatur.
e.preventDefault();
allesZeigen();
return;
}
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-strong bg-white px-3 py-2 focus-within:outline-2 focus-within:outline-offset-1 focus-within:outline-brand-500">
{alleAnzeigen ? (
<button
type="button"
onClick={allesZeigen}
aria-label="Alle anzeigen"
title="Alle anzeigen"
className="rounded p-0.5 hover:bg-surface"
>
<Search className="h-4 w-4 shrink-0 text-ink-muted" aria-hidden />
</button>
) : (
<Search className="h-4 w-4 shrink-0 text-ink-muted" aria-hidden />
)}
<input
ref={inputRef}
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={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
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-[var(--shadow-card-hover)]"
>
{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"
// 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>
))}
</div>
)}
</div>
);
}