Files
tsumugu/frontend/src/pages/content.jsx
T
LarsandCursor 7e39fbb2bd
Deploy Development / deploy (push) Successful in 41s
Test Suite / pytest-backend (push) Failing after 2m55s
Test Suite / smoke-dev (push) Successful in 0s
Test Suite / frontend-build (push) Successful in 23s
Mache große IMAP-Fächer, die Paperless-Suche und die interne Markdown-Notiz über die gemeinsamen Schnittstellen benutzbar.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-20 07:34:14 +02:00

2852 lines
111 KiB
React
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { Link } from "react-router-dom";
import { api, fetchExternal, fetchFile } from "../api.js";
import { moduleFor } from "../sources/registry-core.js";
import { contentSourceSymbol, contentSymbol, symbolUrl } from "../content-symbol.mjs";
import { bezugCount, counterpartLabel, directionSymbol } from "../list-meta.mjs";
import { NoteEditor } from "../notes.jsx";
import { NavIcon } from "./icons.jsx";
import { Modal } from "./Modal.jsx";
import { ErrorNote } from "./widgets.jsx";
import {
buildChapterSections,
chapterPathLabel,
countLabel,
descendantChapterIds,
findSection,
sectionCounts,
siblingChapterIds,
} from "./chapters.js";
import {
Chronology,
DispatchDialog,
EvidenceDialog,
hostMark,
restoreFold,
scopeBody,
StructureAssignDialog,
UnitDetail,
} from "./correspondence.jsx";
export function formatDate(value) {
if (!value) return "Ohne Datum";
const [year, month, day] = String(value).slice(0, 10).split("-");
if (!year || !month || !day) return String(value);
return `${day}.${month}.${year}`;
}
function completeDate(value) {
return /^\d{4}-\d{2}-\d{2}$/.test(value || "");
}
export function DateField({ value = "", onChange, disabled = false, ...rest }) {
const ref = useRef(null);
const committed = useRef(value || "");
// Chromium setzt bei einem gesteuerten Datumsfeld nach jeder Ziffer `value`
// neu. Die Jahresstelle springt dann auf eine einstellige Zahl wie 0002
// und der Fokus verlässt das Feld. Das Feld bleibt deshalb ungesteuert.
useEffect(() => {
const next = value || "";
const node = ref.current;
if (node && document.activeElement === node) return;
committed.current = next;
if (node && node.value !== next) node.value = next;
}, [value]);
function commit(next) {
if (next === committed.current) return;
committed.current = next;
onChange(next);
}
function commitFrom(node) {
if (node.validity?.badInput) {
node.value = committed.current || "";
return;
}
const next = node.value || "";
if (next && !completeDate(next)) return;
commit(next);
}
return (
<input
{...rest}
ref={ref}
type="date"
defaultValue={value || ""}
disabled={disabled}
autoComplete="off"
onChange={(event) => {
if (completeDate(event.target.value)) commit(event.target.value);
}}
onBlur={(event) => commitFrom(event.target)}
/>
);
}
export function formatStamp(value) {
if (!value) return "";
const [day, time = ""] = String(value).split("T");
return `${formatDate(day)} ${time.replace("Z", " UTC").slice(0, 8)}`.trim();
}
export function selectionOf(params) {
return {
scope: params.get("bereich") || "all",
chapterId: params.get("kapitel") || "",
};
}
export function writeSelection(params, setParams, scope, chapterId) {
const next = new URLSearchParams(params);
if (!scope || scope === "all") next.delete("bereich");
else next.set("bereich", scope);
if (chapterId) next.set("kapitel", chapterId);
else next.delete("kapitel");
setParams(next, { replace: true });
}
export function writeChapter(params, setParams, chapterId) {
const next = new URLSearchParams(params);
if (chapterId) next.set("kapitel", chapterId);
else next.delete("kapitel");
setParams(next, { replace: true });
}
export function withSelection(href, params) {
const url = new URL(href, "http://tsumugu.local");
for (const key of ["bereich", "kapitel"]) {
const value = params.get(key);
if (value && !url.searchParams.has(key)) url.searchParams.set(key, value);
}
const search = url.searchParams.toString();
return `${url.pathname}${search ? `?${search}` : ""}`;
}
export function TargetLine({ label, chapters = [], chapterId = "", chapterTitle = "" }) {
if (!label) return null;
const chapter = chapters.find((item) => item.id === chapterId);
const namedChapter = chapter ? chapterPathLabel(chapters, chapter.id) : chapterTitle;
return (
<p className="target-line">
Ziel: <strong>{label}</strong>
{namedChapter ? <> · Kapitel <strong>{namedChapter}</strong></> : null}
</p>
);
}
export function kindLabel(kind) {
if (kind === "note") return "Notiz";
if (kind === "file") return "Datei";
if (kind === "external_ref") return "Paperless";
return "Unterlage";
}
export function fachDate(element) {
return element?.dates?.document_on || null;
}
export function Trail({ items }) {
const [open, setOpen] = useState(false);
if (!items?.length) return null;
const long = items.length > 2;
const shown = long && !open ? [items[0], null, items[items.length - 1]] : items;
return (
<nav className="trail" aria-label="Pfad">
{shown.map((item, index) => (
<span key={item ? `${item.label}-${index}` : `ellipsis-${index}`}>
{index ? <span className="trail__sep" aria-hidden="true">/</span> : null}
{item ? (
item.href ? <Link to={item.href}>{item.label}</Link> : <span aria-current="page">{item.label}</span>
) : (
<span aria-hidden="true">…</span>
)}
</span>
))}
{long ? (
<button type="button" className="trail__more" aria-expanded={open} onClick={() => setOpen((value) => !value)}>
{open ? "Pfad kürzen" : "Pfad vollständig"}
</button>
) : null}
</nav>
);
}
export function nestRecords(items, parentKey) {
const ids = new Set((items || []).map((item) => item.id));
const children = new Map();
const roots = [];
for (const item of items || []) {
const parentId = item[parentKey];
if (parentId && ids.has(parentId)) {
const list = children.get(parentId) || [];
list.push(item);
children.set(parentId, list);
} else {
roots.push(item);
}
}
return { roots, children };
}
function TreeBranch({ item, children, hrefFor, nested }) {
const kids = children.get(item.id) || [];
return (
<li>
<Link className="hierarchy__row" to={hrefFor(item)}>
<span className="hierarchy__kind">{item.kind_label || "Eintrag"}</span>
<strong>{item.title}</strong>
{!nested && item.parent_title ? <span className="muted">in {item.parent_title}</span> : null}
<span className="muted">{item.status === "open" ? "Offen" : item.status === "closed" ? "Geschlossen" : ""}</span>
</Link>
{kids.length ? (
<ul>
{kids.map((child) => (
<TreeBranch key={child.id} item={child} children={children} hrefFor={hrefFor} nested />
))}
</ul>
) : null}
</li>
);
}
export function RecordTree({ items, parentKey, hrefFor }) {
const { roots, children } = nestRecords(items, parentKey);
if (!roots.length) return null;
return (
<ul className="hierarchy">
{roots.map((item) => (
<TreeBranch key={item.id} item={item} children={children} hrefFor={hrefFor} nested={false} />
))}
</ul>
);
}
function looseSection(loose, chapters) {
if (chapters.length && loose.length) {
return { id: "loose", title: "Ohne Kapitel", documentOn: "", parentId: "", items: loose, children: [] };
}
if (!chapters.length) {
return { id: "loose", title: "", documentOn: "", parentId: "", items: loose, children: [] };
}
return null;
}
export function matterOpenHref(item) {
const cases = (item?.contexts || []).filter((entry) => entry.kind === "case");
if (cases.length === 1) return `/matters/${item.id}?context_kind=case&context_id=${cases[0].id}`;
return `/matters/${item.id}`;
}
export function Placements({ items }) {
if (!items?.length) return null;
const current = items.find((item) => item.current);
return (
<p className="placements">
<span>In Akte: </span>
{items.map((item, index) => (
<span key={item.case_id}>
{index ? <span aria-hidden="true"> · </span> : null}
<Link to={item.href} aria-current={item.current ? "true" : undefined}>{item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "").replaceAll(" → ", " / ")}</Link>
</span>
))}
{current ? <span className="muted"> · aktueller Handlungskontext</span> : <span className="muted"> · Handlungskontext direkt, solange keine Akte gewählt ist</span>}
</p>
);
}
export function ObjectMenu({ view, onView, children }) {
const [open, setOpen] = useState(false);
function choose(next) {
setOpen(false);
onView(next);
}
return (
<>
<button type="button" className="icon-button" aria-label="Aktionen" onClick={() => setOpen(true)}>⋯</button>
<Modal open={open} title="Aktionen" onClose={() => setOpen(false)}>
<div className="menu-list" onClick={() => setOpen(false)}>
<button type="button" className={view === "course" ? "" : "quiet"} onClick={() => choose("course")}>Fachlicher Verlauf</button>
<button type="button" className={view === "audit" ? "" : "quiet"} onClick={() => choose("audit")}>Änderungsprotokoll</button>
<button type="button" className={view === "links" ? "" : "quiet"} onClick={() => choose("links")}>Zuordnungen</button>
{children}
</div>
</Modal>
</>
);
}
export function WorkSwitch({ view, onView }) {
return (
<div className="surface-tabs" role="tablist" aria-label="Arbeitsfläche">
<button type="button" role="tab" aria-selected={view === "contents"} className={view === "contents" ? "" : "quiet"} onClick={() => onView("contents")}>Inhalte</button>
<button type="button" role="tab" aria-selected={view === "work"} className={view === "work" ? "" : "quiet"} onClick={() => onView("work")}>Aufgaben und Fristen</button>
{view !== "contents" && view !== "work" ? (
<button type="button" className="quiet" onClick={() => onView("contents")}>Zurück zu den Inhalten</button>
) : null}
</div>
);
}
const SYMBOL_LABEL = {
pdf: "PDF",
document: "Textdokument",
note: "Notiz",
email: "E-Mail",
image: "Bild",
audio: "Audio",
video: "Video",
spreadsheet: "Tabelle",
presentation: "Präsentation",
archive: "Archiv",
link: "Verweis",
attachment: "Anhang",
file: "Datei",
code: "Code",
};
function elementSymbol(element) {
const media = element?.preview?.media;
const representation = moduleFor(element?.external?.source)?.representation;
if (media === "email" || representation === "email") return "email";
return contentSymbol(element || {});
}
export function sourceLabel(element) {
const type = SYMBOL_LABEL[elementSymbol(element)] || "Datei";
const module = moduleFor(element.external?.source);
if (module?.representation === "email") return module.addLabel || "E-Mail";
if (module) return `${type} · ${module.addLabel || module.title}`;
if (element.kind === "external_ref" && type === "Verweis") return "Referenz";
return type;
}
export function mailFacts(element) {
const module = moduleFor(element?.external?.source);
if (element?.preview?.media !== "email" && module?.representation !== "email") return "";
const detail = element.external.detail || {};
const from = detail.message_from ? `Von: ${detail.message_from}` : "";
const to = detail.message_to ? `An: ${detail.message_to}` : "";
const count = Array.isArray(detail.attachments) ? detail.attachments.length : 0;
const files = count ? `${count} ${count === 1 ? "Anhang" : "Anhänge"}` : "";
return [from, to, files].filter(Boolean).join(" · ");
}
export function dateCaption(element) {
const dates = element?.dates || {};
const parts = [];
if (dates.received_on) parts.push(`Eingegangen am ${formatDate(dates.received_on)}`);
if (dates.sent_on) parts.push(`Versendet am ${formatDate(dates.sent_on)}`);
return parts.join(" · ");
}
export function elementFacts(element, communication) {
const direction = communication?.direction;
const way = direction === "out" ? "Ausgang" : direction === "in" ? "Eingang" : "";
return [sourceLabel(element), way, mailFacts(element), dateCaption(element, direction)].filter(Boolean).join(" · ");
}
export function directionWord(direction) {
if (direction === "out") return "Ausgang";
if (direction === "in") return "Eingang";
if (direction === "local") return "Lokal";
return "";
}
export function directionValue(communication) {
const direction = communication?.direction;
if (direction === "in" || direction === "out" || direction === "local") return direction;
return "";
}
function DirectionGlyph({ direction }) {
const name = directionSymbol(direction);
const local = direction === "local";
return (
<>
<img className={`direction-column__icon direction-column__icon--light${local ? " direction-column__icon--local" : ""}`} src={symbolUrl("light", name)} width={local ? 12 : 26} height={local ? 12 : 26} alt="" />
<img className={`direction-column__icon direction-column__icon--dark${local ? " direction-column__icon--local" : ""}`} src={symbolUrl("dark", name)} width={local ? 12 : 26} height={local ? 12 : 26} alt="" />
</>
);
}
export function DirectionColumn({ direction }) {
const label = directionWord(direction) || "Keine Angabe";
return (
<span className={`direction-column${direction === "local" ? " direction-column--local" : ""}`} role="img" aria-label={label}>
<DirectionGlyph direction={direction} />
</span>
);
}
const DIRECTION_OPTIONS = [
["in", "Eingang"],
["out", "Ausgang"],
["local", "Lokal"],
["", "Keine Angabe"],
];
function MenuPopover({ open, anchorRef, onClose, label, children, sheet = false }) {
const panelRef = useRef(null);
const closeRef = useRef(onClose);
closeRef.current = onClose;
const [place, setPlace] = useState(null);
useEffect(() => {
if (!open) return undefined;
function position() {
const phone = window.matchMedia("(max-width: 720px)").matches;
const rect = anchorRef.current?.getBoundingClientRect();
if (phone && sheet) {
setPlace({ phone: true });
return;
}
const width = Math.min(300, window.innerWidth - 16);
const height = 240;
const left = Math.max(8, Math.min(rect ? rect.left : 8, window.innerWidth - width - 8));
let top = rect ? rect.bottom + 6 : 8;
if (rect && top + height > window.innerHeight - 8) top = Math.max(8, rect.top - height - 6);
setPlace({ phone: false, top, left, width });
}
position();
function onKey(event) {
if (event.key !== "Escape") return;
event.preventDefault();
event.stopPropagation();
closeRef.current();
}
function onScroll(event) {
if (panelRef.current?.contains(event.target)) return;
const active = document.activeElement;
if (active && panelRef.current?.contains(active) && /^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName)) return;
position();
}
window.addEventListener("keydown", onKey);
window.addEventListener("resize", position);
window.addEventListener("scroll", onScroll, true);
const frame = requestAnimationFrame(() => {
if (panelRef.current?.contains(document.activeElement)) return;
const selected = panelRef.current?.querySelector("[aria-selected='true']")
|| panelRef.current?.querySelector("button, a, input, select");
selected?.focus();
});
return () => {
cancelAnimationFrame(frame);
window.removeEventListener("keydown", onKey);
window.removeEventListener("resize", position);
window.removeEventListener("scroll", onScroll, true);
};
}, [open, sheet, anchorRef]);
if (!open || typeof document === "undefined") return null;
return createPortal(
<div className="menu-popover">
<button type="button" className={`menu-popover__backdrop${place?.phone ? " is-dim" : ""}`} aria-label="Schließen" onClick={() => closeRef.current()} />
<div
ref={panelRef}
className={place?.phone ? "menu-popover__panel menu-popover__panel--sheet" : "menu-popover__panel"}
role="dialog"
aria-label={label}
style={place?.phone ? undefined : { top: place?.top ?? 8, left: place?.left ?? 8, width: place?.width ?? 280 }}
>
{children}
</div>
</div>,
document.body,
);
}
export function DirectionControl({ direction = "", title, disabled = false, onChange }) {
const anchorRef = useRef(null);
const [open, setOpen] = useState(false);
const known = directionWord(direction);
const name = known
? `Kommunikationsrichtung${title ? ` für ${title}` : ""}: ${known}`
: "Kommunikationsrichtung festlegen – keine Angabe";
function close() {
setOpen(false);
anchorRef.current?.focus();
}
return (
<span className={`direction-column${direction === "local" ? " direction-column--local" : ""}`}>
<button
ref={anchorRef}
type="button"
className="direction-trigger"
aria-label={name}
aria-haspopup="dialog"
aria-expanded={open}
disabled={disabled}
draggable={false}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setOpen((value) => !value);
}}
>
<DirectionGlyph direction={direction} />
</button>
<MenuPopover open={open} anchorRef={anchorRef} onClose={close} label="Kommunikationsrichtung">
<div role="listbox" aria-label="Kommunikationsrichtung">
{DIRECTION_OPTIONS.map(([value, label]) => (
<button
key={label}
type="button"
role="option"
aria-selected={direction === value}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
close();
if (value !== direction) onChange(value);
}}
>
{label}
</button>
))}
</div>
</MenuPopover>
</span>
);
}
export function DirectionChoice({ value, disabled, onChange, compact = false, label = "Kommunikationsrichtung" }) {
const select = (
<select aria-label={label} value={value || ""} disabled={disabled} onChange={(event) => onChange(event.target.value)}>
<option value="">Keine Angabe</option>
<option value="in">Eingang</option>
<option value="out">Ausgang</option>
<option value="local">Lokal</option>
</select>
);
if (compact) return <span className="direction-choice">{select}</span>;
return (
<label>
{label}
{select}
</label>
);
}
export function MarkdownEditor({ value, onChange, disabled }) {
return <NoteEditor value={value} onChange={onChange} disabled={disabled} />;
}
function blurb(element) {
const raw = element?.summary || element?.excerpt || "";
if (typeof raw !== "string") return "";
return raw.replace(/^#{1,3}\s+/gm, "").replace(/\*\*([^*]+)\*\*/g, "$1").replace(/[*`]/g, "").replace(/\s+/g, " ").trim();
}
function BezugTarget({ item, source, onOpen, itemHref, onDone }) {
const found = source.find((entry) => entry.element?.id === item.id);
const href = found && itemHref ? itemHref(found) : "";
const caption = `${formatDate(item.document_on)} · ${item.title}`;
if (found && onOpen) {
return (
<button type="button" onClick={() => { onDone(); onOpen(found); }}>
{caption}
</button>
);
}
if (href) {
return <Link to={href} onClick={onDone}>{caption}</Link>;
}
return <p>{caption}</p>;
}
function BezugMenu({ element, source, onOpen, itemHref, canEdit = false, onClearBezug }) {
const refers = element.refers_to || [];
const replies = element.referred_by || [];
const count = bezugCount(element);
const anchorRef = useRef(null);
const [open, setOpen] = useState(false);
const canClear = Boolean(canEdit && onClearBezug);
if (!count) return null;
function close() {
setOpen(false);
anchorRef.current?.focus();
}
function dissolve(sourceId, targetId) {
close();
onClearBezug(sourceId, targetId);
}
return (
<>
<button
ref={anchorRef}
type="button"
className="bezug-trigger"
aria-expanded={open}
aria-haspopup="dialog"
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setOpen((value) => !value);
}}
>
<img className="bezug-trigger__icon bezug-trigger__icon--light" src={symbolUrl("light", "link")} width="16" height="16" alt="" />
<img className="bezug-trigger__icon bezug-trigger__icon--dark" src={symbolUrl("dark", "link")} width="16" height="16" alt="" />
Bezüge {count}
</button>
<MenuPopover open={open} anchorRef={anchorRef} onClose={close} label={`Bezüge ${count}`} sheet>
{refers.length ? <p className="menu-popover__label">Bezug auf</p> : null}
{refers.map((item) => (
<div key={`to-${item.id}`} className="bezug-entry">
<BezugTarget item={item} source={source} onOpen={onOpen} itemHref={itemHref} onDone={close} />
{canClear ? <button type="button" onClick={() => dissolve(element.id, item.id)}>Bezug lösen</button> : null}
</div>
))}
{replies.length ? <p className="menu-popover__label">Darauf bezogen</p> : null}
{replies.map((item) => (
<div key={`by-${item.id}`} className="bezug-entry">
<BezugTarget item={item} source={source} onOpen={onOpen} itemHref={itemHref} onDone={close} />
{canClear ? <button type="button" onClick={() => dissolve(item.id, element.id)}>Bezug lösen</button> : null}
</div>
))}
</MenuPopover>
</>
);
}
function ChapterHeading({
section,
count,
expanded,
movable,
canEdit,
canDate,
pending,
siblingIndex,
siblingCount,
chapters,
blockedParents,
version,
orderContext,
onToggle,
onRename,
onRemove,
onDate,
onMove,
onAddSubchapter,
onAddContent,
onChange,
onError,
onPending,
}) {
const anchorRef = useRef(null);
const [open, setOpen] = useState(false);
const real = section.id !== "loose";
const showMenu = real && (canEdit || canDate || movable || onAddSubchapter);
function close() {
setOpen(false);
anchorRef.current?.focus();
}
return (
<>
{real ? (
<button
type="button"
className="chapter-fold"
aria-expanded={expanded}
aria-label={expanded ? `${section.title} einklappen` : `${section.title} ausklappen`}
onClick={(event) => {
event.stopPropagation();
onToggle();
}}
>
{expanded ? "▾" : "▸"}
</button>
) : null}
<h3 className={`chapter-title${section.parentId ? " is-nested" : ""}`}>
{real ? <NavIcon name="chapter" /> : null}
<span>{section.title}</span>
</h3>
{canEdit && onAddContent ? (
<button
type="button"
className="chapter-plus"
aria-label={`Inhalt in ${section.title} hinzufügen`}
onClick={(event) => {
event.stopPropagation();
onAddContent(section.id);
}}
>
<NavIcon name="plus" />
</button>
) : null}
<span className="count">{count}</span>
{section.documentOn ? <span className="chapter-date">{formatDate(section.documentOn)}</span> : null}
{showMenu ? (
<>
<button
ref={anchorRef}
type="button"
className="chapter-menu preview-row__menu"
aria-label={`Aktionen für ${section.title}`}
aria-haspopup="dialog"
aria-expanded={open}
onClick={(event) => {
event.stopPropagation();
setOpen((value) => !value);
}}
>
⋯
</button>
<MenuPopover open={open} anchorRef={anchorRef} onClose={close} label={`Kapitel ${section.title}`} sheet>
<button type="button" onClick={() => { close(); onToggle(); }}>{expanded ? "Einklappen" : "Ausklappen"}</button>
{canEdit && onAddSubchapter ? <button type="button" onClick={() => { close(); onAddSubchapter(section.id); }}>Unterkapitel</button> : null}
{canEdit ? <button type="button" onClick={() => { close(); onRename(); }}>Umbenennen</button> : null}
{canDate ? (
<label>
Kapiteldatum
<DateField aria-label={`Kapiteldatum für ${section.title}`} value={section.documentOn || ""} onChange={onDate} />
</label>
) : null}
{movable ? <button type="button" disabled={pending || siblingIndex <= 0} onClick={() => { close(); onMove(-1); }}>Nach oben</button> : null}
{movable ? <button type="button" disabled={pending || siblingIndex < 0 || siblingIndex >= siblingCount - 1} onClick={() => { close(); onMove(1); }}>Nach unten</button> : null}
{canEdit ? (
<form onSubmit={(event) => {
event.preventDefault();
const parent = new FormData(event.currentTarget).get("parent");
onPending(true);
onError("");
api(`/api/v1/chapters/${section.id}/parent`, {
method: "POST",
body: { expected_version: version, parent_chapter_id: parent || null, ...orderContext },
}).then(() => {
close();
return onChange();
}).catch((err) => onError(err.message)).finally(() => onPending(false));
}}>
<fieldset>
<legend>Umhängen</legend>
<label>
Neues Elternkapitel
<select name="parent" defaultValue={section.parentId || ""}>
<option value="">Oberste Ebene</option>
{chapters.filter((chapter) => !blockedParents.has(chapter.id)).map((chapter) => (
<option key={chapter.id} value={chapter.id}>{chapterPathLabel(chapters, chapter.id)}</option>
))}
</select>
</label>
<button type="submit" disabled={pending}>Umhängen</button>
</fieldset>
</form>
) : null}
{canEdit ? <button type="button" className="danger" onClick={() => { close(); onRemove(); }}>Auflösen</button> : null}
</MenuPopover>
</>
) : null}
</>
);
}
function EntryActions({
element,
binding,
source,
chapters,
index,
lastIndex,
canEdit,
canDestroy,
canSort,
custom,
pending,
onSetBezug,
onClearBezug,
onRenameTitle,
onRemove,
onMove,
onPlaceChapter,
onAttach,
onDispatch,
}) {
const anchorRef = useRef(null);
const [open, setOpen] = useState(false);
const show = canEdit || (canSort && custom) || (canSort && chapters.length);
if (!show) return null;
function close() {
setOpen(false);
anchorRef.current?.focus();
}
return (
<div className="preview-row__actions">
<button
ref={anchorRef}
type="button"
className="preview-row__menu"
aria-label={`Aktionen für ${element.title}`}
aria-haspopup="dialog"
aria-expanded={open}
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
event.preventDefault();
event.stopPropagation();
setOpen((value) => !value);
}}
>
⋯
</button>
<MenuPopover open={open} anchorRef={anchorRef} onClose={close} label={`Aktionen für ${element.title}`} sheet>
{canEdit ? (
<>
<button type="button" onClick={() => { close(); onRenameTitle(element); }}>Titel ändern</button>
<p className="menu-popover__label">Bezug</p>
<label>
Bezug auf
<select value="" disabled={pending} onChange={(event) => { const value = event.target.value; if (!value) return; close(); onSetBezug(element.id, value); }}>
<option value="">Unterlage wählen</option>
{source.filter((item) => item.element?.id && item.element.id !== element.id).map((item) => (
<option key={item.element.id} value={item.element.id}>
{formatDate(item.element.dates?.document_on)} · {item.element.title}
</option>
))}
</select>
</label>
{(element.refers_to || []).map((item) => (
<button key={`to-${item.id}`} type="button" onClick={() => { close(); onClearBezug(element.id, item.id); }}>
Bezug auf {item.title} lösen
</button>
))}
{(element.referred_by || []).length ? <p className="menu-popover__label">Darauf bezogen</p> : null}
{(element.referred_by || []).map((item) => (
<button key={`by-${item.id}`} type="button" onClick={() => { close(); onClearBezug(item.id, element.id); }}>
Bezug von {item.title} lösen
</button>
))}
</>
) : null}
{canSort && chapters.length ? (
<label>
Kapitel
<select value={binding.chapter_id || ""} disabled={pending} onChange={(event) => { close(); onPlaceChapter(binding.id, event.target.value); }}>
<option value="">Ohne Kapitel</option>
{chapters.map((chapter) => <option key={chapter.id} value={chapter.id}>{chapterPathLabel(chapters, chapter.id)}</option>)}
</select>
</label>
) : null}
{canSort && custom ? <button type="button" disabled={pending || index === 0} onClick={() => { close(); onMove(binding.id, -1); }}>Nach oben</button> : null}
{canSort && custom ? <button type="button" disabled={pending || index === lastIndex} onClick={() => { close(); onMove(binding.id, 1); }}>Nach unten</button> : null}
{canEdit && onAttach ? <button type="button" onClick={() => { close(); onAttach(binding); }}>Anlagen und Belege zuordnen</button> : null}
{canEdit && onDispatch ? <button type="button" onClick={() => { close(); onDispatch(binding); }}>Versand dokumentieren</button> : null}
{canEdit ? <button type="button" onClick={() => { close(); onRemove(binding, false); }}>Aus diesem Zusammenhang entfernen</button> : null}
{canEdit && canDestroy ? <button type="button" className="danger" onClick={() => { close(); onRemove(binding, true); }}>Überall löschen</button> : null}
</MenuPopover>
</div>
);
}
function TypeGlyph({ name, tone, size = 28 }) {
return (
<img
className={tone === "dark" ? "type-glyph type-glyph--dark" : "type-glyph type-glyph--light"}
src={symbolUrl(tone, name)}
width={size}
height={size}
alt=""
draggable={false}
/>
);
}
function useDropId(node) {
return node?.closest?.("[data-use-drop]")?.getAttribute("data-use-drop") || "";
}
function EntryMark({ element, context, assignable = false, dropId = "", hot = false, onAssignStart, onAssignEnd }) {
const symbol = elementSymbol(element);
const photo = symbol === "image" && Boolean(element.preview?.available);
const [url, setUrl] = useState("");
useEffect(() => {
if (!photo) return undefined;
let alive = true;
let current = "";
const load = element.kind === "external_ref" ? fetchExternal(element.id, context) : fetchFile(element.id, context);
load.then((blob) => {
if (!alive || !blob.type.startsWith("image/")) return;
current = URL.createObjectURL(blob);
setUrl(current);
}).catch(() => {
if (alive) setUrl("");
});
return () => {
alive = false;
if (current) URL.revokeObjectURL(current);
};
}, [photo, element.id, element.preview?.source, context?.kind, context?.id]);
return (
<span
className={[url ? "entry-mark entry-mark--photo" : "entry-mark", hot ? "is-assign-hot" : ""].filter(Boolean).join(" ")}
data-assign-drop={dropId || undefined}
role={assignable ? "button" : undefined}
tabIndex={assignable ? 0 : undefined}
aria-label={assignable ? `${element.title} als Anlage oder Beleg ziehen` : undefined}
onPointerDown={assignable ? onAssignStart : undefined}
>
{url ? <img className="entry-mark__photo" alt="" draggable={false} src={url} /> : (
<>
<TypeGlyph name={symbol} tone="light" />
<TypeGlyph name={symbol} tone="dark" />
</>
)}
{url ? (
<span className="entry-mark__badge">
<TypeGlyph name="image" tone="light" size={14} />
<TypeGlyph name="image" tone="dark" size={14} />
</span>
) : null}
{dropId ? <span className="entry-mark__drop" aria-hidden="true" /> : null}
</span>
);
}
export async function saveChapterOrder({ containerKind, containerId, record, context, ids }) {
const orderPath = `/api/v1/${containerKind === "case" ? "cases" : "matters"}/${containerId}`;
const orderContext = context && containerKind === "matter" ? { context } : {};
let version = record.version;
const direction = record?.content_order_dir === "desc" ? "desc" : "asc";
if (record?.content_order !== "position") {
const switched = await api(`${orderPath}/content-order`, {
method: "PATCH",
body: { expected_version: version, mode: "position", direction, ...orderContext },
});
version = switched.version;
}
await api(`${orderPath}/chapters/order`, {
method: "POST",
body: { expected_version: version, chapter_ids: ids, ...orderContext },
});
}
export function ContentBoard({
record,
bindings,
context,
containerKind,
containerId,
sortable = true,
onChange,
itemHref,
onlyChapter = "",
selectedId = "",
onOpen,
onAddSubchapter,
onAddContent,
listTitle = "",
}) {
const source = bindings || record?.bindings || [];
const chapters = record?.chapters || [];
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const [dialog, setDialog] = useState(null);
const [draggingId, setDraggingId] = useState("");
const [indicator, setIndicator] = useState(null);
const [carrying, setCarrying] = useState(null);
const [folded, setFolded] = useState(() => new Set());
const [picking, setPicking] = useState(false);
const [picked, setPicked] = useState(() => new Set());
const [pickTarget, setPickTarget] = useState("");
const dragRef = useRef(null);
const carryRef = useRef(null);
const releaseRef = useRef(null);
const placeUseRef = useRef(null);
const rootRef = useRef(null);
const savingDirection = useRef(false);
const custom = record?.content_order === "position";
const direction = record?.content_order_dir === "desc" ? "desc" : "asc";
const viewMode = record?.content_view === "chronology" ? "chronology" : "structure";
const listed = source.filter((item) => !item.correspondence?.fold);
const forest = buildChapterSections(chapters, listed);
const loose = looseSection(forest.loose, chapters);
const selectedSection = onlyChapter ? findSection(forest.roots, onlyChapter) : null;
const visibleRoots = onlyChapter ? (selectedSection ? [selectedSection] : []) : forest.roots;
const shownCount = viewMode === "chronology"
? ""
: onlyChapter
? countLabel(sectionCounts(selectedSection).direct, sectionCounts(selectedSection).nested)
: String(listed.length);
const activePath = onlyChapter ? chapterPathLabel(chapters, onlyChapter) : "";
const canSort = sortable && record?.rights?.edit;
const canEdit = Boolean(record?.rights?.edit);
const canDestroy = Boolean(record?.is_owner);
const canMoveChapters = Boolean(canSort && chapters.length > 1);
function actionContext() {
return context || (containerKind === "case" ? { kind: "case", id: containerId } : { kind: "matter", id: containerId });
}
async function setBezug(elementId, refersToId) {
if (!refersToId) return;
setPending(true);
setError("");
try {
await api(`/api/v1/elements/${elementId}/references`, {
method: "POST",
body: { refers_to_element_id: refersToId, context: actionContext() },
});
await onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function saveRowDirection(binding, value) {
if (savingDirection.current) return;
savingDirection.current = true;
setPending(true);
setError("");
try {
await api(`/api/v1/bindings/${binding.id}/communication`, {
method: "PATCH",
body: {
expected_version: binding.element.version,
direction: value || null,
context: actionContext(),
},
});
await onChange();
} catch (err) {
setError(err.message);
} finally {
savingDirection.current = false;
setPending(false);
}
}
async function renameElement(element) {
const title = window.prompt("Titel", element.title);
if (!title || title.trim() === element.title) return;
setPending(true);
setError("");
try {
await api(`/api/v1/elements/${element.id}/title`, {
method: "PATCH",
body: { expected_version: element.version, title: title.trim(), context: actionContext() },
});
await onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function clearBezug(elementId, refersToId) {
setPending(true);
setError("");
try {
const action = actionContext();
const search = new URLSearchParams({ context_kind: action.kind, context_id: action.id });
await api(`/api/v1/elements/${elementId}/references/${refersToId}?${search}`, { method: "DELETE" });
await onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function removeBinding(binding, everywhere) {
const element = binding?.element;
if (!element) return;
setError("");
try {
if (everywhere) {
if (!window.confirm("Überall löschen? Alle Einbindungen verschwinden. Eine Paperless-Quelle bleibt unangetastet.")) return;
await api(`/api/v1/elements/${element.id}/delete`, { method: "POST", body: { expected_version: element.version } });
} else {
if (!window.confirm("Aus diesem Zusammenhang entfernen? Die Unterlage bleibt an anderen Stellen erhalten.")) return;
const action = context || (containerKind === "case" ? { kind: "case", id: containerId } : { kind: "matter", id: containerId });
const search = new URLSearchParams();
search.set("context_kind", action.kind);
search.set("context_id", action.id);
await api(`/api/v1/bindings/${binding.id}?${search}`, { method: "DELETE" });
}
await onChange();
} catch (err) {
setError(err.message);
}
}
const orderPath = `/api/v1/${containerKind === "case" ? "cases" : "matters"}/${containerId}`;
const orderContext = context && containerKind === "matter" ? { context } : {};
const finishDragRef = useRef(finishDrag);
finishDragRef.current = finishDrag;
useEffect(() => {
function onKey(event) {
if (event.key !== "Escape") return;
if (dragRef.current) {
dragRef.current = null;
setDraggingId("");
setIndicator(null);
}
carryRef.current?.cancel?.();
}
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("keydown", onKey);
document.body.classList.remove("is-carrying", "is-assigning", "is-list-intent", "is-list-carry");
rootRef.current?.querySelectorAll(".preview-row.is-carry-source, .preview-row.is-assign-target").forEach((row) => {
row.classList.remove("is-carry-source", "is-assign-target");
});
};
}, []);
useLayoutEffect(() => {
const node = rootRef.current;
if (!node) return undefined;
function place(event) {
const carried = carryRef.current;
if (carried) {
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
if (event.clientX || event.clientY) {
carried.lastX = event.clientX;
carried.lastY = event.clientY;
carried.moved = true;
document.body.classList.add("is-carrying");
}
const mark = event.target?.closest?.(".entry-mark[data-assign-drop]");
const useId = mark?.getAttribute("data-assign-drop") || "";
const blocked = !useId || useId === carried.bindingId || useId === carried.hostBindingId || carried.sourceRow?.contains(mark);
if (!blocked) {
carried.useBindingId = useId;
carried.release = false;
carried.place = false;
setIndicator({ kind: "use", bindingId: useId });
return;
}
if (carried.source === "attachment" || carried.source === "evidence") {
const section = event.target?.closest?.("[data-section]");
carried.useBindingId = "";
carried.release = true;
carried.place = Boolean(section);
carried.chapterId = section && section.getAttribute("data-section") !== "loose" ? section.getAttribute("data-section") : "";
const loose = !section || section.getAttribute("data-section") === "loose";
setIndicator({
kind: "release",
place: carried.place,
chapterId: carried.chapterId,
title: loose ? "" : (section.getAttribute("data-chapter-title") || ""),
});
}
return;
}
const drag = dragRef.current;
if (!drag?.html5 || drag.done) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "move";
if (drag.kind === "chapter") {
drag.useBindingId = null;
drag.index = chapterUnder(event.clientY, drag.parentId);
setIndicator({ sectionId: drag.chapterId, index: drag.index, kind: "chapter", parentId: drag.parentId || "" });
return;
}
const useId = useDropId(event.target);
if (useId && useId !== drag.bindingId) {
drag.useBindingId = useId;
drag.index = null;
setIndicator({ kind: "use", bindingId: useId });
return;
}
drag.useBindingId = null;
const sectionId = event.target?.closest?.("[data-section]")?.getAttribute("data-section");
if (!sectionId) return;
drag.targetSectionId = sectionId;
drag.index = indexAt(sectionId, event.clientY);
setIndicator({ sectionId, index: drag.index, kind: "order" });
}
function drop(event) {
const carried = carryRef.current;
if (carried) {
event.preventDefault();
if (carried.settled) return;
carried.settled = true;
const mark = event.target?.closest?.(".entry-mark[data-assign-drop]");
const useId = mark?.getAttribute("data-assign-drop") || "";
const section = event.target?.closest?.("[data-section]");
const assign = useId && useId !== carried.bindingId && useId !== carried.hostBindingId && !carried.sourceRow?.contains(mark);
carryRef.current = null;
setIndicator(null);
setCarrying(null);
document.body.classList.remove("is-carrying", "is-assigning", "is-list-intent", "is-list-carry");
carried.sourceRow?.classList.remove("is-carry-source");
rootRef.current?.querySelectorAll(".preview-row.is-assign-target").forEach((row) => row.classList.remove("is-assign-target"));
if (assign) placeUseRef.current?.(useId, carried);
else if ((carried.source === "attachment" || carried.source === "evidence") && (section || event.target?.closest?.("[data-release-drop]"))) {
releaseRef.current?.({
...carried,
place: Boolean(section),
chapterId: section && section.getAttribute("data-section") !== "loose" ? section.getAttribute("data-section") : "",
});
}
return;
}
const drag = dragRef.current;
if (!drag?.html5 || drag.done) return;
place(event);
finishDragRef.current(drag);
}
function rowTarget(event) {
const target = event.target?.nodeType === 1 ? event.target : event.target?.parentElement;
if (!target?.closest?.("li.preview-row")) return null;
if (target.closest("button, input, textarea, select, label, .direction-column, .preview-row__actions, .handle, .row-menu")) return null;
return target;
}
function blockRowMouseDown(event) {
if (event.button !== 0 || !rowTarget(event)) return;
event.preventDefault();
}
node.addEventListener("mousedown", blockRowMouseDown, true);
node.addEventListener("dragover", place);
node.addEventListener("drop", drop);
return () => {
node.removeEventListener("mousedown", blockRowMouseDown, true);
node.removeEventListener("dragover", place);
node.removeEventListener("drop", drop);
};
}, [canEdit, picking, source.length]);
async function saveMode(mode, nextDirection, nextView = viewMode) {
setError("");
setPending(true);
try {
await api(`${orderPath}/content-order`, {
method: "PATCH",
body: { expected_version: record.version, mode, direction: nextDirection, view: nextView, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
function orderedIds(sections) {
const hidden = source.filter((item) => item.correspondence?.fold);
const used = new Set();
const ids = [];
for (const section of sections) {
for (const item of section.items) {
ids.push(item.id);
used.add(item.id);
}
const chapterId = section.id === "loose" ? null : section.id;
for (const item of hidden) {
const itemChapter = item.chapter_id || null;
if ((chapterId ? itemChapter === chapterId : !itemChapter) && !used.has(item.id)) {
ids.push(item.id);
used.add(item.id);
}
}
}
for (const item of source) {
if (!used.has(item.id)) ids.push(item.id);
}
return ids;
}
async function persist(next, version = record.version) {
setError("");
setPending(true);
try {
await api(`${orderPath}/bindings/order`, {
method: "POST",
body: {
expected_version: version,
binding_ids: orderedIds(next),
...orderContext,
},
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function reorderChapters(ids) {
setError("");
setPending(true);
try {
let version = record.version;
if (!custom) {
const switched = await api(`${orderPath}/content-order`, {
method: "PATCH",
body: { expected_version: version, mode: "position", direction, ...orderContext },
});
version = switched.version;
}
await api(`${orderPath}/chapters/order`, {
method: "POST",
body: { expected_version: version, chapter_ids: ids, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
function moveChapter(chapterId, delta) {
const ids = siblingChapterIds(chapters, chapterId);
const index = ids.indexOf(chapterId);
const target = index + delta;
if (index < 0 || target < 0 || target >= ids.length) return;
const [id] = ids.splice(index, 1);
ids.splice(target, 0, id);
reorderChapters(ids);
}
async function saveChapterDate(chapterId, value) {
setError("");
setPending(true);
try {
await api(`/api/v1/chapters/${chapterId}`, {
method: "PATCH",
body: { expected_version: record.version, document_on: value || null, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function renameChapter(section) {
const title = window.prompt("Kapitelname", section.title);
if (!title || title.trim() === section.title) return;
setError("");
setPending(true);
try {
await api(`/api/v1/chapters/${section.id}/title`, {
method: "PATCH",
body: { expected_version: record.version, title: title.trim(), ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function removeChapter(section) {
const parent = chapters.find((chapter) => chapter.id === section.parentId);
const targetName = parent ? `das Kapitel „${parent.title}“` : "die oberste Ebene";
const childNote = section.children?.length ? " Direkte Unterkapitel rücken mit ihrem Unterbaum mit." : "";
if (!window.confirm(`Kapitel „${section.title}“ auflösen? Die Gliederung entfällt. Direkte Inhalte rücken nach ${targetName}.${childNote} Dateien und andere Einbindungen bleiben erhalten.`)) return;
setError("");
setPending(true);
try {
await api(`/api/v1/chapters/${section.id}/delete`, {
method: "POST",
body: { expected_version: record.version, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
function allSections() {
const list = [];
const walk = (section) => {
list.push(section);
(section.children || []).forEach(walk);
};
forest.roots.forEach(walk);
if (loose) list.push(loose);
return list;
}
async function move(bindingId, delta) {
const next = allSections().map((section) => ({ ...section, items: [...section.items] }));
let moved = false;
for (const section of next) {
const index = section.items.findIndex((item) => item.id === bindingId);
const target = index + delta;
if (index < 0 || target < 0 || target >= section.items.length) continue;
const [item] = section.items.splice(index, 1);
section.items.splice(target, 0, item);
moved = true;
}
if (!moved) return;
await persist(next);
}
async function placeMany(ids, chapterId) {
if (!ids.length) return;
setError("");
setPending(true);
try {
await api(`${orderPath}/bindings/chapters`, {
method: "POST",
body: {
expected_version: record.version,
binding_ids: ids,
chapter_id: chapterId || null,
...orderContext,
},
});
setPicked(new Set());
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function placeChapter(bindingId, chapterId) {
setError("");
setPending(true);
try {
await api(`/api/v1/bindings/${bindingId}/chapter`, {
method: "PATCH",
body: { expected_version: record.version, chapter_id: chapterId || null, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
function indexAt(sectionId, clientY) {
const rows = [...(rootRef.current?.querySelectorAll(`[data-section="${sectionId}"] [data-binding]`) || [])];
for (let i = 0; i < rows.length; i += 1) {
const rect = rows[i].getBoundingClientRect();
if (clientY < rect.top + rect.height / 2) return i;
}
return rows.length;
}
function sectionUnder(clientY) {
const nodes = [...(rootRef.current?.querySelectorAll("[data-section]") || [])].filter((node) => {
const rect = node.getBoundingClientRect();
return clientY >= rect.top && clientY <= rect.bottom;
});
nodes.sort((left, right) => left.getBoundingClientRect().height - right.getBoundingClientRect().height);
return nodes[0]?.getAttribute("data-section") || null;
}
function chapterUnder(clientY, parentId) {
const key = parentId || "";
const nodes = [...(rootRef.current?.querySelectorAll("[data-chapter]") || [])].filter(
(node) => (node.getAttribute("data-chapter-parent") || "") === key,
);
if (!nodes.length) return 0;
for (let i = 0; i < nodes.length; i += 1) {
const next = nodes[i + 1]?.getBoundingClientRect();
const bottom = next ? next.top : Number.POSITIVE_INFINITY;
if (clientY < bottom) return i;
}
return nodes.length - 1;
}
function finishDrag(drag) {
if (!drag || drag.done) return;
drag.done = true;
dragRef.current = null;
setDraggingId("");
setIndicator(null);
if (drag?.useBindingId && drag.bindingId && drag.useBindingId !== drag.bindingId) {
const host = source.find((item) => item.id === drag.useBindingId);
const item = source.find((item) => item.id === drag.bindingId);
if (host && item && host.element.id !== item.element.id) {
setDialog({
type: "place-use",
host,
binding: item,
payload: {
source: "list",
elementId: item.element.id,
bindingId: item.id,
title: item.element.title,
},
});
}
return;
}
if (!drag || !drag.moved || drag.index == null) return;
if (drag.kind === "chapter") {
const ids = siblingChapterIds(chapters, drag.chapterId);
const from = ids.indexOf(drag.chapterId);
const target = drag.index;
if (from < 0 || target == null || target === from) return;
const [id] = ids.splice(from, 1);
ids.splice(Math.max(0, Math.min(target, ids.length)), 0, id);
reorderChapters(ids);
return;
}
const next = allSections().map((section) => ({ ...section, items: [...section.items] }));
const source = next.find((item) => item.id === drag.sectionId);
const targetSection = next.find((item) => item.id === (drag.targetSectionId || drag.sectionId));
if (!source || !targetSection) return;
const from = source.items.findIndex((item) => item.id === drag.bindingId);
if (from < 0) return;
let target = drag.index;
if (source.id === targetSection.id && from < target) target -= 1;
if (target < 0) target = 0;
if (target > targetSection.items.length) target = targetSection.items.length;
if (source.id === targetSection.id && target === from) return;
const [item] = source.items.splice(from, 1);
const nextChapter = targetSection.id === "loose" ? null : targetSection.id;
const changed = (item.chapter_id || null) !== nextChapter;
item.chapter_id = nextChapter;
const insertAt = source.id === targetSection.id ? target : Math.min(target, targetSection.items.length);
targetSection.items.splice(insertAt, 0, item);
if (!changed) {
persist(next);
return;
}
setPending(true);
setError("");
api(`/api/v1/bindings/${item.id}/chapter`, {
method: "PATCH",
body: { expected_version: record.version, chapter_id: nextChapter, ...orderContext },
}).then((moved) => persist(next, moved.version)).catch((err) => {
setError(err.message);
setPending(false);
});
}
function track(event) {
const drag = dragRef.current;
if (!drag || drag.pointerId !== event.pointerId) return;
if (Math.abs(event.clientY - drag.startY) > 4) drag.moved = true;
if (event.clientY < 72) window.scrollBy(0, -16);
if (event.clientY > window.innerHeight - 72) window.scrollBy(0, 16);
if (drag.kind === "chapter") {
drag.useBindingId = null;
drag.index = chapterUnder(event.clientY, drag.parentId);
setIndicator({ sectionId: drag.chapterId, index: drag.index, kind: "chapter", parentId: drag.parentId || "" });
return;
}
const useId = useDropId(document.elementFromPoint(event.clientX, event.clientY));
if (useId && useId !== drag.bindingId) {
drag.useBindingId = useId;
drag.index = null;
drag.moved = true;
setIndicator({ kind: "use", bindingId: useId });
return;
}
drag.useBindingId = null;
drag.targetSectionId = sectionUnder(event.clientY) || drag.sectionId;
drag.index = indexAt(drag.targetSectionId, event.clientY);
setIndicator({ sectionId: drag.targetSectionId, index: drag.index, kind: "order" });
}
function release(event) {
const drag = dragRef.current;
window.removeEventListener("pointermove", track);
window.removeEventListener("pointerup", release);
window.removeEventListener("pointercancel", cancel);
if (!drag || drag.done || drag.pointerId !== event.pointerId) return;
finishDrag(drag);
}
function cancel() {
const drag = dragRef.current;
window.removeEventListener("pointermove", track);
window.removeEventListener("pointerup", release);
window.removeEventListener("pointercancel", cancel);
if (drag?.html5) return;
dragRef.current = null;
setDraggingId("");
setIndicator(null);
}
function markHtml5(drag) {
const current = dragRef.current;
if (current && (current.chapterId === drag.chapterId || current.bindingId === drag.bindingId)) {
current.html5 = true;
current.moved = true;
return;
}
dragRef.current = { ...drag, html5: true, moved: true, index: null, pointerId: "html5", startY: 0 };
}
function endHtml5() {
setTimeout(() => {
const drag = dragRef.current;
if (!drag?.html5 || drag.done) return;
finishDrag(drag);
}, 0);
}
function beginCarryPointer(event, payload) {
if (carryRef.current || pending || (event.button != null && event.button !== 0)) return;
const target = event.target?.nodeType === 1 ? event.target : event.target?.parentElement;
if (!target?.closest || target.closest("button:not(.handle), input, textarea, select, label")) return;
event.preventDefault();
event.stopPropagation();
const opener = target.closest("a.preview-row__title, a.preview-row__text, .use-chip__title");
const sourceRow = target.closest(".preview-row");
const carried = {
...payload,
pointerId: event.pointerId ?? 1,
anchorX: event.clientX,
anchorY: event.clientY,
lastX: event.clientX,
lastY: event.clientY,
moved: false,
settled: false,
useBindingId: "",
release: false,
sourceNode: sourceRow || target.closest(".use-chip") || target,
sourceRow,
};
function paintAssignTarget(bindingId) {
const root = rootRef.current;
if (!root) return;
root.querySelectorAll(".preview-row.is-assign-target").forEach((row) => row.classList.remove("is-assign-target"));
root.querySelectorAll(".entry-mark.is-assign-hot").forEach((mark) => mark.classList.remove("is-assign-hot"));
if (!bindingId) return;
const row = root.querySelector(`.preview-row[data-binding="${bindingId}"]`);
if (!row) return;
if (carried.source === "list") {
row.querySelector(":scope > .entry-mark")?.classList.add("is-assign-hot");
return;
}
row.classList.add("is-assign-target");
}
function beginCarryMotion() {
document.body.classList.add("is-carrying");
if (carried.source === "list") {
document.body.classList.add("is-list-carry");
carried.sourceRow?.classList.add("is-carry-source");
}
setCarrying({
source: carried.source,
bindingId: carried.bindingId || "",
hostBindingId: carried.hostBindingId || "",
});
}
function clearCarryMotion() {
paintAssignTarget("");
document.body.classList.remove("is-carrying", "is-assigning", "is-list-intent", "is-list-carry");
carried.sourceRow?.classList.remove("is-carry-source");
}
function blockBrowserGesture(native) {
native.preventDefault();
}
function assignIdAt(x, y) {
const root = rootRef.current;
if (!root) return "";
const marks = carried.source === "list"
? root.querySelectorAll(".preview-row:not(.is-carry-source) > .entry-mark[data-assign-drop]")
: root.querySelectorAll(".entry-mark[data-assign-drop]");
let best = "";
let bestArea = Number.POSITIVE_INFINITY;
for (const mark of marks) {
if (carried.sourceRow?.contains(mark)) continue;
const rect = mark.getBoundingClientRect();
if (rect.width < 1 || rect.height < 1) continue;
if (x < rect.left || x > rect.right || y < rect.top || y > rect.bottom) continue;
const useId = mark.getAttribute("data-assign-drop") || "";
if (!useId || useId === carried.bindingId || useId === carried.hostBindingId) continue;
const area = rect.width * rect.height;
if (area < bestArea) {
best = useId;
bestArea = area;
}
}
return best;
}
function hitAt(x, y) {
const direct = assignIdAt(x, y);
if (direct) return { useId: direct };
const nodes = document.elementsFromPoint(x, y);
for (const node of nodes) {
if (carried.sourceRow?.contains(node)) continue;
const mark = node.closest?.(".entry-mark[data-assign-drop]");
if (!mark || carried.sourceRow?.contains(mark)) continue;
const useId = mark.getAttribute("data-assign-drop") || "";
if (!useId || useId === carried.bindingId || useId === carried.hostBindingId) continue;
return { useId };
}
if (carried.source !== "attachment" && carried.source !== "evidence") return {};
if (nodes.some((node) => node.closest?.("[data-release-drop]"))) return { release: true, place: false, chapterId: "" };
for (const node of nodes) {
if (carried.sourceNode?.contains(node)) continue;
const section = node.closest?.("[data-section]");
if (!section || !rootRef.current?.contains(section)) continue;
const id = section.getAttribute("data-section") || "";
return {
release: true,
place: true,
chapterId: id === "loose" ? "" : id,
title: id === "loose" ? "" : (section.getAttribute("data-chapter-title") || ""),
};
}
return {};
}
function remember(x, y, sticky) {
const found = hitAt(x, y);
if (found.useId) {
carried.useBindingId = found.useId;
carried.release = false;
carried.place = false;
carried.chapterId = "";
carried.reorderTarget = null;
paintAssignTarget(found.useId);
setIndicator({ kind: "use", bindingId: found.useId });
return;
}
if (found.release) {
carried.useBindingId = "";
carried.release = true;
carried.place = Boolean(found.place);
carried.chapterId = found.chapterId || "";
paintAssignTarget("");
setIndicator({ kind: "release", place: carried.place, chapterId: carried.chapterId, title: found.title || "" });
return;
}
if (sticky && carried.useBindingId) {
carried.release = false;
paintAssignTarget(carried.useBindingId);
setIndicator({ kind: "use", bindingId: carried.useBindingId });
return;
}
carried.useBindingId = "";
carried.release = false;
carried.place = false;
carried.chapterId = "";
paintAssignTarget("");
if (carried.reorder) {
const sectionId = sectionUnder(y) || carried.reorder.sectionId;
const index = indexAt(sectionId, y);
carried.reorderTarget = { sectionId, index };
setIndicator({ sectionId, index, kind: "order" });
return;
}
carried.reorderTarget = null;
setIndicator(null);
}
function cleanup() {
window.removeEventListener("pointermove", track, true);
window.removeEventListener("pointerup", finish, true);
window.removeEventListener("mousemove", onMouseMove, true);
window.removeEventListener("mouseup", onMouseUp, true);
window.removeEventListener("mousedown", blockBrowserGesture, true);
window.removeEventListener("dragstart", onDragStart, true);
window.removeEventListener("dragend", onDragEnd, true);
window.removeEventListener("selectstart", blockBrowserGesture, true);
clearCarryMotion();
if (carryRef.current === carried) carryRef.current = null;
setCarrying(null);
setIndicator(null);
}
function noteMove(x, y) {
if (x || y) {
carried.lastX = x;
carried.lastY = y;
}
if (!carried.moved && Math.hypot(carried.lastX - carried.anchorX, carried.lastY - carried.anchorY) > 3) {
carried.moved = true;
if (carried.sourceNode) carried.sourceNode.dataset.dragged = "1";
beginCarryMotion();
}
if (!carried.moved) return false;
remember(carried.lastX, carried.lastY, false);
return true;
}
function track(pointer) {
if (carryRef.current !== carried || (pointer.pointerId !== carried.pointerId && pointer.pointerId !== 0)) return;
if (noteMove(pointer.clientX, pointer.clientY)) pointer.preventDefault();
}
function onMouseMove(native) {
if (carryRef.current !== carried) return;
if (noteMove(native.clientX, native.clientY)) native.preventDefault();
}
function onMouseUp(native) {
if (carryRef.current !== carried) return;
finish({ pointerId: carried.pointerId, clientX: native.clientX, clientY: native.clientY });
}
function onDragStart(native) {
native.preventDefault();
if (!carried.moved) {
carried.moved = true;
if (carried.sourceNode) carried.sourceNode.dataset.dragged = "1";
beginCarryMotion();
}
}
function finish(pointer) {
if (pointer && pointer.pointerId !== carried.pointerId && pointer.pointerId !== 0) return;
if (carried.settled) {
cleanup();
return;
}
carried.settled = true;
const moved = carried.moved;
const x = pointer && (pointer.clientX || pointer.clientY) ? pointer.clientX : carried.lastX;
const y = pointer && (pointer.clientX || pointer.clientY) ? pointer.clientY : carried.lastY;
if (moved) remember(x, y, true);
const useId = carried.useBindingId;
const release = carried.release;
cleanup();
if (!moved) {
opener?.click();
return;
}
window.addEventListener("click", (click) => {
if (click.target.closest("button, [role=dialog]")) return;
click.preventDefault();
click.stopPropagation();
}, { capture: true, once: true });
if (useId && useId !== carried.bindingId && useId !== carried.hostBindingId) {
placeUseRef.current?.(useId, carried);
return;
}
if (carried.reorder && carried.reorderTarget?.index != null) {
finishDrag({
bindingId: carried.reorder.bindingId,
sectionId: carried.reorder.sectionId,
targetSectionId: carried.reorderTarget.sectionId,
index: carried.reorderTarget.index,
moved: true,
});
return;
}
if (release && (carried.source === "attachment" || carried.source === "evidence")) {
releaseRef.current?.({ ...carried, place: carried.place, chapterId: carried.chapterId });
}
}
function onDragEnd() {
if (carried.settled) {
cleanup();
return;
}
if (!carried.moved) return;
finish({ pointerId: carried.pointerId, clientX: carried.lastX, clientY: carried.lastY });
}
carried.cancel = () => {
if (carried.settled) return;
carried.settled = true;
carried.moved = false;
cleanup();
};
carryRef.current = carried;
document.body.classList.add("is-assigning");
if (carried.source === "list") document.body.classList.add("is-list-intent");
window.addEventListener("mousedown", blockBrowserGesture, true);
window.addEventListener("dragstart", onDragStart, true);
window.addEventListener("dragend", onDragEnd, true);
window.addEventListener("selectstart", blockBrowserGesture, true);
window.addEventListener("pointermove", track, true);
window.addEventListener("pointerup", finish, true);
window.addEventListener("mousemove", onMouseMove, true);
window.addEventListener("mouseup", onMouseUp, true);
}
function bindingByElement(elementId) {
return source.find((item) => item.element?.id === elementId) || null;
}
function dispatchOf(dispatchId) {
for (const item of source) {
const found = (item.correspondence?.dispatches || []).find((entry) => entry.id === dispatchId);
if (found) return { host: item, dispatch: found };
}
return null;
}
const correspondenceScope = () => scopeBody(actionContext(), containerKind, containerId);
async function releaseToList(payload) {
setPending(true);
setError("");
try {
const scope = correspondenceScope();
if (payload.source === "attachment") {
const host = bindingByElement(payload.hostElementId);
if (!host) return;
await api(`/api/v1/elements/${host.element.id}/attachments/${payload.elementId}/detach`, {
method: "POST",
body: { expected_version: host.element.version, ...scope },
});
} else if (payload.source === "evidence") {
const found = dispatchOf(payload.dispatchId);
if (!found) return;
await api(`/api/v1/dispatches/${found.dispatch.id}/evidence/${payload.elementId}/detach`, {
method: "POST",
body: { expected_version: found.dispatch.version, ...scope },
});
}
const item = bindingByElement(payload.elementId);
if (item?.correspondence?.fold) {
await restoreFold(item.id, item.element.version, scope);
}
if (payload.place && item && (item.chapter_id || "") !== (payload.chapterId || "")) {
await api(`/api/v1/bindings/${item.id}/chapter`, {
method: "PATCH",
body: { expected_version: record.version, chapter_id: payload.chapterId || null, ...orderContext },
});
}
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
releaseRef.current = releaseToList;
async function dropAttachment(hostBinding, payload) {
if (!payload || payload.elementId === hostBinding.element.id) return;
const already = (hostBinding.correspondence?.attachments || []).some((item) => item.element_id === payload.elementId);
if (payload.source === "attachment" && payload.hostElementId === hostBinding.element.id) return;
if (already) {
setError("Diese Anlage ist dem Schreiben bereits zugeordnet.");
return;
}
setPending(true);
setError("");
try {
const scope = correspondenceScope();
if (payload.source === "attachment") {
const from = bindingByElement(payload.hostElementId);
if (!from) return;
await api(`/api/v1/elements/${from.element.id}/attachments/${payload.elementId}/detach`, {
method: "POST",
body: { expected_version: from.element.version, ...scope },
});
}
if (payload.source === "evidence") {
const found = dispatchOf(payload.dispatchId);
if (!found) return;
await api(`/api/v1/dispatches/${found.dispatch.id}/evidence/${payload.elementId}/detach`, {
method: "POST",
body: { expected_version: found.dispatch.version, ...scope },
});
}
await api(`/api/v1/elements/${hostBinding.element.id}/attachments`, {
method: "POST",
body: {
expected_version: hostBinding.element.version,
attachment_element_ids: [payload.elementId],
fold: "attachment",
...scope,
},
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function placeReceipt(hostBinding, payload, element) {
if (!payload || payload.elementId === hostBinding.element.id) return;
const role = moduleFor(element?.external?.source)?.representation === "email" ? "email" : "other";
setPending(true);
setError("");
try {
const scope = correspondenceScope();
if (payload.source === "attachment") {
const from = bindingByElement(payload.hostElementId);
if (!from) return;
await api(`/api/v1/elements/${from.element.id}/attachments/${payload.elementId}/detach`, {
method: "POST",
body: { expected_version: from.element.version, ...scope },
});
}
if (payload.source === "evidence") {
const found = dispatchOf(payload.dispatchId);
if (!found) return;
await api(`/api/v1/dispatches/${found.dispatch.id}/evidence/${payload.elementId}/detach`, {
method: "POST",
body: { expected_version: found.dispatch.version, ...scope },
});
}
let expected = hostBinding.element.version;
if (payload.source === "attachment") {
const from = bindingByElement(payload.hostElementId);
if (from?.element.id === hostBinding.element.id) expected += 1;
}
const holder = (hostBinding.correspondence?.dispatches || []).find((item) => (
item.channel === "other"
&& !(item.items || []).some((part) => part.role === "host" || part.role === "attachment")
));
if (!holder) {
await api(`/api/v1/elements/${hostBinding.element.id}/dispatches`, {
method: "POST",
body: {
expected_version: expected,
channel: "other",
sent_on: element?.dates?.sent_on || element?.dates?.document_on || null,
counterpart: null,
attachment_element_ids: [],
evidence: [{ element_id: payload.elementId, role, fold: "evidence" }],
historical_gap: false,
capture_editions: false,
...scope,
},
});
} else {
await api(`/api/v1/dispatches/${holder.id}/evidence`, {
method: "POST",
body: {
expected_version: holder.version,
element_id: payload.elementId,
role,
fold: "evidence",
...scope,
},
});
}
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
function openPlace(hostBindingId, payload) {
const host = source.find((item) => item.id === hostBindingId);
if (!host || !payload || host.element.id === payload.elementId) return;
if (payload.source === "attachment" && payload.hostElementId === host.element.id) return;
if (payload.source === "evidence") {
const found = dispatchOf(payload.dispatchId);
if (found?.host?.element.id === host.element.id) return;
}
const item = bindingByElement(payload.elementId);
setDialog({
type: "place-use",
host,
binding: item || { element: { id: payload.elementId, title: payload.title || "Unterlage", version: 1 } },
payload,
});
}
placeUseRef.current = openPlace;
function beginDrag(event, drag) {
if (pending || (event.button != null && event.button !== 0)) return;
event.preventDefault();
dragRef.current = { ...drag, pointerId: event.pointerId, startY: event.clientY, moved: false, index: null };
setDraggingId(drag.bindingId || drag.chapterId || "");
window.addEventListener("pointermove", track);
window.addEventListener("pointerup", release);
window.addEventListener("pointercancel", cancel);
try {
event.currentTarget.setPointerCapture?.(event.pointerId);
} catch {
// The window listeners still follow the pointer when capture is unavailable.
}
}
return (
<div className="contents" ref={rootRef}>
{carrying && (carrying.source === "attachment" || carrying.source === "evidence") ? (
<div className={indicator?.kind === "release" && !indicator.place ? "release-lane is-hot" : "release-lane"} data-release-drop="1">
{indicator?.kind === "release" && indicator.place && indicator.title ? `In ${indicator.title} legen` : "In den Vorgang legen"}
</div>
) : null}
<div className="content-toolbar">
<h2>{viewMode === "chronology" ? "Chronologie" : (activePath || listTitle || "Inhalte")} <span className="count">{shownCount}</span></h2>
<div className="content-toolbar__tools">
{canSort && chapters.length && !picking ? (
<button type="button" className="quiet content-toolbar__pick" onClick={() => { setPicking(true); setPickTarget(onlyChapter || ""); }}>Mehrere einordnen</button>
) : null}
{canSort ? (
<OrderChoice
mode={custom ? "position" : "date"}
direction={direction}
view={viewMode}
disabled={pending}
allowPosition
allowChronology
onChange={saveMode}
/>
) : sortable ? (
<p className="muted">{custom ? "Eigene Reihenfolge" : `Fachliches Datum, ${direction === "desc" ? "absteigend" : "aufsteigend"}`}</p>
) : null}
</div>
</div>
{pending ? <p className="muted">Ordnung wird gespeichert …</p> : null}
<ErrorNote error={error} />
{picking ? (
<div className="pick-bar">
<p>{picked.size} ausgewählt</p>
<label>
Zielkapitel
<select aria-label="Zielkapitel für die Auswahl" value={pickTarget} disabled={pending} onChange={(event) => setPickTarget(event.target.value)}>
<option value="">Ohne Kapitel</option>
{chapters.map((chapter) => (
<option key={chapter.id} value={chapter.id}>{chapterPathLabel(chapters, chapter.id)}</option>
))}
</select>
</label>
<button type="button" disabled={pending || picked.size === 0} onClick={() => placeMany([...picked], pickTarget)}>Einordnen</button>
<button type="button" disabled={pending || picked.size === 0} onClick={() => setDialog({ type: "bulk" })}>Als Anlagen an ein Schriftstück</button>
<button type="button" className="quiet" onClick={() => { setPicking(false); setPicked(new Set()); }}>Auswahl beenden</button>
</div>
) : null}
{viewMode === "chronology" ? (
<Chronology bindings={source} direction={direction} itemHref={itemHref} selectedId={selectedId} onOpen={onOpen} />
) : source.length || chapters.length ? (
renderBlockList()
) : (
<p className="muted">Noch keine Unterlage und keine Notiz.</p>
)}
<Modal wide open={dialog?.type === "attach" || dialog?.type === "bulk"} title={dialog?.type === "attach" ? "Anlagen und Belege" : "Anlagen"} onClose={() => setDialog(null)}>
{dialog?.type === "bulk" && !dialog.host ? (
<form className="stack" onSubmit={async (event) => {
event.preventDefault();
const host = source.find((item) => item.id === new FormData(event.currentTarget).get("host"));
const ids = [...picked].map((id) => source.find((item) => item.id === id)).filter((item) => item && item.id !== host?.id).map((item) => item.element.id);
if (!host || !ids.length) return;
setPending(true);
setError("");
try {
await api(`/api/v1/elements/${host.element.id}/attachments`, {
method: "POST",
body: {
expected_version: host.element.version,
attachment_element_ids: ids,
fold: "attachment",
...scopeBody(actionContext(), containerKind, containerId),
},
});
setDialog(null);
setPicked(new Set());
setPicking(false);
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}}>
<p>Die ausgewählten Unterlagen werden Anlagen dieses Schriftstücks und verschwinden aus der normalen Liste. Zurückziehen legt sie wieder dorthin.</p>
<label>
Schriftstück
<select name="host" defaultValue="">
<option value="">Schriftstück wählen</option>
{source.map((item) => <option key={item.id} value={item.id}>{item.element.title}</option>)}
</select>
</label>
<button type="submit" disabled={pending}>Als Anlagen zuordnen</button>
</form>
) : null}
{dialog?.type === "attach" && dialog.host ? (
<StructureAssignDialog
host={source.find((item) => item.id === dialog.host.id) || dialog.host}
bindings={source}
chapters={chapters}
scope={scopeBody(actionContext(), containerKind, containerId)}
pending={pending}
onClose={() => setDialog(null)}
onDone={() => onChange()}
/>
) : null}
</Modal>
<Modal open={dialog?.type === "dispatch"} title="Versand dokumentieren" onClose={() => setDialog(null)}>
{dialog?.type === "dispatch" ? (
<DispatchDialog
host={dialog.host}
scope={scopeBody(actionContext(), containerKind, containerId)}
pending={pending}
onClose={() => setDialog(null)}
onDone={() => { setDialog(null); onChange(); }}
/>
) : null}
</Modal>
<Modal open={dialog?.type === "place-use"} title="Ablegen" onClose={() => setDialog(null)}>
{dialog?.type === "place-use" ? (
<div className="stack">
<p><strong>{dialog.payload.title || dialog.binding.element.title}</strong> an <strong>{dialog.host.element.title}</strong></p>
<button type="button" disabled={pending} onClick={async () => {
await dropAttachment(dialog.host, dialog.payload);
setDialog(null);
}}>Als Anlage</button>
<button type="button" disabled={pending} onClick={async () => {
await placeReceipt(dialog.host, dialog.payload, dialog.binding.element);
setDialog(null);
}}>Als Beleg</button>
<button type="button" className="quiet" onClick={() => setDialog(null)}>Abbrechen</button>
</div>
) : null}
</Modal>
<Modal open={dialog?.type === "evidence"} title="Beleg zuordnen" onClose={() => setDialog(null)}>
{dialog?.type === "evidence" ? (
<EvidenceDialog
element={dialog.binding.element}
hosts={dialog.hosts || source.filter((item) => item.element.id !== dialog.binding.element.id)}
presetDispatchId={dialog.dispatchId}
replace={dialog.replace || null}
scope={scopeBody(actionContext(), containerKind, containerId)}
pending={pending}
onClose={() => setDialog(null)}
onDone={() => onChange()}
/>
) : null}
</Modal>
</div>
);
function renderBlockList() {
const blocks = [...visibleRoots];
if (!onlyChapter && loose) blocks.push(loose);
return blocks.map((section) => renderBlock(section, 0, Boolean(onlyChapter && section.id === onlyChapter)));
}
function renderBlock(section, depth, hideHead) {
const siblings = section.id === "loose" ? [] : siblingChapterIds(chapters, section.id);
const siblingIndex = siblings.indexOf(section.id);
const fromSiblings = siblingChapterIds(chapters, draggingId);
const fromIndex = fromSiblings.indexOf(draggingId);
const expanded = !folded.has(section.id);
const movable = canMoveChapters && section.id !== "loose" && siblings.length > 1;
const classes = ["content-section"];
if (depth) classes.push("chapter-nest");
if (section.title) classes.push("content-section--group");
if (draggingId === section.id) classes.push("is-dragging");
if (!expanded) classes.push("is-collapsed");
if (indicator?.kind === "release" && indicator.place && (indicator.chapterId || "loose") === section.id) classes.push("is-release-target");
const sameParent = (indicator?.parentId || "") === (section.parentId || "");
const insertBefore = indicator?.kind === "chapter" && sameParent && fromIndex > indicator.index && siblingIndex === indicator.index;
const insertAfter = indicator?.kind === "chapter" && sameParent && fromIndex >= 0 && fromIndex < indicator.index && siblingIndex === indicator.index;
const blockedParents = new Set([section.id, ...descendantChapterIds(chapters, section.id)]);
return (
<section
key={section.id}
className={classes.join(" ")}
data-section={section.id}
data-chapter={section.id === "loose" ? undefined : section.id}
data-chapter-title={section.title || ""}
data-chapter-parent={section.parentId || ""}
>
{insertBefore ? <div className="insert-line" aria-hidden="true" /> : null}
{section.title && !hideHead ? (
<div
className={movable ? "chapter-head is-movable" : "chapter-head"}
draggable={movable && !pending}
onPointerDownCapture={(event) => {
if (!movable) return;
if (event.target.closest("input, textarea, select, a, button, label, .chapter-move, .chapter-date, .chapter-menu")) return;
beginDrag(event, { kind: "chapter", chapterId: section.id, parentId: section.parentId || "" });
}}
onDragStart={(event) => {
if (!movable || event.target.closest("input, textarea, select, a, button, label, .chapter-move, .chapter-menu")) {
event.preventDefault();
return;
}
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", section.id);
markHtml5({ kind: "chapter", chapterId: section.id, parentId: section.parentId || "" });
setDraggingId(section.id);
}}
onDragEnd={endHtml5}
>
{movable ? (
<span className="handle" aria-hidden="true">
<span className="handle__grip" />
</span>
) : null}
<ChapterHeading
section={section}
count={countLabel(sectionCounts(section).direct, sectionCounts(section).nested)}
expanded={expanded}
movable={movable}
canEdit={canEdit && section.id !== "loose"}
canDate={canSort && section.id !== "loose"}
pending={pending}
siblingIndex={siblingIndex}
siblingCount={siblings.length}
chapters={chapters}
blockedParents={blockedParents}
version={record.version}
orderContext={orderContext}
onToggle={() => setFolded((current) => {
const next = new Set(current);
if (next.has(section.id)) next.delete(section.id);
else next.add(section.id);
return next;
})}
onRename={() => renameChapter(section)}
onRemove={() => removeChapter(section)}
onDate={(value) => saveChapterDate(section.id, value)}
onMove={(delta) => moveChapter(section.id, delta)}
onAddSubchapter={onAddSubchapter}
onAddContent={section.id === "loose" ? null : onAddContent}
onChange={onChange}
onError={setError}
onPending={setPending}
/>
</div>
) : null}
{expanded && section.title && !section.items.length && !section.children?.length ? <p className="muted">Noch nichts in diesem Kapitel.</p> : null}
{expanded && picking && section.items.length ? (
<button type="button" className="quiet" onClick={() => setPicked((current) => {
const next = new Set(current);
section.items.forEach((item) => next.add(item.id));
return next;
})}>Einträge dieses Kapitels auswählen</button>
) : null}
{expanded ? <ol className="preview-list">
{section.items.filter((binding) => binding?.element).map((binding, index, rows) => {
const element = binding.element;
const href = itemHref(binding);
const text = blurb(element);
const sourceSymbol = contentSourceSymbol(element);
const way = directionWord(binding.communication?.direction) || "Keine Angabe";
const party = counterpartLabel(element, binding.communication?.direction);
const facts = [party, formatDate(fachDate(element)), sourceLabel(element), way].filter(Boolean).join(" · ");
const samePiece = hostMark(binding);
const originText = binding.origin && section.title && !binding.origin.includes(section.title)
? `${binding.origin}${binding.shared ? " · weitere Einbindung" : ""}`
: binding.origin && !section.title
? `${binding.origin}${binding.shared ? " · weitere Einbindung" : ""}`
: "";
const assignDropId = canEdit ? binding.id : "";
const rowClass = [
"preview-row",
draggingId === binding.id ? "is-dragging" : "",
carrying && (binding.id === carrying.bindingId || binding.id === carrying.hostBindingId) ? "is-carry-source" : "",
selectedId === binding.id ? "is-selected" : "",
picking && picked.has(binding.id) ? "is-picked" : "",
picking ? "preview-row--picking" : "",
(canEdit || (canSort && custom)) ? "preview-row--ordered" : "",
].filter(Boolean).join(" ");
function openFromList(event) {
const row = event.currentTarget.closest(".preview-row");
if (row?.dataset.dragged === "1") {
delete row.dataset.dragged;
event.preventDefault();
return;
}
if (!onOpen || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0) return;
event.preventDefault();
onOpen(binding);
}
return (
<li
key={binding.id}
data-binding={binding.id}
className={rowClass}
>
{indicator?.kind === "order" && indicator?.sectionId === section.id && indicator.index === index ? <div className="insert-line" /> : null}
{picking ? (
<label className="pick-box">
<input
type="checkbox"
checked={picked.has(binding.id)}
aria-label={`${element.title} auswählen`}
onChange={() => setPicked((current) => {
const next = new Set(current);
if (next.has(binding.id)) next.delete(binding.id);
else next.add(binding.id);
return next;
})}
/>
</label>
) : null}
{canEdit ? (
<DirectionControl
direction={directionValue(binding.communication)}
title={element.title}
disabled={pending}
onChange={(value) => saveRowDirection(binding, value)}
/>
) : (
<DirectionColumn direction={binding.communication?.direction} />
)}
{canEdit || (canSort && custom) ? (
<button
type="button"
className="handle"
aria-label={canEdit && canSort && custom
? `${element.title} ziehen, zuordnen oder sortieren`
: canEdit
? `${element.title} zuordnen`
: `${element.title} ziehen`}
draggable={false}
disabled={pending || picking}
onPointerDown={(event) => {
event.stopPropagation();
if (!canEdit || picking) {
if (canSort && custom) beginDrag(event, { bindingId: binding.id, sectionId: section.id });
return;
}
beginCarryPointer(event, {
source: "list",
elementId: element.id,
bindingId: binding.id,
title: element.title,
reorder: canSort && custom ? { bindingId: binding.id, sectionId: section.id } : null,
});
}}
>
<span className="handle__grip" aria-hidden="true" />
</button>
) : null}
<EntryMark
element={element}
context={context}
dropId={assignDropId}
hot={indicator?.kind === "use" && indicator.bindingId === binding.id}
/>
<UnitDetail
binding={binding}
canEdit={canEdit}
pending={pending}
scope={scopeBody(actionContext(), containerKind, containerId)}
onCarryStart={beginCarryPointer}
onOpen={(elementId) => {
const found = source.find((item) => item.element?.id === elementId);
if (found) onOpen?.(found);
}}
onDetach={(elementId) => releaseToList({
source: "attachment",
elementId,
hostElementId: element.id,
})}
onDetachEvidence={(proof, dispatch) => releaseToList({
source: "evidence",
elementId: proof.element_id,
dispatchId: dispatch.id,
})}
onUnfold={async (elementId) => {
const found = source.find((item) => item.element?.id === elementId);
if (!found) return;
setPending(true);
setError("");
try {
await restoreFold(found.id, found.element.version, scopeBody(actionContext(), containerKind, containerId));
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}}
>
{(switches, lists) => (
<div className="preview-row__body">
<div className="preview-row__headline">
<Link
className="preview-row__title"
to={href}
draggable={false}
aria-current={selectedId === binding.id ? "true" : undefined}
onClick={openFromList}
>
<strong>{element.title}</strong>
</Link>
{switches}
</div>
<div className="preview-row__meta">
{sourceSymbol ? (
<span className="source-mark">
<TypeGlyph name={sourceSymbol} tone="light" size={16} />
<TypeGlyph name={sourceSymbol} tone="dark" size={16} />
</span>
) : null}
<span className="preview-row__facts">{facts}</span>
<BezugMenu element={element} source={source} onOpen={onOpen} itemHref={itemHref} canEdit={canEdit} onClearBezug={clearBezug} />
</div>
{text ? (
<Link className="preview-row__text" to={href} draggable={false} onClick={openFromList}>{text}</Link>
) : null}
{samePiece ? <span className="preview-row__origin">{samePiece}</span> : null}
{originText ? <span className="preview-row__origin">{originText}</span> : null}
{lists}
</div>
)}
</UnitDetail>
<EntryActions
element={element}
binding={binding}
source={source}
chapters={chapters}
index={index}
lastIndex={rows.length - 1}
canEdit={canEdit}
canDestroy={canDestroy}
canSort={canSort}
custom={custom}
pending={pending}
onSetBezug={setBezug}
onClearBezug={clearBezug}
onRenameTitle={renameElement}
onRemove={removeBinding}
onMove={move}
onPlaceChapter={placeChapter}
onAttach={(row) => setDialog({ type: "attach", host: row })}
onDispatch={(row) => setDialog({ type: "dispatch", host: row })}
/>
</li>
);
})}
{indicator?.kind === "order" && indicator?.sectionId === section.id && indicator.index === section.items.length ? <li className="insert-line" aria-hidden="true" /> : null}
</ol> : null}
{expanded && section.children?.length ? (
<div className="chapter-children">
{section.children.map((child) => renderBlock(child, depth + 1, false))}
</div>
) : null}
{insertAfter ? <div className="insert-line" aria-hidden="true" /> : null}
</section>
);
}
}
export function OrderChoice({ mode, direction, view = "structure", disabled, allowPosition = false, allowChronology = false, onChange }) {
const value = view === "chronology"
? (direction === "desc" ? "chrono-desc" : "chrono-asc")
: mode === "position" ? "position" : direction === "desc" ? "date-desc" : "date-asc";
return (
<label className="order-choice">
<span>{allowChronology ? "Ansicht" : "Ordnung"}</span>
<select
aria-label="Ansicht und Ordnung der Inhalte"
value={value}
disabled={disabled}
onChange={(event) => {
const next = event.target.value;
const kept = mode === "position" ? "position" : "date";
if (next === "chrono-asc") onChange(kept, "asc", "chronology");
else if (next === "chrono-desc") onChange(kept, "desc", "chronology");
else if (next === "position") onChange("position", direction === "desc" ? "desc" : "asc", "structure");
else onChange("date", next === "date-desc" ? "desc" : "asc", "structure");
}}
>
<option value="date-asc">{allowChronology ? "Gliederung, Datum aufsteigend" : "Fachliches Datum, aufsteigend"}</option>
<option value="date-desc">{allowChronology ? "Gliederung, Datum absteigend" : "Fachliches Datum, absteigend"}</option>
{allowPosition ? <option value="position">{allowChronology ? "Gliederung, eigene Reihenfolge" : "Eigene Reihenfolge"}</option> : null}
{allowChronology ? <option value="chrono-asc">Chronologie, aufsteigend</option> : null}
{allowChronology ? <option value="chrono-desc">Chronologie, absteigend</option> : null}
</select>
</label>
);
}
export function CourseList({ items }) {
if (!items) return <p className="muted">Verlauf wird geladen …</p>;
if (!items.length) return <p className="muted">Noch kein fachlicher Verlauf.</p>;
return (
<ol className="timeline">
{items.map((item) => (
<li key={item.id}>
<time>{item.dated ? formatDate(item.document_on) : "Ohne Datum"}</time>
<div>
<strong>{item.title}</strong>
<span>{kindLabel(item.kind)}{item.sent_on ? ` · Versand ${formatDate(item.sent_on)}` : ""}{item.received_on ? ` · Zugang ${formatDate(item.received_on)}` : ""}</span>
</div>
</li>
))}
</ol>
);
}
export function RecordTabs({ coursePath, auditPath }) {
const [tab, setTab] = useState("");
const [course, setCourse] = useState(null);
const [audit, setAudit] = useState(null);
const [cursor, setCursor] = useState(null);
const [error, setError] = useState("");
async function showCourse() {
setTab("course");
if (course) return;
setError("");
try {
const data = await api(coursePath);
setCourse(data.items);
} catch (err) {
setError(err.message);
}
}
async function showAudit(nextCursor) {
setTab("audit");
setError("");
try {
const joiner = auditPath.includes("?") ? "&" : "?";
const data = await api(`${auditPath}${nextCursor ? `${joiner}cursor=${encodeURIComponent(nextCursor)}` : ""}`);
setAudit((current) => (nextCursor ? [...(current || []), ...data.items] : data.items));
setCursor(data.next_cursor);
} catch (err) {
setError(err.message);
}
}
return (
<section className="section">
<div className="order-bar">
<button type="button" className={tab === "course" ? "" : "quiet"} onClick={showCourse}>Fachlicher Verlauf</button>
<button type="button" className={tab === "audit" ? "" : "quiet"} onClick={() => showAudit("")}>Änderungsprotokoll</button>
</div>
<ErrorNote error={error} />
{tab === "course" ? <CourseList items={course} /> : null}
{tab === "audit" ? <AuditLog items={audit} nextCursor={cursor} onMore={() => showAudit(cursor)} /> : null}
</section>
);
}
export function AuditLog({ items, nextCursor, onMore }) {
if (!items) return <p className="muted">Protokoll wird geladen …</p>;
if (!items.length) return <p className="muted">Noch kein Eintrag.</p>;
return (
<div className="stack">
<ol className="timeline">
{items.map((item) => (
<li key={item.id}>
<time>{formatStamp(item.occurred_at)}</time>
<div>
<strong>{item.label}</strong>
<span>{item.title}{item.actor_display_name ? ` · ${item.actor_display_name}` : ""}</span>
</div>
</li>
))}
</ol>
{nextCursor ? <button type="button" className="quiet" onClick={onMore}>Weitere Einträge</button> : null}
</div>
);
}
function contentChoices(record) {
const rows = [...(record?.bindings || [])];
for (const group of record?.contained || []) rows.push(...(group.bindings || []));
const seen = new Set();
return rows.flatMap((binding) => {
const element = binding.element;
if (!element?.id || seen.has(element.id)) return [];
seen.add(element.id);
return [{ id: element.id, title: element.title }];
});
}
function taskContextBody(task, context) {
const taskContext = task.action_context || context;
return taskContext ? { context: taskContext } : {};
}
export function WorkLists({ record, context, onChange }) {
const links = record.task_deadline_links || [];
const tasks = record.tasks || [];
const elements = contentChoices(record);
async function complete(task) {
const body = { expected_version: task.version, status: "done" };
const taskContext = task.action_context || context;
if (taskContext) body.context = taskContext;
await api(`/api/v1/tasks/${task.id}`, { method: "PATCH", body });
onChange();
}
async function fulfill(deadline) {
const body = { expected_version: deadline.version };
if (context) body.context = context;
await api(`/api/v1/deadlines/${deadline.id}/fulfill`, { method: "POST", body });
onChange();
}
const tasksFor = (deadlineId) => tasks.filter((task) => links.some((link) => link.deadline_id === deadlineId && link.task_id === task.id));
const linkedIds = new Set(links.map((link) => link.task_id));
const loose = tasks.filter((task) => !linkedIds.has(task.id));
async function assign(task, deadline) {
await api(`/api/v1/tasks/${task.id}/deadline-links`, {
method: "POST",
body: { deadline_id: deadline.id, ...taskContextBody(task, context) },
});
onChange();
}
return (
<div className="stack">
<p className="muted">Eine Frist ist der maßgebliche Termin. Mehrere Aufgaben können davor liegen. Erledigen einer Aufgabe erfüllt die Frist nicht.</p>
<div>
<h3>Fristen</h3>
{record.deadlines?.length ? (
<ul className="work">
{record.deadlines.map((deadline) => {
const assigned = tasksFor(deadline.id);
const available = tasks.filter((task) => !assigned.some((item) => item.id === task.id));
return (
<li key={deadline.id}>
<div>
<strong>{deadline.title}</strong>
<span>{deadline.status === "fulfilled" ? "Erfüllt" : "Offen"} · {formatDate(deadline.due_on)}{deadline.matter_title ? ` · ${deadline.matter_title}` : ""}</span>
{assigned.length ? (
<ul className="task-under">
{assigned.map((task) => (
<TaskRow key={task.id} task={task} tasks={tasks} elements={elements} context={context} onComplete={complete} onChange={onChange} />
))}
</ul>
) : <small>Noch keine Aufgabe vor dieser Frist.</small>}
{available.length ? (
<label className="task-assign">
Aufgabe zuordnen
<select value="" onChange={(event) => { const task = available.find((item) => item.id === event.target.value); if (task) assign(task, deadline); }}>
<option value="">Auswählen</option>
{available.map((task) => <option key={task.id} value={task.id}>{task.title}</option>)}
</select>
</label>
) : null}
</div>
{deadline.status === "open" ? <button type="button" onClick={() => fulfill(deadline)}>Frist erfüllen</button> : null}
</li>
);
})}
</ul>
) : <p className="muted">Keine Frist.</p>}
</div>
<div>
<h3>Aufgaben ohne Frist</h3>
{loose.length ? (
<ul className="work">
{loose.map((task) => (
<li key={task.id}>
<TaskRow task={task} tasks={tasks} elements={elements} context={context} onComplete={complete} onChange={onChange} />
</li>
))}
</ul>
) : <p className="muted">Keine Aufgabe ohne Frist.</p>}
</div>
</div>
);
}
function TaskRow({ task, tasks, elements, context, onComplete, onChange }) {
const [elementIds, setElementIds] = useState((task.elements || []).map((item) => item.id));
const [dependsOn, setDependsOn] = useState("");
const others = tasks.filter((item) => item.id !== task.id);
async function saveElements(next) {
setElementIds(next);
await api(`/api/v1/tasks/${task.id}/elements`, {
method: "PUT",
body: { element_ids: next, ...taskContextBody(task, context) },
});
onChange();
}
async function addDependency(event) {
const id = event.target.value;
setDependsOn("");
if (!id) return;
await api(`/api/v1/tasks/${task.id}/dependencies`, {
method: "POST",
body: { depends_on_task_id: id, ...taskContextBody(task, context) },
});
onChange();
}
return (
<div className="task-row">
<div>
<strong>{task.title}</strong>
<span>{task.status === "done" ? "Erledigt" : "Offen"}{task.due_on ? ` · Arbeitstermin ${formatDate(task.due_on)}` : ""}</span>
{(task.depends_on || []).length ? <small>Hängt ab von {task.depends_on.map((item) => item.title).join(", ")}.</small> : null}
{(task.elements || []).length ? <small>Bezieht sich auf {task.elements.map((item) => item.title).join(", ")}.</small> : null}
</div>
{task.status === "open" && task.rights?.edit !== false ? <button type="button" onClick={() => onComplete(task)}>Erledigen</button> : null}
{task.rights?.edit !== false ? (
<details className="row-menu">
<summary>Bezüge</summary>
<label>
Hängt ab von
<select value={dependsOn} onChange={addDependency}>
<option value="">Aufgabe wählen</option>
{others.map((item) => <option key={item.id} value={item.id}>{item.title}</option>)}
</select>
</label>
<fieldset className="task-elements">
<legend>Inhalte</legend>
{elements.length ? elements.map((element) => (
<label key={element.id}>
<input
type="checkbox"
checked={elementIds.includes(element.id)}
onChange={(event) => {
const next = event.target.checked ? [...elementIds, element.id] : elementIds.filter((id) => id !== element.id);
saveElements(next);
}}
/>
{element.title}
</label>
)) : <span>In diesem Objekt liegt noch kein Inhalt.</span>}
</fieldset>
</details>
) : null}
</div>
);
}
export function SurfaceView({ view, coursePath, auditPath }) {
const [course, setCourse] = useState(null);
const [audit, setAudit] = useState(null);
const [cursor, setCursor] = useState(null);
const [error, setError] = useState("");
useEffect(() => {
setCourse(null);
setAudit(null);
setCursor(null);
}, [coursePath, auditPath]);
useEffect(() => {
if (view !== "course") return undefined;
let alive = true;
api(coursePath).then((data) => {
if (alive) setCourse(data.items);
}).catch((err) => {
if (alive) setError(err.message);
});
return () => {
alive = false;
};
}, [view, coursePath]);
async function showAudit(nextCursor) {
const joiner = auditPath.includes("?") ? "&" : "?";
const data = await api(`${auditPath}${nextCursor ? `${joiner}cursor=${encodeURIComponent(nextCursor)}` : ""}`);
setAudit((current) => (nextCursor ? [...(current || []), ...data.items] : data.items));
setCursor(data.next_cursor);
}
useEffect(() => {
if (view !== "audit") return undefined;
let alive = true;
showAudit("").catch((err) => {
if (alive) setError(err.message);
});
return () => {
alive = false;
};
}, [view, auditPath]);
if (view !== "course" && view !== "audit") return null;
return (
<div>
<ErrorNote error={error} />
{view === "course" ? <CourseList items={course} /> : <AuditLog items={audit} nextCursor={cursor} onMore={() => showAudit(cursor).catch((err) => setError(err.message))} />}
</div>
);
}