import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { api, fetchFile, fetchPaperless } from "../api.js";
import { Modal } from "./Modal.jsx";
import { ErrorNote } from "./widgets.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}`;
}
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?.title || chapterTitle;
return (
Ziel: {label}
{namedChapter ? <> · Kapitel {namedChapter}> : null}
);
}
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 }) {
if (!items?.length) return null;
return (
);
}
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 (
{item.kind_label || "Eintrag"}
{item.title}
{!nested && item.parent_title ? in {item.parent_title} : null}
{item.status === "open" ? "Offen" : item.status === "closed" ? "Geschlossen" : ""}
{kids.length ? (
{kids.map((child) => (
))}
) : null}
);
}
export function RecordTree({ items, parentKey, hrefFor }) {
const { roots, children } = nestRecords(items, parentKey);
if (!roots.length) return null;
return (
{roots.map((item) => (
))}
);
}
function sectionsOf(chapters, bindings) {
const buckets = new Map();
const loose = [];
for (const binding of bindings || []) {
if (binding.chapter_id && chapters.some((chapter) => chapter.id === binding.chapter_id)) {
const list = buckets.get(binding.chapter_id) || [];
list.push(binding);
buckets.set(binding.chapter_id, list);
} else {
loose.push(binding);
}
}
const sections = (chapters || []).map((chapter) => ({
id: chapter.id,
title: chapter.title,
documentOn: chapter.document_on || "",
items: buckets.get(chapter.id) || [],
}));
if (sections.length && loose.length) {
sections.push({ id: "loose", title: "Ohne Kapitel", documentOn: "", items: loose });
} else if (!sections.length) {
sections.push({ id: "loose", title: "", documentOn: "", items: loose });
}
return sections;
}
export function matterOpenHref(item) {
const contexts = item?.contexts || [];
if (contexts.some((entry) => entry.kind === "direct")) return `/matters/${item.id}`;
const context = contexts.find((entry) => entry.kind === "case");
if (!context) return `/matters/${item.id}`;
return `/matters/${item.id}?context_kind=case&context_id=${context.id}`;
}
export function Placements({ items }) {
if (!items?.length) return null;
const current = items.find((item) => item.current);
return (
In Akte:
{items.map((item, index) => (
{index ? · : null}
{item.label.replaceAll("Unterakte ", "").replaceAll("Akte ", "")}
))}
{current ? · aktueller Handlungskontext : · Handlungskontext direkt, solange keine Akte gewählt ist}
);
}
export function ObjectMenu({ view, onView, children }) {
const [open, setOpen] = useState(false);
function choose(next) {
setOpen(false);
onView(next);
}
return (
<>
setOpen(false)}>
setOpen(false)}>
{children}
>
);
}
export function WorkSwitch({ view, onView }) {
return (
{view !== "contents" && view !== "work" ? (
) : null}
);
}
function sourceLabel(element) {
if (element.kind === "note") return "Notiz";
if (element.kind === "external_ref") return element.external?.source === "paperless" ? "Paperless" : "Referenz";
if (element.file?.content_type === "application/pdf") return "PDF";
if (element.file?.content_type?.startsWith("image/")) return "Bild";
if (element.kind === "file") return "Datei";
return kindLabel(element.kind);
}
function blurb(element) {
return element.summary || element.excerpt || "";
}
function Thumb({ element, context }) {
const [url, setUrl] = useState("");
const [media, setMedia] = useState("");
const [failed, setFailed] = useState(false);
useEffect(() => {
if (!element.preview?.available) return undefined;
let alive = true;
let current = "";
const load = element.preview.source === "paperless" ? fetchPaperless(element.id, context) : fetchFile(element.id, context);
load.then((blob) => {
if (!alive) return;
current = URL.createObjectURL(blob);
setUrl(current);
if (blob.type.startsWith("image/")) setMedia("image");
else if (blob.type.includes("pdf")) setMedia("pdf");
else setMedia("other");
}).catch(() => {
if (alive) setFailed(true);
});
return () => {
alive = false;
if (current) URL.revokeObjectURL(current);
};
}, [element.id, element.preview?.available, element.preview?.source, context?.kind, context?.id]);
if (element.kind === "note") return Notiz;
if (url && media === "image") return
;
if (url && media === "pdf") return ;
if (failed) return Vorschau nicht verfügbar;
if (element.preview?.available) return Vorschau wird geladen;
return Keine Vorschau;
}
export function ContentBoard({
record,
bindings,
context,
containerKind,
containerId,
sortable = true,
onChange,
itemHref,
onlyChapter = "",
}) {
const source = bindings || record?.bindings || [];
const chapters = record?.chapters || [];
const [error, setError] = useState("");
const [pending, setPending] = useState(false);
const [draggingId, setDraggingId] = useState("");
const [indicator, setIndicator] = useState(null);
const dragRef = useRef(null);
const rootRef = useRef(null);
const custom = record?.content_order === "position";
const direction = record?.content_order_dir === "desc" ? "desc" : "asc";
const sections = sectionsOf(chapters, source);
const visibleSections = onlyChapter ? sections.filter((section) => section.id !== "loose") : sections;
const canSort = sortable && record?.rights?.edit;
const canMoveChapters = Boolean(canSort && chapters.length > 1);
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" || !dragRef.current) return;
dragRef.current = null;
setDraggingId("");
setIndicator(null);
}
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, []);
useEffect(() => {
const node = rootRef.current;
if (!node) return undefined;
function place(event) {
const drag = dragRef.current;
if (!drag?.html5) return;
event.preventDefault();
if (drag.kind === "chapter") {
drag.index = chapterUnder(event.clientY);
setIndicator({ sectionId: drag.chapterId, index: drag.index, kind: "chapter" });
return;
}
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 });
}
function drop(event) {
if (!dragRef.current?.html5) return;
place(event);
finishDragRef.current(dragRef.current);
}
node.addEventListener("dragover", place);
node.addEventListener("drop", drop);
return () => {
node.removeEventListener("dragover", place);
node.removeEventListener("drop", drop);
};
}, []);
async function saveMode(mode, nextDirection) {
setError("");
setPending(true);
try {
await api(`${orderPath}/content-order`, {
method: "PATCH",
body: { expected_version: record.version, mode, direction: nextDirection, ...orderContext },
});
onChange();
} catch (err) {
setError(err.message);
} finally {
setPending(false);
}
}
async function persist(next, version = record.version) {
setError("");
setPending(true);
try {
await api(`${orderPath}/bindings/order`, {
method: "POST",
body: {
expected_version: version,
binding_ids: next.flatMap((section) => section.items.map((item) => item.id)),
...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 = chapters.map((chapter) => chapter.id);
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 move(bindingId, delta) {
const next = sections.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 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]") || [])];
const hit = nodes.find((node) => {
const rect = node.getBoundingClientRect();
return clientY >= rect.top && clientY <= rect.bottom;
});
return hit?.getAttribute("data-section") || null;
}
function chapterUnder(clientY) {
const nodes = [...(rootRef.current?.querySelectorAll("[data-chapter] .chapter-head") || [])];
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) {
dragRef.current = null;
setDraggingId("");
setIndicator(null);
if (!drag || !drag.moved || drag.index == null) return;
if (drag.kind === "chapter") {
const ids = chapters.map((chapter) => chapter.id);
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 = sections.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.index = chapterUnder(event.clientY);
setIndicator({ sectionId: drag.chapterId, index: drag.index, kind: "chapter" });
return;
}
drag.targetSectionId = sectionUnder(event.clientY) || drag.sectionId;
drag.index = indexAt(drag.targetSectionId, event.clientY);
setIndicator({ sectionId: drag.targetSectionId, index: drag.index });
}
function release(event) {
const drag = dragRef.current;
window.removeEventListener("pointermove", track);
window.removeEventListener("pointerup", release);
window.removeEventListener("pointercancel", cancel);
if (!drag || drag.html5 || 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) return;
dragRef.current = null;
setDraggingId("");
setIndicator(null);
}, 0);
}
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 (
{canSort ? (
) : sortable ? (
{custom ? "Eigene Reihenfolge" : `Fachliches Datum, ${direction === "desc" ? "absteigend" : "aufsteigend"}`}
) : null}
{pending ?
Ordnung wird gespeichert …
: null}
{source.length || chapters.length ? (
visibleSections.map((section) => {
const chapterIndex = chapters.findIndex((chapter) => chapter.id === section.id);
const expanded = !onlyChapter || section.id === onlyChapter;
const movable = canMoveChapters && section.id !== "loose";
const classes = ["content-section"];
if (draggingId === section.id) classes.push("is-dragging");
if (!expanded) classes.push("is-collapsed");
if (indicator?.kind === "chapter" && chapterIndex === indicator.index && draggingId !== section.id) classes.push("is-chapter-target");
return (
{section.title ? (
{
if (!movable) return;
if (event.target.closest("input, textarea, select, a, label, .chapter-move")) return;
beginDrag(event, { kind: "chapter", chapterId: section.id });
}}
onDragStart={(event) => {
if (!movable || event.target.closest("input, textarea, select, a, label, .chapter-move")) {
event.preventDefault();
return;
}
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", section.id);
markHtml5({ kind: "chapter", chapterId: section.id });
setDraggingId(section.id);
}}
onDragEnd={endHtml5}
>
{movable ? (
) : null}
{section.title}
{section.documentOn ? {formatDate(section.documentOn)} : null}
{movable ? (
) : null}
{canSort && section.id !== "loose" ? (
) : null}
) : null}
{expanded && section.title && !section.items.length ? Noch nichts in diesem Kapitel.
: null}
{expanded ?
{section.items.map((binding, index) => {
const element = binding.element;
const href = itemHref(binding);
const text = blurb(element);
return (
-
{indicator?.sectionId === section.id && indicator?.kind !== "chapter" && indicator.index === index ? : null}
{canSort && custom ? (
) : null}
{element.title}
{formatDate(fachDate(element))} · {sourceLabel(element)}
{text ? {text} : null}
{binding.origin ? {binding.origin}{binding.shared ? " · weitere Einbindung" : ""} : null}
{(canSort && custom) || (canSort && chapters.length) ? (
{canSort && custom ? (
Reihenfolge
) : null}
{canSort && chapters.length ? (
In Kapitel einordnen
) : null}
) : null}
);
})}
{indicator?.sectionId === section.id && indicator?.kind !== "chapter" && indicator.index === section.items.length ? : null}
: null}
);
})
) : (
Noch keine Unterlage und keine Notiz.
)}
);
}
export function OrderChoice({ mode, direction, disabled, allowPosition = false, onChange }) {
const value = mode === "position" ? "position" : direction === "desc" ? "date-desc" : "date-asc";
return (
);
}
export function CourseList({ items }) {
if (!items) return Verlauf wird geladen …
;
if (!items.length) return Noch kein fachlicher Verlauf.
;
return (
{items.map((item) => (
-
{item.title}
{kindLabel(item.kind)}{item.sent_on ? ` · Versand ${formatDate(item.sent_on)}` : ""}{item.received_on ? ` · Zugang ${formatDate(item.received_on)}` : ""}
))}
);
}
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 (
{tab === "course" ? : null}
{tab === "audit" ? showAudit(cursor)} /> : null}
);
}
export function AuditLog({ items, nextCursor, onMore }) {
if (!items) return Protokoll wird geladen …
;
if (!items.length) return Noch kein Eintrag.
;
return (
{items.map((item) => (
-
{item.label}
{item.title}{item.actor_display_name ? ` · ${item.actor_display_name}` : ""}
))}
{nextCursor ?
: null}
);
}
export function WorkLists({ record, context, onChange }) {
const linked = new Set((record.task_deadline_links || []).map((item) => item.task_id));
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();
}
return (
Erledigen und Erfüllen bleiben getrennte Aktionen.
Aufgaben
{record.tasks?.length ? (
) :
Keine Aufgabe.
}
Fristen
{record.deadlines?.length ? (
) :
Keine Frist.
}
);
}
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 (
{view === "course" ?
:
showAudit(cursor).catch((err) => setError(err.message))} />}
);
}