Files
alpenwerk-hr/components/orgchart/EmployeeTree.tsx
Maximilian Stubhan d9367a8ce4 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.
2026-07-25 13:11:09 +02:00

189 lines
7.8 KiB
TypeScript

"use client";
import { ChevronDown, ChevronRight } from "lucide-react";
import Link from "next/link";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Avatar } from "@/components/ui/Avatar";
import { Button } from "@/components/ui/Button";
import { SearchInput } from "@/components/ui/SearchInput";
import { SegmentedControl } from "@/components/ui/SegmentedControl";
import { LazyGraphOrgChart } from "./LazyGraphOrgChart";
import type { ChartNode, OrgEmployee } from "./types";
type ViewMode = "list" | "graph";
export function EmployeeTree({ employees, focusId = null }: { employees: OrgEmployee[]; focusId?: string | null }) {
// Seeded with the focus target so their own reports are already unfolded;
// the chain *above* them comes from ancestorExpandIds.
const [expanded, setExpanded] = useState<Set<string>>(() => (focusId ? new Set([focusId]) : new Set()));
const [query, setQuery] = useState("");
const [mode, setMode] = useState<ViewMode>("list");
const focusRef = useRef<HTMLDivElement>(null);
const { childrenByManager, totalReportsById, root } = useMemo(() => {
const byManager = new Map<string, OrgEmployee[]>();
for (const e of employees) {
const key = e.manager_id ?? "__root__";
if (!byManager.has(key)) byManager.set(key, []);
byManager.get(key)!.push(e);
}
for (const list of byManager.values()) list.sort((a, b) => a.last_name.localeCompare(b.last_name));
// Nothing in the schema forbids a manager_id cycle (A reports to B
// reports to A), and a reorg that moves a lead under one of their own
// reports would create one. Every walk below is recursive, so an
// unguarded cycle is an infinite recursion that hangs the tab rather
// than a wrong number — hence the on-path set.
const totals = new Map<string, number>();
function countTotal(id: string, path: Set<string>): number {
const memo = totals.get(id);
if (memo !== undefined) return memo;
if (path.has(id)) return 0;
path.add(id);
let total = 0;
for (const child of byManager.get(id) ?? []) total += 1 + countTotal(child.id, path);
path.delete(id);
totals.set(id, total);
return total;
}
for (const e of employees) countTotal(e.id, new Set());
return { childrenByManager: byManager, totalReportsById: totals, root: byManager.get("__root__") ?? [] };
}, [employees]);
const matchIds = useMemo(() => {
// A focus target behaves exactly like a search hit — same ancestor
// auto-expand, same ring, same fitView in graph mode — until the user
// starts typing, at which point their own search takes over.
if (query.trim().length < 2) return focusId ? new Set([focusId]) : null;
const q = query.trim().toLowerCase();
const matches = new Set<string>();
for (const e of employees) {
if (
`${e.first_name} ${e.last_name}`.toLowerCase().includes(q) ||
e.job_title.toLowerCase().includes(q) ||
String(e.personnel_number).includes(q)
) {
matches.add(e.id);
}
}
return matches;
}, [query, employees, focusId]);
// The chain above the focused person is auto-expanded, so the row only
// exists after that render — scroll once it does.
useEffect(() => {
if (!focusId) return;
focusRef.current?.scrollIntoView({ block: "center", behavior: "smooth" });
}, [focusId, mode]);
const ancestorExpandIds = useMemo(() => {
if (!matchIds) return null;
const byId = new Map(employees.map((e) => [e.id, e]));
const toExpand = new Set<string>();
for (const id of matchIds) {
let current = byId.get(id);
while (current?.manager_id && !toExpand.has(current.manager_id)) {
toExpand.add(current.manager_id);
current = byId.get(current.manager_id);
}
}
return toExpand;
}, [matchIds, employees]);
// useCallback-stable: GraphOrgChart's layout memo depends on this
// reference, so an unstable function would force a Dagre re-layout on
// every unrelated re-render.
const toggle = useCallback((id: string) => {
setExpanded((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}, []);
const isExpanded = useCallback((id: string): boolean => expanded.has(id) || (ancestorExpandIds?.has(id) ?? false), [expanded, ancestorExpandIds]);
const chartTree = useMemo<ChartNode[]>(() => {
function toChartNode(e: OrgEmployee, ancestors: Set<string>): ChartNode {
const children = ancestors.has(e.id) ? [] : (childrenByManager.get(e.id) ?? []);
const total = totalReportsById.get(e.id) ?? 0;
const nextAncestors = new Set(ancestors).add(e.id);
return {
id: e.id,
kind: "person",
label: `${e.first_name} ${e.last_name}`,
sublabel: e.job_title,
href: `/employees/${e.id}`,
avatar: { firstName: e.first_name, lastName: e.last_name },
totalReports: total,
matched: matchIds?.has(e.id) ?? false,
children: children.map((c) => toChartNode(c, nextAncestors)),
};
}
return root.map((r) => toChartNode(r, new Set()));
}, [root, childrenByManager, totalReportsById, matchIds]);
function renderNode(e: OrgEmployee, depth: number, ancestors: Set<string>) {
const children = ancestors.has(e.id) ? [] : (childrenByManager.get(e.id) ?? []);
const hasChildren = children.length > 0;
const expandedNow = isExpanded(e.id);
const isMatch = matchIds?.has(e.id) ?? false;
const totalReports = totalReportsById.get(e.id) ?? 0;
return (
<div key={e.id}>
<div
ref={e.id === focusId ? focusRef : undefined}
className={`flex items-center gap-2 rounded px-2 py-1.5 hover:bg-surface ${isMatch ? "bg-brand-100" : ""}`}
style={{ paddingLeft: depth * 24 + 8 }}
>
{hasChildren ? (
<button type="button" onClick={() => toggle(e.id)} className="shrink-0 text-ink-muted">
{expandedNow ? <ChevronDown className="h-4 w-4" /> : <ChevronRight className="h-4 w-4" />}
</button>
) : (
<span className="w-4 shrink-0" />
)}
<Avatar firstName={e.first_name} lastName={e.last_name} size="sm" />
<Link href={`/employees/${e.id}`} className="flex-1 hover:underline">
<span className="text-sm font-semibold text-ink">
{e.first_name} {e.last_name}
</span>
<span className="ml-2 text-xs text-ink-muted">{e.job_title}</span>
</Link>
{hasChildren && (
<span className="shrink-0 text-xs text-ink-muted">
{children.length} direkt · {totalReports} gesamt
</span>
)}
</div>
{hasChildren && expandedNow && (
<div>{children.map((c) => renderNode(c, depth + 1, new Set(ancestors).add(e.id)))}</div>
)}
</div>
);
}
return (
<div className="rounded border border-border bg-white p-4">
<div className="mb-4 flex flex-wrap items-center gap-3">
<SearchInput label="Organigramm durchsuchen" placeholder="Name, Pers.-Nr., Titel…" value={query} onChange={setQuery} />
<Button variant="secondary" size="sm" onClick={() => setExpanded(new Set(root.map((r) => r.id)))}>
Bereiche anzeigen
</Button>
<Button variant="secondary" size="sm" onClick={() => setExpanded(new Set())}>
Alles einklappen
</Button>
<SegmentedControl<ViewMode> value={mode} onChange={setMode} options={[{ value: "list", label: "Liste" }, { value: "graph", label: "Grafisch" }]} />
</div>
{mode === "list" ? (
<div>{root.map((r) => renderNode(r, 0, new Set()))}</div>
) : (
<LazyGraphOrgChart tree={chartTree} isExpanded={isExpanded} onToggle={toggle} matchedIds={matchIds} />
)}
</div>
);
}